From 83a099ab25b0e6be5b731f9bb1089a75a445a83a Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 11:53:14 +0200 Subject: [PATCH 01/61] Add recursive local file search to KSwitcher Files Refs #85 --- FILES-UI.md | 10 +++ resources/files.rc | 13 ++++ src/files_find.inl | 75 +++++++++++++++++++++ src/files_find_scan.inl | 74 +++++++++++++++++++++ src/files_main.cpp | 141 ++++++++++++++++++++++++++++++++++++---- 5 files changed, 301 insertions(+), 12 deletions(-) create mode 100644 src/files_find.inl create mode 100644 src/files_find_scan.inl diff --git a/FILES-UI.md b/FILES-UI.md index 3dd6c60..b9d19ef 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -429,6 +429,16 @@ Warning і початковий фокус на No. ## Панелі +- **F9 → Commands → Find files** або **Alt+F7** запускає фоновий пошук + файлів у поточній локальній папці та її підпапках. Поле приймає повне + ім’я або маску без урахування регістру. `*` відповідає довільній + послідовності символів, `?` — одному символу. Приховані та системні + елементи можна включити прапорцем. Пошук не обходить junction та інші + посилання на каталоги. Esc під час пошуку зупиняє обхід і показує знайдене. + Результати відкриваються в тій самій панелі з відносними шляхами. + Enter або подвійний клік відкриває папку й ставить курсор на файл. + Esc у результатах повертає вихідну папку, курсор і позначки. + - Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів у відкритих локальних папках. Фокус залишається там, де був, а курсор лишається на поточному елементі, якщо той ще існує. diff --git a/resources/files.rc b/resources/files.rc index 50e927d..1736ae7 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -407,3 +407,16 @@ BEGIN LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13 CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17 END + +116 DIALOGEX 0, 0, 300, 98 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "Find files" +FONT 10, "Consolas" +BEGIN + LTEXT "File &name or mask", 483, 16, 18, 268, 12 + FAR_EDIT(480, 0, 16, 32, 268, 15) + AUTOCHECKBOX "Include &hidden and system files", 481, 16, 53, 268, 12 + LTEXT "", 482, 10, 69, 1, 1, NOT WS_VISIBLE + CONTROL "&Find", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 68, 73, 80, 17 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 73, 80, 17 +END diff --git a/src/files_find.inl b/src/files_find.inl new file mode 100644 index 0000000..66f9d51 --- /dev/null +++ b/src/files_find.inl @@ -0,0 +1,75 @@ +constexpr int findMask=480, findHidden=481, findFooter=482, findLabel=483; + +INT_PTR CALLBACK findFilesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_DRAWITEM) + { + paintDialogButton(*reinterpret_cast(lp),RGB(192,192,192),RGB(0,0,0),true); + return TRUE; + } + if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Find files ",false,{findFooter})) + return painted; + if(message==WM_INITDIALOG) + { + const auto &options=*reinterpret_cast(lp); + SetWindowLongPtrW(dialog,DWLP_USER,lp); + prepareTextDialog(dialog); + layoutDialogContent(dialog,findLabel); + for(const auto id:{IDOK,IDCANCEL}) + { + const auto button=GetDlgItem(dialog,id); + SetWindowPos(button,nullptr,0,0,farDialogButtonWidth(button),textHeight, + SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE); + } + layoutDialogButtons(dialog,findFooter,{IDOK,IDCANCEL}); + installFarCheckbox(GetDlgItem(dialog,findHidden),FarCheckboxSurface::gray); + SendDlgItemMessageW(dialog,findMask,EM_SETLIMITTEXT,255,0); + SetDlgItemTextW(dialog,findMask,options.mask.c_str()); + CheckDlgButton(dialog,findHidden,options.includeHidden?BST_CHECKED:BST_UNCHECKED); + SetFocus(GetDlgItem(dialog,findMask)); + SendDlgItemMessageW(dialog,findMask,EM_SETSEL,0,-1); + return FALSE; + } + if(message==WM_COMMAND && LOWORD(wp)==IDOK) + { + auto &options=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + wchar_t mask[256]{}; + GetDlgItemTextW(dialog,findMask,mask,static_cast(std::size(mask))); + if(std::wstring_view(mask).find_first_of(L"/\\:")!=std::wstring_view::npos) + { + showFilesNotice(dialog,L"Enter a file name or mask without a path.",L"Find files"); + SetFocus(GetDlgItem(dialog,findMask)); + return TRUE; + } + options.mask=*mask?mask:L"*"; + options.includeHidden=IsDlgButtonChecked(dialog,findHidden)==BST_CHECKED; + FilesModalDialog::finish(dialog,IDOK); + return TRUE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + return FALSE; +} + +void findLocalFiles(HWND owner,Panel &panel) +{ + if(panel.peer || panel.ftp || panel.directory.empty()) + { + setStatus(L"Find files requires a local folder."); + return; + } + if(panel.scanRequest) + { + setStatus(L"Wait for the current scan to finish."); + return; + } + Panel::FindOptions options; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner, + findFilesDialog,reinterpret_cast(&options))!=IDOK) return; + cancelFolderSizes(panel); + panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)}; + startDirectoryScan(panel); +} diff --git a/src/files_find_scan.inl b/src/files_find_scan.inl new file mode 100644 index 0000000..6600b5a --- /dev/null +++ b/src/files_find_scan.inl @@ -0,0 +1,74 @@ +bool matchesFileMask(std::wstring_view name,std::wstring_view mask) +{ + size_t fileIndex=0, maskIndex=0, star=mask.npos, afterStar=0; + while(fileIndex scanFileMatches(const Panel::ScanRequest &request, + std::atomic_size_t &entriesRead,std::stop_token stop) +{ + auto result=std::make_unique(); + FilesConnection local(nullptr); + std::vector pending{request.directory}; + size_t visited=0; + while(!pending.empty() && !stop.stop_requested()) + { + const auto directory=std::move(pending.back()); + pending.pop_back(); + try + { + listFiles(local,directory,[&](const fs::path &path,const FileInfo &entry) + { + if(stop.stop_requested()) return false; + entriesRead.store(++visited,std::memory_order_relaxed); + if(!request.find->includeHidden && (entry.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))) + return true; + if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY) + { + if(!(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) pending.push_back(path); + } + else if(matchesFileMask(path.filename().native(),request.find->mask)) + { + result->files.push_back(path); + result->metadata.emplace(path,FolderEntryMetadata{entry.attributes,entry.size}); + result->timestamps.emplace(path,entry.modified); + } + return true; + }); + } + catch(const std::system_error &) + { + if(directory==request.directory) + { + result->failure=L"Cannot search folder: "+directory.native(); + return result; + } + result->error=ERROR_PARTIAL_COPY; + } + } + if(stop.stop_requested()) result->error=ERROR_CANCELLED; + result->opened=true; + std::sort(result->files.begin(),result->files.end()); + return result; +} diff --git a/src/files_main.cpp b/src/files_main.cpp index 49d1089..9640daa 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -367,6 +367,15 @@ struct Panel FILE_NOTIFY_CHANGE_ATTRIBUTES|FILE_NOTIFY_CHANGE_SIZE|FILE_NOTIFY_CHANGE_LAST_WRITE); } } watch; + struct FindOptions { std::wstring mask=L"*"; bool includeHidden{}; }; + struct FindOrigin + { + fs::path cursor; + std::set marks; + LRESULT row{}, top{}; + DWORD error{}; + }; + std::optional findOrigin; struct ScanRequest { fs::path directory, selection, fallback; @@ -375,6 +384,7 @@ struct Panel uint64_t statusRevision{}; std::shared_ptr elevated; std::optional ftp; + std::optional find; }; struct ScanResult { @@ -418,6 +428,16 @@ std::wstring panelLocation(const Panel &panel) return (panel.peer?panel.peer->name+L" · ":std::wstring{})+panel.directory.native(); } +bool hasPanelSizeColumn(const Panel &panel) +{ + return panel.wide && !panel.findOrigin; +} + +std::wstring panelCaption(const Panel &panel) +{ + return panel.findOrigin?L"Search results":panelLocation(panel); +} + Panel panels[2]; FilesTerminal terminal; std::mutex pendingTerminalOutputMutex; @@ -1207,7 +1227,7 @@ bool showDirectoryScanProgress(Panel &panel) const auto entries=panel.scanEntriesRead ? panel.scanEntriesRead->load(std::memory_order_relaxed) : 0; auto message=panel.scanSuperseded ? std::wstring(L"Waiting to read…") : panel.scanStop.stop_requested() ? L"Stopping… "+std::to_wstring(entries) : - L"Reading "+std::to_wstring(entries)+L" [Esc]"; + (panel.scanRequest->find?L"Searching ":L"Reading ")+std::to_wstring(entries)+L" [Esc]"; wchar_t displayed[96]{}; GetWindowTextW(status,displayed,std::size(displayed)); if(message!=displayed) setStatus(message); @@ -1999,6 +2019,14 @@ void updateSelectionSummary(const Panel &panel) void showFileDetails(const Panel &panel) { if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return; + if(panel.findOrigin) + { + const auto error=panel.findOrigin->error; + setStatus(std::to_wstring(panel.rows.size())+(error==ERROR_CANCELLED?L" matches (stopped)": + error?L" matches (some folders could not be read)":L" matches")+ + L" · Enter: Go · Esc: Back"); + return; + } if(ftpProfileList(panel)) { setStatus(ftpProfiles.empty()?L"Shift+F4 New connection":L"Shift+F4 New F4 Edit Enter Connect"); @@ -2045,9 +2073,12 @@ void showFileDetails(const Panel &panel) setStatus(details); } +#include "files_find_scan.inl" + std::unique_ptr scanDirectory(const Panel::ScanRequest &request, std::atomic_size_t &entriesRead,std::stop_token stop) { + if(request.find) return scanFileMatches(request,entriesRead,stop); auto result=std::make_unique(); auto &[watch,folders,files,metadata,timestamps,error,opened,failure,ftpInitialDirectory]=*result; const auto &directory=request.directory; @@ -2240,6 +2271,28 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul for(size_t i=0;ierror=error; + previousSelection.clear(); + previousRow=previousTop=0; + markedPaths.clear(); + } + else if(panel.findOrigin) + { + if(sameDirectory) + { + previousSelection=std::move(panel.findOrigin->cursor); + markedPaths=std::move(panel.findOrigin->marks); + previousRow=panel.findOrigin->row; + previousTop=panel.findOrigin->top; + } + panel.findOrigin.reset(); + } panel.directory = directory; panel.peer=std::move(peer); panel.ftp=std::move(request.ftp); @@ -2248,7 +2301,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul cancelFolderSizes(panel); panel.folderSizes.clear(); } - if(partial) panel.watch.reset(); + if(partial || finding) panel.watch.reset(); else if(!sameDirectory || panel.watch.handle==INVALID_HANDLE_VALUE) { panel.watch.reset(); @@ -2261,7 +2314,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul panel.marked.clear(); panel.fileExtensionLength=panel.folderExtensionLength=0; const bool profiles=ftpProfileList(panel); - const bool hasParent=directory.has_relative_path(); + const bool hasParent=!finding && directory.has_relative_path(); const auto rowCount=profiles?ftpProfiles.size():folders.size()+files.size()+hasParent; panel.rows.reserve(rowCount); panel.sizes.reserve(rowCount); @@ -2298,11 +2351,16 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul { if(hasParent) add(directory.parent_path(),L"..",true); for(const auto &folder:folders) add(folder,L"["+folder.filename().wstring()+L"]",true); - for(const auto &file:files) add(file,file.filename().wstring(),false); + for(const auto &file:files) add(file,finding?file.lexically_relative(directory).native():file.filename().native(),false); } - const auto label=panelLocation(panel); + const auto label=panelCaption(panel); SetWindowTextW(panel.path,label.c_str()); InvalidateRect(panel.path,nullptr,FALSE); + if(viewChanged) + { + InvalidateRect(panel.heading,nullptr,FALSE); + InvalidateRect(GetParent(panel.list),nullptr,FALSE); + } if(&panel==&panels[active] && !sameDirectory) layout(GetParent(panel.list),true); auto selected=std::find(panel.rows.begin(),panel.rows.end(),previousSelection); @@ -2326,7 +2384,8 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul if(visible) SendMessageW(panel.list,WM_SETREDRAW,TRUE,0); InvalidateRect(panel.list,nullptr,FALSE); updateSelectionSummary(panel); - if(partial && &panel==&panels[active]) + if(finding && &panel==&panels[active]) showFileDetails(panel); + else if(partial && &panel==&panels[active]) setStatus(L"Partial: "+std::to_wstring(folders.size()+files.size())); else if(!partial && error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND) setStatus(L"Some entries could not be read."); @@ -2595,6 +2654,7 @@ void collectFolderSizes(Panel &panel) } void openSelectedText(const Panel &panel, bool edit, bool external); +void findLocalFiles(HWND owner,Panel &panel); void compareSelectedFiles(HWND owner); INT_PTR confirmTextSave(HWND owner,bool draft); bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveFormat &format); @@ -2730,6 +2790,7 @@ void selectDrive() else if(menuIndex==2 && (row==4 || row==5)) openSelectedText(panels[active],row==5,true); else if(menuIndex==2 && (row==6 || row==7)) runActivePeerAction(owner,row==7); else if(menuIndex==2 && row==8) compareSelectedFiles(owner); + else if(menuIndex==2 && row==9) findLocalFiles(owner,panels[active]); else { const int command=menuIndex==1?113+static_cast(row):110+static_cast(row); @@ -3280,6 +3341,11 @@ void enter(Panel &panel) return; } auto target = panel.rows[row]; + if(panel.findOrigin) + { + openOn(panel,target.parent_path(),false,{},target); + return; + } if(panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") open(panel,target,true); else if(panel.ftp) openSelectedText(panel,false,false); else openPanelFile(panel, target, nullptr, L"Cannot open the selected file."); @@ -5104,6 +5170,11 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa void copySelection(HWND owner,Panel &source,Panel &destination,bool move) { + if(source.findOrigin || destination.findOrigin) + { + setStatus(L"Open the folder before copying or moving files."); + return; + } const auto sourceFtp=source.ftp; const bool ftpRename=move && sourceFtp && !ftpProfileList(source); const auto destinationFtp=ftpRename?sourceFtp:destination.ftp; @@ -5461,6 +5532,11 @@ INT_PTR CALLBACK deleteProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM void deleteSelection(HWND owner,Panel &panel,bool permanent) { + if(panel.findOrigin) + { + setStatus(L"Open the folder before making changes."); + return; + } if(ftpProfileList(panel)) return; if(copyInProgress) return; const auto ftp=panel.ftp; @@ -5881,6 +5957,11 @@ INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) void makeFolder(HWND owner,Panel &panel) { + if(panel.findOrigin) + { + setStatus(L"Open the folder before making changes."); + return; + } if(panel.ftp) return; if(panel.directory.empty()) return; const auto directory=panel.directory; @@ -6067,6 +6148,11 @@ bool chooseTextSaveOptions(HWND owner,fs::path &destination,ks::files::TextSaveF void openOrCreateText(HWND owner,const Panel &panel) { + if(panel.findOrigin) + { + setStatus(L"Open the folder before making changes."); + return; + } if(panel.ftp) return; if(panel.peer) { @@ -6232,7 +6318,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT auto result=DefSubclassProc(window,message,wp,lp); if(movesCursor) invalidatePanelCursorChange(window,previous); if(message==WM_LBUTTONUP && GetFocus()==window) restoreCommandFocus(); - if(message==WM_PAINT && panels[index].wide) + if(message==WM_PAINT && hasPanelSizeColumn(panels[index])) { auto dc=GetDC(window); if(dc) @@ -6274,6 +6360,7 @@ bool loadFilesPreferences(HWND window) return true; } +#include "files_find.inl" #include "files_options.inl" void openMenu(HWND window, int index) @@ -6302,12 +6389,14 @@ void openMenu(HWND window, int index) { rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts", L"View externally\tAlt+F3",L"Edit externally\tAlt+F4", - L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel()}; + L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(), + L"Find files\tAlt+F7"}; } commandActions.clear(); if(index==2) { commandActions={0,3,-1,1,2,4,5,8}; + if(!panels[active].peer && !panels[active].ftp) commandActions.insert(commandActions.begin()+1,9); if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7}); } else @@ -6771,7 +6860,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) InflateRect(&box,-3,-3); FrameRect(dc,&box,border); FillRect(dc,÷r,border); - if(panel.wide) + if(hasPanelSizeColumn(panel)) { RECT column{columnX,box.top+1,columnX+1,pathBounds.bottom+6}; FillRect(dc,&column,border); @@ -6822,7 +6911,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) auto bounds=item.rcItem; FillRect(item.hDC,&bounds,blue); const auto &panel=panels[item.CtlID-142]; - const auto path=panelLocation(panel); + const auto path=panelCaption(panel); const auto middle=bounds.top+(bounds.bottom-bounds.top)/2; SetDCBrushColor(item.hDC,colors[Frame]); const auto lineBrush=static_cast(GetStockObject(DC_BRUSH)); @@ -6830,7 +6919,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) RECT lower{bounds.left,middle+1,bounds.right,middle+2}; FillRect(item.hDC,&upper,lineBrush); FillRect(item.hDC,&lower,lineBrush); - if(panels[item.CtlID-142].wide) + if(hasPanelSizeColumn(panel)) { const auto index=item.CtlID-142; RECT list{}; @@ -6861,6 +6950,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } if(item.CtlID==140 || item.CtlID==141) { + if(panels[item.CtlID-140].findOrigin) + { + paintText(item.hDC,item.rcItem,L"Relative path",RGB(255,255,0),colors[PanelBlue]); + return TRUE; + } auto name=item.rcItem, size=item.rcItem; size.left=panelSizeColumn(size); name.right=size.left; @@ -7092,7 +7186,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) if(item.CtlID==102 || item.CtlID==103) { const auto &panel=panels[item.CtlID-102]; - if(panel.wide && !ftpProfileList(panel) && item.itemIDfind) + { + if(!panel.scanSuperseded) stopDirectoryScan(); + continue; + } + if(panel.findOrigin && !panel.scanRequest) + { + openOn(panel,panel.directory,false,{}); + continue; + } if(panel.folderSizeJob) { collectFolderSizes(panel); @@ -7333,6 +7437,19 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) continue; } } + if(!terminalVisible && !copyInProgress && !commandHistoryWindow && !FilesModalDialog::activeFor(window) && + message.message==WM_SYSKEYDOWN && message.wParam==VK_F7 && + (message.lParam & (1LL<<29)) && + !((GetKeyState(VK_CONTROL)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) + { + if(!(message.lParam & (1LL<<30))) + { + hidePicker(); + showMenu(false); + findLocalFiles(window,panels[active]); + } + continue; + } if(!copyInProgress && !commandHistoryWindow && !FilesModalDialog::activeFor(window) && !terminalVisible && message.message==WM_SYSKEYDOWN && (message.wParam==VK_F3 || message.wParam==VK_F4) && (message.lParam & (1LL<<29)) && From 94b22fdd5221d75c21bad356e706452dab143615 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 12:59:04 +0200 Subject: [PATCH 02/61] Enable file operations in search results Refs #86 --- FILES-UI.md | 5 +++ src/files_find.inl | 14 ++++-- src/files_main.cpp | 110 ++++++++++++++++++++++++++++++++++----------- 3 files changed, 99 insertions(+), 30 deletions(-) diff --git a/FILES-UI.md b/FILES-UI.md index b9d19ef..9c23218 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -438,6 +438,11 @@ Warning і початковий фокус на No. Результати відкриваються в тій самій панелі з відносними шляхами. Enter або подвійний клік відкриває папку й ставить курсор на файл. Esc у результатах повертає вихідну папку, курсор і позначки. + У результатах F3/F4 відкривають файл, а F5/F6 працюють із позначеними + або поточним файлом, використовуючи папку іншої панелі як призначення. + F8 і Shift+Delete використовують звичайні підтвердження. Успішно + переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук + з тією самою маскою й видимістю прихованих файлів. - Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів у відкритих локальних папках. Фокус залишається там, де був, а курсор diff --git a/src/files_find.inl b/src/files_find.inl index 66f9d51..2aa1506 100644 --- a/src/files_find.inl +++ b/src/files_find.inl @@ -54,6 +54,14 @@ INT_PTR CALLBACK findFilesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) return FALSE; } +void startFileSearch(Panel &panel,Panel::FindOptions options) +{ + if(panel.scanRequest) return; + cancelFolderSizes(panel); + panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)}; + startDirectoryScan(panel); +} + void findLocalFiles(HWND owner,Panel &panel) { if(panel.peer || panel.ftp || panel.directory.empty()) @@ -66,10 +74,8 @@ void findLocalFiles(HWND owner,Panel &panel) setStatus(L"Wait for the current scan to finish."); return; } - Panel::FindOptions options; + auto options=panel.findOrigin?panel.findOrigin->options:Panel::FindOptions{}; if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner, findFilesDialog,reinterpret_cast(&options))!=IDOK) return; - cancelFolderSizes(panel); - panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)}; - startDirectoryScan(panel); + startFileSearch(panel,std::move(options)); } diff --git a/src/files_main.cpp b/src/files_main.cpp index 9640daa..42a0667 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -370,6 +370,7 @@ struct Panel struct FindOptions { std::wstring mask=L"*"; bool includeHidden{}; }; struct FindOrigin { + FindOptions options; fs::path cursor; std::set marks; LRESULT row{}, top{}; @@ -1626,12 +1627,15 @@ void copyCommandLineOrPanelNames(HWND owner) else copyPanelNames(owner); } +void startFileSearch(Panel &panel,Panel::FindOptions options); + void refreshPanel(Panel &panel) { cancelFolderSizes(panel); panel.folderSizes.clear(); updateSelectionSummary(panel); - open(panel,panel.directory,false); + if(panel.findOrigin) startFileSearch(panel,panel.findOrigin->options); + else open(panel,panel.directory,false); } std::wstring powerShellPath(const fs::path &path) @@ -2276,11 +2280,14 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul if(finding) { if(!panel.findOrigin) - panel.findOrigin=Panel::FindOrigin{previousSelection,std::move(markedPaths),previousRow,previousTop}; + { + panel.findOrigin=Panel::FindOrigin{*request.find,previousSelection,std::move(markedPaths),previousRow,previousTop}; + previousSelection.clear(); + previousRow=previousTop=0; + markedPaths.clear(); + } + panel.findOrigin->options=std::move(*request.find); panel.findOrigin->error=error; - previousSelection.clear(); - previousRow=previousTop=0; - markedPaths.clear(); } else if(panel.findOrigin) { @@ -3994,10 +4001,14 @@ CopyDestination validateCopyDestination(CopyRequest request,const std::wstring & throw std::runtime_error(ks::utf8(L"The destination folder is unavailable.")); const bool sameHost=(!peer && !request.sourcePeer) || (peer && request.sourcePeer && peer->id==request.sourcePeer->id); - const bool sameFolder=sameHost && (peer? - CompareStringOrdinal(destination.c_str(),-1,sourceDirectory.c_str(),-1,TRUE)==CSTR_EQUAL: - fs::equivalent(destination,sourceDirectory,error)); - if(request.newName.empty() && sameFolder) + const bool containsDestination=sameHost && request.newName.empty() && + std::any_of(request.sources.begin(),request.sources.end(),[&](const auto &path) + { + const auto parent=path.parent_path(); + return peer?CompareStringOrdinal(destination.c_str(),-1,parent.c_str(),-1,TRUE)==CSTR_EQUAL: + fs::equivalent(destination,parent,error); + }); + if(containsDestination) throw std::runtime_error(ks::utf8(L"Open a different folder in the other panel, or enter a new name for a single item.")); return {std::move(request.destination),std::move(request.newName),useSourcePeer}; } @@ -4233,7 +4244,7 @@ struct CopyProgress HWND window{}; std::atomic_bool canceled{}; bool closeOwner{}; - bool move{}; + bool move{}, fileSourcesOnly{}; int conflictChoice{}; ConflictMode conflictMode{}; bool askReadOnly=true; @@ -4979,6 +4990,8 @@ bool countCopy(CopyHost &host,const fs::path &path,CopyProgress &progress) const auto info=host.stat(path,progress.canceled); if(!info || (info->attributes&FILE_ATTRIBUTE_REPARSE_POINT)) throw std::system_error(info?ERROR_NOT_SUPPORTED:ERROR_FILE_NOT_FOUND,std::system_category()); + if(progress.fileSourcesOnly && (info->attributes&FILE_ATTRIBUTE_DIRECTORY)) + throw std::system_error(ERROR_FILE_INVALID,std::system_category()); if(!(info->attributes&FILE_ATTRIBUTE_DIRECTORY)) { ++progress.totalFiles; @@ -5045,6 +5058,8 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa const auto incoming=hosts.source.stat(from,progress.canceled); if(!incoming || (incoming->attributes&FILE_ATTRIBUTE_REPARSE_POINT)) throw std::system_error(incoming?ERROR_NOT_SUPPORTED:ERROR_FILE_NOT_FOUND,std::system_category()); + if(progress.fileSourcesOnly && (incoming->attributes&FILE_ATTRIBUTE_DIRECTORY)) + throw std::system_error(ERROR_FILE_INVALID,std::system_category()); const auto moveOnHost=[&](const fs::path &target,bool replace) { @@ -5168,15 +5183,48 @@ CopyResult copyItem(const CopyEndpoints &hosts,const fs::path &from,const fs::pa return transfer(to,true,mode==ConflictMode::append); } +void pruneSearchResults(Panel &panel,const std::set &removed) +{ + if(!panel.findOrigin || removed.empty()) return; + const bool visible=IsWindowVisible(panel.list); + if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0); + const auto cursor=currentPanelRow(panel); + LRESULT next=cursor; + for(size_t row=panel.rows.size();row>0;) + { + --row; + const auto &path=panel.rows[row]; + if(!removed.contains(path)) continue; + panel.timestamps.erase(path); + SendMessageW(panel.list,LB_DELETESTRING,row,0); + panel.rows.erase(panel.rows.begin()+row); + panel.sizes.erase(panel.sizes.begin()+row); + panel.dimmed.erase(panel.dimmed.begin()+row); + panel.marked.erase(panel.marked.begin()+row); + if(static_cast(row)(panel.rows.size()-1)),0); + if(visible) SendMessageW(panel.list,WM_SETREDRAW,TRUE,0); + InvalidateRect(panel.list,nullptr,FALSE); + updateSelectionSummary(panel); +} + void copySelection(HWND owner,Panel &source,Panel &destination,bool move) { - if(source.findOrigin || destination.findOrigin) - { - setStatus(L"Open the folder before copying or moving files."); - return; - } const auto sourceFtp=source.ftp; const bool ftpRename=move && sourceFtp && !ftpProfileList(source); + if(destination.findOrigin && !ftpRename) + { + setStatus(L"Open a destination folder in the other panel before copying or moving files."); + return; + } + if(source.findOrigin && source.scanRequest) + { + setStatus(L"Wait for the search to finish."); + return; + } + const bool fromSearch=source.findOrigin.has_value(); const auto destinationFtp=ftpRename?sourceFtp:destination.ftp; const bool ftp=sourceFtp || destinationFtp; if(ftp && !ftpRename && (move || (sourceFtp && destinationFtp) || source.peer || destination.peer || @@ -5221,6 +5269,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) const bool sameHost=!ftp && peerId(request.sourcePeer)==peerId(targetPeer); CopyProgress progress; progress.move=move; + progress.fileSourcesOnly=fromSearch; progress.conflictMode=request.conflictMode; progress.askReadOnly=request.askReadOnly; FilesModalDialog progressDialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(103),owner, @@ -5238,7 +5287,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) progressDialog.show(); bool failed=false, skipped=false; size_t copied=0; - std::set results; + std::set results, removed; std::wstring failure; std::vector lockPaths; try @@ -5303,6 +5352,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) if(outcome==CopyResult::failed) { failed=true; break; } if(outcome==CopyResult::skipped) { skipped=true; continue; } ++copied; + if(move && fromSearch) removed.insert(path); results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget); progress.ui.invoke([&] { const auto row=std::find(source.rows.begin(),source.rows.end(),path); @@ -5341,9 +5391,10 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) } if(move) { - open(source,source.directory); + if(fromSearch) pruneSearchResults(source,removed); + else open(source,source.directory); if(!ftpRename) open(destination,destination.directory); - if(renamed && copied && (sameHost || ftpRename)) + if(!fromSearch && renamed && copied && (sameHost || ftpRename)) { const auto renamedPath=progress.renamedTarget.empty()? targetDirectory/request.newName:progress.renamedTarget; @@ -5353,7 +5404,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) else { auto &updated=renameInSource?source:destination; - if(updated.directory==targetDirectory) + if(!updated.findOrigin && updated.directory==targetDirectory) open(updated,updated.directory); } if(!results.empty()) @@ -5532,9 +5583,10 @@ INT_PTR CALLBACK deleteProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM void deleteSelection(HWND owner,Panel &panel,bool permanent) { - if(panel.findOrigin) + const bool fromSearch=panel.findOrigin.has_value(); + if(fromSearch && panel.scanRequest) { - setStatus(L"Open the folder before making changes."); + setStatus(L"Wait for the search to finish."); return; } if(ftpProfileList(panel)) return; @@ -5548,7 +5600,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) for(size_t i=0;i> groups; std::wstring failure, sharingFailure; - std::set lockPaths; + std::set lockPaths, removed; const auto recordFailure=[&](const std::system_error &error,const fs::path &path) { ++failed; @@ -5617,7 +5669,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) { if(canceled) break; auto &group=groups.emplace_back(1,path); - if(permanent) + if(permanent && !fromSearch) { try { @@ -5679,7 +5731,9 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) bool readOnly=false; try { - const auto info=permanent?host.stat(current,canceled):std::optional{}; + const auto info=(permanent || fromSearch)?host.stat(current,canceled):std::optional{}; + if(fromSearch && info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY)) + throw std::system_error(ERROR_FILE_INVALID,std::system_category()); const auto attributes=info?info->attributes:INVALID_FILE_ATTRIBUTES; if(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_READONLY) && !(attributes&FILE_ATTRIBUTE_DIRECTORY)) @@ -5724,6 +5778,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) } else host.remove(current,permanent,attributes,readOnly); ++done; + if(!panel.peer && !ftp) removed.insert(current); } catch(const std::system_error &e) { @@ -5742,7 +5797,10 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) progressDialog.close(); for(auto &visible:panels) - if(!visible.directory.empty()) open(visible,visible.directory); + { + if(visible.findOrigin) pruneSearchResults(visible,removed); + else if(!visible.directory.empty()) open(visible,visible.directory); + } SetFocus(panel.list); const auto summary=(canceled?L"Deletion canceled. ":L"Deletion finished. ")+ std::to_wstring(done)+(permanent?L" deleted, ":L" moved to Recycle Bin, ")+ From 6cbb0639a13822644536cdbdcd614ac1ca954f6c Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 13:14:18 +0200 Subject: [PATCH 03/61] Add local path breadcrumbs and panel history Refs #87 --- FILES-UI.md | 12 +- resources/files.rc | 12 ++ src/files_main.cpp | 127 ++++++++++-- src/files_path_navigation.inl | 368 ++++++++++++++++++++++++++++++++++ 4 files changed, 502 insertions(+), 17 deletions(-) create mode 100644 src/files_path_navigation.inl diff --git a/FILES-UI.md b/FILES-UI.md index 9c23218..a6a3fa0 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -484,7 +484,17 @@ Warning і початковий фокус на No. - Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель. - Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший. -- Поточний шлях відображається по центру верхньої подвійної лінії панелі. Лінію видно з обох боків напису. Бірюзове тло активної панелі охоплює лише напис шляху з невеликими відступами. Довгий шлях скорочується в межах панелі. +- У локальному заголовку кнопки ← та → переходять назад і вперед + в історії відповідної панелі. Стрілка ↑, Alt+↑ та рядок `..` + відкривають безпосередню батьківську папку. На корені стрілка вимкнена, + а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі. +- Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва + трикрапка відкриває прихованих предків, а права — приховані папки + попередньої гілки. Клік по поточній папці або кнопці редагування та Ctrl+L + відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях, + а Esc повертає до тих самих панелей і курсора. + +- Для LAN і FTP поточний шлях відображається по центру верхньої подвійної лінії панелі. Довгий шлях скорочується в межах панелі. ## Спільні елементи діалогів diff --git a/resources/files.rc b/resources/files.rc index 1736ae7..3d2630a 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -420,3 +420,15 @@ BEGIN CONTROL "&Find", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 68, 73, 80, 17 CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 73, 80, 17 END + +117 DIALOGEX 0, 0, 290, 83 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "Go to folder" +FONT 10, "Consolas" +BEGIN + LTEXT "Folder &path (Tab completes)", 486, 16, 18, 258, 12 + FAR_EDIT(485, 0, 16, 32, 258, 15) + LTEXT "", 487, 10, 54, 1, 1, NOT WS_VISIBLE + CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17 +END diff --git a/src/files_main.cpp b/src/files_main.cpp index 42a0667..a2cd4f3 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -333,10 +333,72 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir constexpr auto schemeKey = L"Software\\KSwitcher\\Files"; #include "files_ftp.inl" + +fs::path panelParentPath(const fs::path &directory,bool local) +{ + if(!directory.has_relative_path()) return {}; + const auto parent=directory.parent_path(); + if(parent==directory) return {}; + if(local && directory.root_name().native().starts_with(L"\\\\") && !parent.has_relative_path()) + return {}; // A UNC share is a browsing root. + return parent; +} + +bool sameLocalFolder(const fs::path &a,const fs::path &b) +{ + return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,TRUE)==CSTR_EQUAL; +} + +bool inLocalBranch(const fs::path &ancestor,fs::path directory) +{ + while(!directory.empty()) + { + if(sameLocalFolder(ancestor,directory)) return true; + directory=panelParentPath(directory,true); + } + return false; +} + +struct LocalNavigation +{ + std::vector history; + size_t current{}; + fs::path previousBranch; + + void opened(const fs::path &directory,std::optional position) + { + if(!history.empty()) + { + const auto &previous=history[current]; + if(sameLocalFolder(previous,directory)) return; + if(inLocalBranch(directory,previous)) + { + if(!inLocalBranch(previous,previousBranch)) previousBranch=previous; + } + else if(!inLocalBranch(directory,previousBranch)) previousBranch.clear(); + } + if(position && *position neighbor(int direction) const + { + if(direction<0) return current?std::optional(current-1):std::nullopt; + return current+1(current+1):std::nullopt; + } +}; + struct Panel { HWND path{}, list{}, heading{}; fs::path directory; + LocalNavigation navigation; std::optional peer; std::optional ftp; struct DirectoryWatch @@ -386,6 +448,7 @@ struct Panel std::shared_ptr elevated; std::optional ftp; std::optional find; + std::optional navigationPosition; }; struct ScanResult { @@ -491,6 +554,8 @@ std::vector commandAccessPositions; std::vector commandActions; int menuIndex{}; bool commandPicker{}; +struct FolderPicker { const wchar_t *caption; std::vector paths; }; +std::optional folderPicker; constexpr int defaultSizeWidth=6, defaultFontPoints=110; constexpr bool defaultWide=false, defaultAlignExtensions=true, defaultShowDetails=true, defaultAlignFolders=false; constexpr DWORD defaultStatusFields=15; @@ -903,6 +968,7 @@ void showMenu(bool show); void hidePicker() { if (!picker || !IsWindowVisible(picker)) return; + folderPicker.reset(); KillTimer(GetParent(picker),driveQueryTimer); driveQueries.clear(); ShowWindow(picker,SW_HIDE); @@ -2300,6 +2366,8 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul } panel.findOrigin.reset(); } + if(peer || request.ftp) panel.navigation={}; + else if(!finding) panel.navigation.opened(directory,request.navigationPosition); panel.directory = directory; panel.peer=std::move(peer); panel.ftp=std::move(request.ftp); @@ -2321,7 +2389,8 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul panel.marked.clear(); panel.fileExtensionLength=panel.folderExtensionLength=0; const bool profiles=ftpProfileList(panel); - const bool hasParent=!finding && directory.has_relative_path(); + const auto parent=finding?fs::path{}:panelParentPath(directory,!panel.peer && !panel.ftp); + const bool hasParent=!parent.empty(); const auto rowCount=profiles?ftpProfiles.size():folders.size()+files.size()+hasParent; panel.rows.reserve(rowCount); panel.sizes.reserve(rowCount); @@ -2356,7 +2425,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul } else { - if(hasParent) add(directory.parent_path(),L"..",true); + if(hasParent) add(parent,L"..",true); for(const auto &folder:folders) add(folder,L"["+folder.filename().wstring()+L"]",true); for(const auto &file:files) add(file,finding?file.lexically_relative(directory).native():file.filename().native(),false); } @@ -2422,13 +2491,14 @@ void startDirectoryScan(Panel &panel) } void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional peer, - fs::path selection={},fs::path fallback={},std::optional ftp={}) + fs::path selection={},fs::path fallback={},std::optional ftp={}, + std::optional navigationPosition={}) { if(directory.empty() && !ftp) return; if(directory!=panel.directory || !samePanelSource(panel,peer,ftp)) cancelFolderSizes(panel); panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback), - std::move(peer),offerElevation,statusRevision,{},std::move(ftp)}; + std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition}; if(panel.scan.valid()) { panel.scanSuperseded=true; @@ -2770,6 +2840,7 @@ LRESULT ftpDriveRow() {return static_cast(drivePaths.size())+1;} bool selectablePickerRow(LRESULT row) { if(row<0) return false; + if(folderPicker) return static_cast(row)paths.size(); if(commandPicker) return static_cast(row)=0; return row(drivePaths.size()) || row==ftpDriveRow() || remoteDriveRows.contains(row); @@ -2779,6 +2850,14 @@ void selectDrive() { auto row=SendMessageW(picker,LB_GETCURSEL,0,0); if(!selectablePickerRow(row)) return; + if(folderPicker) + { + const auto path=folderPicker->paths[row]; + auto &panel=panels[pickerPanel]; + hidePicker(); + openOn(panel,path,true,{}); + return; + } if(commandPicker) row=commandActions[row]; const auto remote=remoteDriveRows.find(row); hidePicker(); @@ -2853,7 +2932,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT if(!HIWORD(hit) && !selectablePickerRow(LOWORD(hit))) return 0; } if(msg==WM_CAPTURECHANGED) driveWakeAction.cancel(); - if(!commandPicker && (msg==WM_LBUTTONDOWN || msg==WM_LBUTTONUP || msg==WM_LBUTTONDBLCLK)) + if(!commandPicker && !folderPicker && (msg==WM_LBUTTONDOWN || msg==WM_LBUTTONUP || msg==WM_LBUTTONDBLCLK)) { const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp); const int row=HIWORD(hit)?-1:LOWORD(hit); @@ -2875,7 +2954,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT return 0; } } - if(!commandPicker && msg==WM_CHAR) + if(!commandPicker && !folderPicker && msg==WM_CHAR) { const auto key=towupper(static_cast(wp)); LRESULT row=LB_ERR; @@ -2899,7 +2978,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT return 0; } } - if(!commandPicker && (msg==WM_MOUSEMOVE || msg==WM_MOUSELEAVE)) + if(!commandPicker && !folderPicker && (msg==WM_MOUSEMOVE || msg==WM_MOUSELEAVE)) { int row=-1; if(msg==WM_MOUSEMOVE) @@ -3089,7 +3168,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0) void pollDriveQueries(HWND owner) { - if(commandPicker || !IsWindowVisible(picker)) + if(commandPicker || folderPicker || !IsWindowVisible(picker)) { KillTimer(owner,driveQueryTimer); driveQueries.clear(); @@ -3157,6 +3236,7 @@ void pollDriveQueries(HWND owner) void chooseDrive(int index,bool fromMenu) { + folderPicker.reset(); commandPicker=false; if (!fromMenu) showMenu(false); pickerPanel=index; @@ -6432,6 +6512,7 @@ void openMenu(HWND window, int index) return; } menuIndex=index; + folderPicker.reset(); commandPicker=true; SendMessageW(picker,LB_RESETCONTENT,0,0); std::vector rows; @@ -6659,6 +6740,8 @@ void submitTerminalReturn(HWND owner,bool shift) handleFilesReturn(shift); } +#include "files_path_navigation.inl" + LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) { if(message==filesPreferencesChanged) @@ -6795,7 +6878,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) for (int i = 0; i < 2; ++i) { auto &panel = panels[i]; - panel.path = CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SS_OWNERDRAW, + panel.path = CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SS_OWNERDRAW | SS_NOTIFY, 0, 0, 0, 0, window, reinterpret_cast(142 + static_cast(i)), instance, nullptr); panel.list = CreateWindowExW(0, L"LISTBOX", L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS, @@ -6815,6 +6898,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) openOn(panel,saved.is_absolute()?saved:root,false,{},savedPanelPath(panelCursorKeys[i]), saved.is_absolute() && saved!=root?root:fs::path{}); SetWindowSubclass(panel.list, panelKeys, 1, 0); + SetWindowSubclass(panel.path,pathBarInput,1,0); installScrollBar(panel.list,window,firstPanelScrollBar+i); } SetFocus(panels[0].list); @@ -6987,6 +7071,12 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) RECT column{x,middle,x+1,bounds.bottom}; FillRect(item.hDC,&column,lineBrush); } + const bool highlighted=static_cast(item.CtlID)-142==active; + if(localNavigationAvailable(panel)) + { + paintLocalPath(item.hDC,bounds,panel,highlighted); + return TRUE; + } if(path.empty()) return TRUE; const int saved=SaveDC(item.hDC); SelectObject(item.hDC,mono); @@ -6995,7 +7085,6 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) const auto width=std::min(bounds.right-bounds.left,text.cx+2L*cellWidth); bounds.left+=(bounds.right-bounds.left-width)/2; bounds.right=bounds.left+width; - const bool highlighted=static_cast(item.CtlID)-142==active; FillRect(item.hDC,&bounds,highlighted?teal:blue); const auto padding=std::min(static_cast(cellWidth),width/4); InflateRect(&bounds,-padding,0); @@ -7025,7 +7114,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } if(item.hwndItem==pickerFrame || item.hwndItem==completionFrame) { - const bool driveFrame=item.hwndItem==pickerFrame && !commandPicker; + const bool driveFrame=item.hwndItem==pickerFrame && !commandPicker && !folderPicker; auto border=CreateSolidBrush(driveFrame?RGB(255,255,255):colors[Frame]); const auto box=paintDialogFrame(item.hDC,item.rcItem, dialogFrameMetrics(GetDpiForWindow(window)),teal,border); @@ -7048,6 +7137,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } paintDialogFrameCaptions(item.hDC,item.rcItem,box,L"Change drive",teal,colors[Text],mono); } + if(item.hwndItem==pickerFrame && folderPicker) + paintDialogFrameCaptions(item.hDC,item.rcItem,box,folderPicker->caption,teal,colors[Text],mono); const auto list=item.hwndItem==pickerFrame?picker:completionList; paintScrollPosition(item.hwndItem,item.hDC,list,colors[Dialog]); DeleteObject(border); @@ -7085,7 +7176,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) const bool popupRow=item.hwndItem==picker || item.hwndItem==completionList; auto background=item.CtlType==ODT_BUTTON?Footer:popupRow?Dialog:PanelBlue; auto foreground=colors[Text]; - if(item.hwndItem==picker && ((commandPicker && item.itemID(GetStockObject(DC_BRUSH))); return TRUE; } - if(item.hwndItem==picker && !commandPicker && item.itemID==ftpDriveRow()+1) + if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID==ftpDriveRow()+1) { auto row=item.rcItem; FillRect(item.hDC,&row,teal); @@ -7138,7 +7229,10 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } } auto shortcut=text.find(L'\t'); - if(item.hwndItem==picker && commandPicker && item.itemID=drivePaths.size()) + else if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID>=drivePaths.size()) { auto bounds=item.rcItem; RECT button{}; @@ -7453,6 +7547,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) if(message.hwnd==window && message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST && GetFocus()==terminalInput) message.hwnd=terminalInput; + if(handleLocalPathKey(window,message)) continue; if(message.hwnd==terminalInput && message.message==WM_KEYDOWN && !(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) && diff --git a/src/files_path_navigation.inl b/src/files_path_navigation.inl new file mode 100644 index 0000000..3fbe63f --- /dev/null +++ b/src/files_path_navigation.inl @@ -0,0 +1,368 @@ + +bool localNavigationAvailable(const Panel &panel) +{ + return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.directory.empty(); +} + +enum class PathAction { back, forward, up, edit, ancestors, previous, folder }; + +void navigateLocal(Panel &panel,const fs::path &path,std::optional position={}) +{ + if(path.empty() || sameLocalFolder(path,panel.directory)) return; + closePanelSearch(); + openOn(panel,path,true,{},{},{},{},position); +} + +void navigateLocalHistory(Panel &panel,int direction) +{ + if(const auto next=panel.navigation.neighbor(direction)) + navigateLocal(panel,panel.navigation.history[*next],next); +} + +struct PathPart +{ + PathAction action{}; + std::wstring label; + fs::path target; + std::vector hidden; + RECT rect{}; + bool current{}, dim{}, enabled=true; +}; + +std::wstring pathSegmentLabel(const fs::path &path) +{ + return panelParentPath(path,true).empty()?path.native():path.filename().native(); +} + +LONG segmentWidth(const fs::path &path) +{ + return static_cast(pathSegmentLabel(path).size()+2)*cellWidth; +} + +std::vector localPathParts(const Panel &panel,RECT bounds) +{ + const LONG total=bounds.right-bounds.left; + if(total<=0) return {}; + const LONG width=std::max(1L,std::min(2L*cellWidth,total/7)); + std::vector parts; + const auto add=[&](PathPart part,LONG length) + { + if(length<=0 || bounds.left>=bounds.right) return; + part.rect={bounds.left,bounds.top,std::min(bounds.right,bounds.left+length),bounds.bottom}; + bounds.left=part.rect.right; + parts.push_back(std::move(part)); + }; + const auto parent=panelParentPath(panel.directory,true); + add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width); + add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width); + add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width); + add({.action=PathAction::edit,.label=L"✎"},width); + + std::vector ancestors, previous; + for(auto path=parent;!path.empty();path=panelParentPath(path,true)) ancestors.push_back(path); + std::reverse(ancestors.begin(),ancestors.end()); + if(inLocalBranch(panel.directory,panel.navigation.previousBranch)) + { + for(auto path=panel.navigation.previousBranch;!sameLocalFolder(path,panel.directory); + path=panelParentPath(path,true)) + previous.push_back(path); + std::reverse(previous.begin(),previous.end()); + } + + const LONG room=bounds.right-bounds.left; + LONG required=segmentWidth(panel.directory); + for(const auto &path:ancestors) required+=segmentWidth(path); + for(const auto &path:previous) required+=segmentWidth(path); + size_t firstAncestor=0,visiblePrevious=previous.size(); + LONG currentWidth=segmentWidth(panel.directory); + if(required>room) + { + const LONG reserved=(!ancestors.empty()?width:0)+(!previous.empty()?width:0); + currentWidth=std::min(currentWidth,std::max(1L,room-reserved)); + LONG remaining=room-currentWidth-reserved; + firstAncestor=ancestors.size(); + while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1])) + remaining-=segmentWidth(ancestors[--firstAncestor]); + visiblePrevious=0; + while(visiblePrevious=segmentWidth(previous[visiblePrevious])) + remaining-=segmentWidth(previous[visiblePrevious++]); + } + + if(firstAncestor) + add({.action=PathAction::ancestors,.label=L"…", + .hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width); + for(size_t i=firstAncestor;i(part.label.size()),&text, + DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX); + } + if(saved) RestoreDC(dc,saved); +} + +constexpr int addressField=485,addressLabel=486,addressFooter=487; + +struct PathPrompt +{ + fs::path base, result; + std::wstring completionInput; + std::future completion; +}; + +constexpr UINT addressComplete=WM_APP+29; +constexpr UINT_PTR addressCompletionTimer=1; + +fs::path enteredPanelPath(const fs::path &base,std::wstring text) +{ + if(text.size()>=2 && text.front()==L'"' && text.back()==L'"') + text=text.substr(1,text.size()-2); + return fs::path(text).is_absolute()?fs::path(std::move(text)):base/fs::path(std::move(text)); +} + +std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text) +{ + const auto path=enteredPanelPath(base,text); + const auto directory=path.has_filename()?path.parent_path():path; + const auto prefix=path.filename().native(); + fs::path best; + std::error_code error; + for(fs::directory_iterator it(directory,error),end;!error && it!=end;it.increment(error)) + { + const auto name=it->path().filename().native(); + if(name.size()(prefix.size()),prefix.data(),static_cast(prefix.size()),TRUE)!=CSTR_EQUAL)) + continue; + std::error_code typeError; + if(it->is_directory(typeError) && (best.empty() || it->path()path(); + } + return best.empty()?std::wstring{}:best.native()+L"\\"; +} + +LRESULT CALLBACK addressFieldKeys(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + if(message==WM_GETDLGCODE) + { + const auto *key=reinterpret_cast(lp); + if(key && key->wParam==VK_TAB && !(GetKeyState(VK_SHIFT)&0x8000)) + return DefSubclassProc(field,message,wp,lp)|DLGC_WANTTAB; + } + if(message==WM_KEYDOWN && wp==VK_TAB && !(GetKeyState(VK_SHIFT)&0x8000)) + { + SendMessageW(GetParent(field),addressComplete,0,0); + return 0; + } + if(message==WM_CHAR && wp==VK_TAB) return 0; + return DefSubclassProc(field,message,wp,lp); +} + +INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_DRAWITEM) + { + paintDialogButton(*reinterpret_cast(lp),RGB(192,192,192),RGB(0,0,0),true); + return TRUE; + } + if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Go to folder ",false,{addressFooter})) + return painted; + if(message==WM_INITDIALOG) + { + auto &prompt=*reinterpret_cast(lp); + SetWindowLongPtrW(dialog,DWLP_USER,lp); + prepareTextDialog(dialog); + layoutDialogContent(dialog,addressLabel); + layoutDialogButtons(dialog,addressFooter,{IDOK,IDCANCEL}); + const auto field=GetDlgItem(dialog,addressField); + SendMessageW(field,EM_SETLIMITTEXT,32767,0); + SetWindowTextW(field,(prompt.base/fs::path{}).c_str()); + SetWindowSubclass(field,addressFieldKeys,4,0); + SetFocus(field); + SendMessageW(field,EM_SETSEL,0,-1); + return FALSE; + } + if(message==addressComplete) + { + auto &prompt=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(prompt.completion.valid()) return TRUE; + prompt.completionInput=shortcutField(dialog,addressField); + std::packaged_task task([base=prompt.base,text=prompt.completionInput] + { + return panelPathCompletion(base,text); + }); + if(!SetTimer(dialog,addressCompletionTimer,30,nullptr)) return TRUE; + prompt.completion=task.get_future(); + std::thread(std::move(task)).detach(); + return TRUE; + } + if(message==WM_TIMER && wp==addressCompletionTimer) + { + auto &prompt=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(!prompt.completion.valid() || + prompt.completion.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return TRUE; + KillTimer(dialog,addressCompletionTimer); + try + { + const auto value=prompt.completion.get(); + if(!value.empty() && shortcutField(dialog,addressField)==prompt.completionInput) + { + const auto field=GetDlgItem(dialog,addressField); + SetWindowTextW(field,value.c_str()); + SendMessageW(field,EM_SETSEL,value.size(),value.size()); + SendMessageW(field,EM_SCROLLCARET,0,0); + } + } + catch(const std::exception &) {} + return TRUE; + } + if(message==WM_COMMAND && LOWORD(wp)==IDOK) + { + auto &prompt=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + auto path=enteredPanelPath(prompt.base,shortcutField(dialog,addressField)).lexically_normal(); + if(!path.is_absolute()) + { + showFilesNotice(dialog,L"Enter a folder path.",L"Go to folder"); + return TRUE; + } + if(!path.has_filename() && path.has_relative_path()) path=path.parent_path(); + prompt.result=std::move(path); + FilesModalDialog::finish(dialog,IDOK); + return TRUE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + return FALSE; +} + +void editPanelPath(Panel &panel) +{ + PathPrompt prompt{panel.directory}; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(117),GetParent(panel.list), + editPathDialog,reinterpret_cast(&prompt))==IDOK) + navigateLocal(panel,prompt.result); +} + +void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector paths,RECT anchor) +{ + hidePicker(); + showMenu(false); + commandPicker=false; + pickerPanel=side; + folderPicker=FolderPicker{caption,std::move(paths)}; + SendMessageW(picker,LB_RESETCONTENT,0,0); + size_t longest=wcslen(caption); + for(const auto &path:folderPicker->paths) + { + longest=std::max(longest,path.native().size()); + SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast(path.c_str())); + } + RECT client{}; + GetClientRect(owner,&client); + const int inset=dialogFrameMetrics(GetDpiForWindow(owner)).content(); + const int width=std::max(1,std::min(static_cast(client.right)-2*inset,static_cast(longest+3)*cellWidth)); + const int x=std::clamp(static_cast(anchor.left),inset,std::max(inset,static_cast(client.right)-width-inset)); + const int y=anchor.bottom+inset; + const int row=std::max(1,static_cast(SendMessageW(picker,LB_GETITEMHEIGHT,0,0))); + RECT input{}; + GetWindowRect(terminalInput,&input); + MapWindowPoints(nullptr,owner,reinterpret_cast(&input),2); + const int bottom=std::min(client.bottom,input.top); + const int shown=std::clamp((bottom-y-inset)/row,1,static_cast(folderPicker->paths.size())); + showFramedList(picker,pickerFrame,x,y,width,row*shown,inset); + SendMessageW(picker,LB_SETCURSEL,0,0); + SetFocus(picker); +} + +void showHiddenPathParts(HWND window,int side,const PathPart &part) +{ + const auto owner=GetParent(window); + auto anchor=part.rect; + MapWindowPoints(window,owner,reinterpret_cast(&anchor),2); + showFolderPicker(owner,side,part.action==PathAction::ancestors?L"Parent folders":L"Previous path", + part.hidden,anchor); +} + +LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + if(message==WM_LBUTTONDOWN) + { + SetCapture(window); + return 0; + } + if(message==WM_LBUTTONUP && GetCapture()==window) + { + ReleaseCapture(); + const int index=GetDlgCtrlID(window)-142; + if(index<0 || index>=2) return 0; + auto &panel=panels[index]; + if(!localNavigationAvailable(panel)) + { + selectPanelEdge(panel,true); + return 0; + } + activatePanel(index); + RECT bounds{}; + GetClientRect(window,&bounds); + const POINT mouse{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; + const auto parts=localPathParts(panel,bounds); + for(const auto &part:parts) + { + if(!part.enabled || !PtInRect(&part.rect,mouse)) continue; + switch(part.action) + { + case PathAction::back: navigateLocalHistory(panel,-1); break; + case PathAction::forward: navigateLocalHistory(panel,1); break; + case PathAction::up: case PathAction::folder: navigateLocal(panel,part.target); break; + case PathAction::edit: editPanelPath(panel); break; + case PathAction::ancestors: case PathAction::previous: showHiddenPathParts(window,index,part); break; + } + break; + } + return 0; + } + return DefSubclassProc(window,message,wp,lp); +} + +bool handleLocalPathKey(HWND owner,const MSG &message) +{ + if(!commandLineAvailable(owner) || terminalVisible || !localNavigationAvailable(panels[active]) || + (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(message.message==WM_KEYDOWN && message.wParam=='L' && + (GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000)) + { + if(!(message.lParam&(1LL<<30))) editPanelPath(panel); + return true; + } + if(message.message!=WM_SYSKEYDOWN || !(message.lParam&(1LL<<29)) || + (GetKeyState(VK_CONTROL)&0x8000)) return false; + if(message.wParam==VK_UP) + navigateLocal(panel,panelParentPath(panel.directory,true)); + else if(message.wParam==VK_LEFT || message.wParam==VK_RIGHT) + navigateLocalHistory(panel,message.wParam==VK_LEFT?-1:1); + else return false; + return true; +} From 9e287c3a1d1b49c2fc2e99a8e30bec21267e616c Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 13:19:55 +0200 Subject: [PATCH 04/61] Add persistent recent folders to source menus Refs #88 --- FILES-UI.md | 5 +++ src/files_folder_shortcuts.inl | 15 +++----- src/files_main.cpp | 63 +++++++++++++++++++++++++++++---- src/files_path_navigation.inl | 19 ++++++++-- src/files_recent_folders.inl | 41 +++++++++++++++++++++ src/files_registry_json.inl | 25 +++++++++++++ tests/files_drive_shortcuts.ps1 | 9 +++-- 7 files changed, 154 insertions(+), 23 deletions(-) create mode 100644 src/files_recent_folders.inl create mode 100644 src/files_registry_json.inl diff --git a/FILES-UI.md b/FILES-UI.md index a6a3fa0..e8642aa 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -484,6 +484,11 @@ Warning і початковий фокус на No. - Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель. - Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший. +- **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує + останні відвідані локальні папки. Повторний візит підіймає один запис + угору, порядок зберігається після перезапуску. Enter або клік відкриває + шлях у панелі, з якої викликали меню. Delete прибирає вибраний запис. + - У локальному заголовку кнопки ← та → переходять назад і вперед в історії відповідної панелі. Стрілка ↑, Alt+↑ та рядок `..` відкривають безпосередню батьківську папку. На корені стрілка вимкнена, diff --git a/src/files_folder_shortcuts.inl b/src/files_folder_shortcuts.inl index 22ca55a..9369691 100644 --- a/src/files_folder_shortcuts.inl +++ b/src/files_folder_shortcuts.inl @@ -27,25 +27,18 @@ bool saveFolderShortcuts(const FolderShortcuts &shortcuts) {"name",ks::utf8(entry.peerName)},{"title",ks::utf8(entry.title)}}); groups.push_back(std::move(rows)); } - const auto data=groups.dump(); - return data.size()<=1024*1024 && - RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,REG_BINARY,data.data(), - static_cast(data.size()))==ERROR_SUCCESS; + return writeFilesJsonPreference(folderShortcutsKey,groups); } catch(const std::exception &){return false;} } void loadFolderShortcuts() { - DWORD bytes{}; - if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS || - !bytes || bytes>1024*1024) return; - std::string data(bytes,'\0'); - if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,folderShortcutsKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS) - return; + const auto saved=readFilesJsonPreference(folderShortcutsKey); + if(!saved) return; try { - const auto groups=Json::parse(data.begin(),data.begin()+bytes); + const auto &groups=*saved; if(!groups.is_array() || groups.size()!=folderShortcuts.size()) return; FolderShortcuts loaded; for(size_t digit=0;digit history; @@ -554,7 +557,12 @@ std::vector commandAccessPositions; std::vector commandActions; int menuIndex{}; bool commandPicker{}; -struct FolderPicker { const wchar_t *caption; std::vector paths; }; +struct FolderPicker +{ + const wchar_t *caption; + std::vector paths; + bool recent{}; +}; std::optional folderPicker; constexpr int defaultSizeWidth=6, defaultFontPoints=110; constexpr bool defaultWide=false, defaultAlignExtensions=true, defaultShowDetails=true, defaultAlignFolders=false; @@ -2367,7 +2375,11 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul panel.findOrigin.reset(); } if(peer || request.ftp) panel.navigation={}; - else if(!finding) panel.navigation.opened(directory,request.navigationPosition); + else if(!finding) + { + panel.navigation.opened(directory,request.navigationPosition); + if(!sameDirectory && !panel.directory.empty() && !partial) updateRecentFolders(directory,true); + } panel.directory = directory; panel.peer=std::move(peer); panel.ftp=std::move(request.ftp); @@ -2836,6 +2848,8 @@ void runActivePeerAction(HWND owner,bool update) } LRESULT ftpDriveRow() {return static_cast(drivePaths.size())+1;} +LRESULT recentDriveRow() {return ftpDriveRow()+1;} +void showRecentFolders(int side); bool selectablePickerRow(LRESULT row) { @@ -2843,7 +2857,8 @@ bool selectablePickerRow(LRESULT row) if(folderPicker) return static_cast(row)paths.size(); if(commandPicker) return static_cast(row)=0; - return row(drivePaths.size()) || row==ftpDriveRow() || remoteDriveRows.contains(row); + return row(drivePaths.size()) || row==ftpDriveRow() || row==recentDriveRow() || + remoteDriveRows.contains(row); } void selectDrive() @@ -2895,6 +2910,7 @@ void selectDrive() } else setStatus(L"Cannot load saved FTP connections."); } + else if(row==recentDriveRow()) showRecentFolders(pickerPanel); else if(remote!=remoteDriveRows.end()) { const auto &choice=remote->second; @@ -2905,6 +2921,37 @@ void selectDrive() LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR) { + if(folderPicker && folderPicker->recent && msg==WM_KEYDOWN && wp==VK_DELETE) + { + const auto row=SendMessageW(window,LB_GETCURSEL,0,0); + if(!selectablePickerRow(row)) return 0; + auto &paths=folderPicker->paths; + if(!updateRecentFolders(paths[row],false)) + { + setStatus(L"Could not remove the recent folder."); + return 0; + } + paths.erase(paths.begin()+row); + SendMessageW(window,LB_DELETESTRING,row,0); + if(paths.empty()) + { + hidePicker(); + setStatus(L"No recent local folders."); + } + else SendMessageW(window,LB_SETCURSEL,std::min(row,static_cast(paths.size()-1)),0); + return 0; + } + if(folderPicker && msg==WM_LBUTTONUP) + { + const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp); + const auto result=DefSubclassProc(window,msg,wp,lp); + if(folderPicker && !HIWORD(hit) && selectablePickerRow(LOWORD(hit))) + { + SendMessageW(window,LB_SETCURSEL,LOWORD(hit),0); + selectDrive(); + } + return result; + } if(msg==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN)) { const auto count=SendMessageW(window,LB_GETCOUNT,0,0); @@ -2989,7 +3036,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT if(!HIWORD(hit)) { const auto choice=remoteDriveRows.find(LOWORD(hit)); - if(LOWORD(hit)second.path && driveWakeAction.hit(window,LOWORD(hit),lp,cellWidth))) row=LOWORD(hit); @@ -3113,7 +3160,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0) auto selection=SendMessageW(picker,LB_GETCURSEL,0,0); std::optional previous; if(auto row=remoteDriveRows.find(selection);row!=remoteDriveRows.end()) previous=row->second; - if(selection>ftpDriveRow()) selection=-1; + if(selection>recentDriveRow()) selection=-1; if(focus) selection=initialRow; const auto top=SendMessageW(picker,LB_GETTOPINDEX,0,0); for(auto count=SendMessageW(picker,LB_GETCOUNT,0,0);count>static_cast(drivePaths.size());--count) @@ -3126,6 +3173,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0) }; add(L""); add(L"FTP"); + add(L"Recent folders"); add(L"KSwitcher LAN"); if(!drivePeerLookupError.empty()) add(L" "+drivePeerLookupError); else if(driveQueries.empty()) add(L" No paired computers"); @@ -7138,7 +7186,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) paintDialogFrameCaptions(item.hDC,item.rcItem,box,L"Change drive",teal,colors[Text],mono); } if(item.hwndItem==pickerFrame && folderPicker) - paintDialogFrameCaptions(item.hDC,item.rcItem,box,folderPicker->caption,teal,colors[Text],mono); + paintDialogFrameCaptions(item.hDC,item.rcItem,box,folderPicker->caption,teal,colors[Text],mono, + folderPicker->recent?L"Del Remove":nullptr); const auto list=item.hwndItem==pickerFrame?picker:completionList; paintScrollPosition(item.hwndItem,item.hDC,list,colors[Dialog]); DeleteObject(border); @@ -7186,7 +7235,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) FillRect(item.hDC,&line,static_cast(GetStockObject(DC_BRUSH))); return TRUE; } - if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID==ftpDriveRow()+1) + if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID==recentDriveRow()+1) { auto row=item.rcItem; FillRect(item.hDC,&row,teal); diff --git a/src/files_path_navigation.inl b/src/files_path_navigation.inl index 3fbe63f..b2ab625 100644 --- a/src/files_path_navigation.inl +++ b/src/files_path_navigation.inl @@ -264,13 +264,13 @@ void editPanelPath(Panel &panel) navigateLocal(panel,prompt.result); } -void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector paths,RECT anchor) +void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector paths,RECT anchor,bool recent=false) { hidePicker(); showMenu(false); commandPicker=false; pickerPanel=side; - folderPicker=FolderPicker{caption,std::move(paths)}; + folderPicker=FolderPicker{caption,std::move(paths),recent}; SendMessageW(picker,LB_RESETCONTENT,0,0); size_t longest=wcslen(caption); for(const auto &path:folderPicker->paths) @@ -295,6 +295,21 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector(&anchor),2); + showFolderPicker(owner,side,L"Recent folders",std::move(paths),anchor,true); +} + void showHiddenPathParts(HWND window,int side,const PathPart &part) { const auto owner=GetParent(window); diff --git a/src/files_recent_folders.inl b/src/files_recent_folders.inl new file mode 100644 index 0000000..40b88fd --- /dev/null +++ b/src/files_recent_folders.inl @@ -0,0 +1,41 @@ +constexpr wchar_t recentFoldersKey[]=L"RecentFolders"; +constexpr size_t recentFoldersLimit=100; + +std::vector readRecentFolders() +{ + const auto saved=readFilesJsonPreference(recentFoldersKey); + std::vector folders; + if(!saved || !saved->is_array()) return folders; + for(const auto &entry:*saved) + { + if(!entry.is_string()) continue; + const auto path=filePath(entry); + if(!path.is_absolute() || path.native().find(L'\0')!=std::wstring::npos) continue; + if(std::none_of(folders.begin(),folders.end(),[&](const auto &known){return sameLocalFolder(path,known);})) + folders.push_back(path); + if(folders.size()==recentFoldersLimit) break; + } + return folders; +} + +bool updateRecentFolders(const fs::path &path,bool remember) +{ + const Handle lock{CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.RecentFolders")}; + if(!lock.value) return false; + const auto wait=WaitForSingleObject(lock.value,100); + if(wait!=WAIT_OBJECT_0 && wait!=WAIT_ABANDONED) return false; + bool saved=false; + try + { + auto folders=readRecentFolders(); + std::erase_if(folders,[&](const auto &known){return sameLocalFolder(path,known);}); + if(remember) folders.insert(folders.begin(),path); + if(folders.size()>recentFoldersLimit) folders.resize(recentFoldersLimit); + auto data=Json::array(); + for(const auto &folder:folders) data.push_back(ks::utf8(folder.native())); + saved=writeFilesJsonPreference(recentFoldersKey,data); + } + catch(const std::exception &) {} + ReleaseMutex(lock.value); + return saved; +} diff --git a/src/files_registry_json.inl b/src/files_registry_json.inl new file mode 100644 index 0000000..457d8ba --- /dev/null +++ b/src/files_registry_json.inl @@ -0,0 +1,25 @@ +constexpr DWORD maxFilesJsonBytes=1024*1024; + +std::optional readFilesJsonPreference(const wchar_t *key) +{ + DWORD bytes{}; + if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS || + !bytes || bytes>maxFilesJsonBytes) return {}; + std::string data(bytes,'\0'); + if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,key,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS) + return {}; + try {return Json::parse(data.begin(),data.begin()+bytes);} + catch(const std::exception &) {return {};} +} + +bool writeFilesJsonPreference(const wchar_t *key,const Json &value) +{ + try + { + const auto data=value.dump(); + return data.size()<=maxFilesJsonBytes && + RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,key,REG_BINARY,data.data(), + static_cast(data.size()))==ERROR_SUCCESS; + } + catch(const std::exception &) {return false;} +} diff --git a/tests/files_drive_shortcuts.ps1 b/tests/files_drive_shortcuts.ps1 index 0a9a481..e02e975 100644 --- a/tests/files_drive_shortcuts.ps1 +++ b/tests/files_drive_shortcuts.ps1 @@ -89,7 +89,8 @@ try { Open-Picker $side $rows = @(Read-Picker) $row = [Array]::IndexOf($rows, 'FTP') - if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'KSwitcher LAN') { + if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'Recent folders' -or + $rows[$row + 2] -cne 'KSwitcher LAN') { throw "Source groups are missing separators in panel $side." } [void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$row, $null) @@ -98,12 +99,14 @@ try { [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero) Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row } [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero) + Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 } + [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero) Wait-Until { $selected = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() - $selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 1) + $selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 2) } [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero) - Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row } + Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 } [void][FilesDriveShortcutTest]::SendMessage($picker, 407, [IntPtr]($row - 2), $null) $bitmap = Render-Picker try { From 3dd4edeb2cc0139aebd2361e7c60d097f121cc34 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 13:33:15 +0200 Subject: [PATCH 05/61] Add Quick View for local text and Markdown Refs #89 --- CMakeLists.txt | 5 + FILES-UI.md | 6 + resources/terminal/markdown.html | 4 + resources/terminal/markdown.js | 9 +- src/files_main.cpp | 94 ++++++++++-- src/files_text_window.cpp | 245 +++++++++++++++++++++++++------ src/files_text_window.h | 4 + tests/files_quick_view.ps1 | 101 +++++++++++++ 8 files changed, 408 insertions(+), 60 deletions(-) create mode 100644 tests/files_quick_view.ps1 diff --git a/CMakeLists.txt b/CMakeLists.txt index d27491f..c02d213 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -26,6 +26,11 @@ add_custom_target(check-files-search-arrow -Executable "$" DEPENDS KSwitcherFiles VERBATIM) +add_custom_target(check-files-quick-view + COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_quick_view.ps1" + -Executable "$" + DEPENDS KSwitcherFiles + VERBATIM) target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include") target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet) if(MSVC) diff --git a/FILES-UI.md b/FILES-UI.md index e8642aa..07ef715 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -484,6 +484,12 @@ Warning і початковий фокус на No. - Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель. - Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший. +- **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального + тексту й Markdown у сусідній панелі. Перегляд слідує за курсором активної + панелі. Повторна команда повертає сусідній каталог, курсор і позначки. + Під час перегляду файлові операції з призначенням у сусідній панелі + пропонують спершу закрити Quick View. + - **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує останні відвідані локальні папки. Повторний візит підіймає один запис угору, порядок зберігається після перезапуску. Enter або клік відкриває diff --git a/resources/terminal/markdown.html b/resources/terminal/markdown.html index e12fbbe..e97375c 100644 --- a/resources/terminal/markdown.html +++ b/resources/terminal/markdown.html @@ -10,6 +10,10 @@ body { max-width: var(--markdown-width, 960px); margin: auto; padding: 20px 28px; overflow-wrap: anywhere; } main { font: var(--markdown-font-size, 12pt)/1.55 var(--markdown-font, system-ui, sans-serif); } nav { position: sticky; top: 0; display: flex; flex-wrap: wrap; gap: .4em; padding-block: .25em; background: Canvas; } +:root.quick-view body { padding: 8px 12px; } +:root.quick-view nav { display: none; } +:root.quick-view main > :first-child { margin-block-start: 0; } +:root.quick-view h1 { font-size: 1.4em; } nav button { appearance: none; border: 0; background: transparent; color: LinkText; font: 1.35em/1.25 system-ui, sans-serif; min-width: 1.55em; padding: 0; cursor: pointer; } nav button:disabled { color: GrayText; opacity: .6; cursor: default; } diff --git a/resources/terminal/markdown.js b/resources/terminal/markdown.js index 675116f..8ca0643 100644 --- a/resources/terminal/markdown.js +++ b/resources/terminal/markdown.js @@ -247,12 +247,13 @@ searchPrevious.addEventListener('click', () => stepSearch(-1)); searchNext.addEventListener('click', () => stepSearch(1)); content.addEventListener('toggle', () => { if (!search.hidden) updateSearch(false); }, true); -async function render({ text, fragment, scroll, title, keepPosition, revision, canSave }) { +async function render({ text, fragment, scroll, title, keepPosition, revision, canSave, compact }) { const current = ++generation; if (keepPosition) scroll = window.scrollY; else closeSearch(); document.documentElement.classList.remove('rendered'); document.title = title; + document.documentElement.classList.toggle('quick-view', Boolean(compact)); previewRevision = revision; renderContent(text, canSave); const headings = new Set(); @@ -264,7 +265,7 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c headings.add(id); } images = Array.from(content.querySelectorAll('img[data-path]')); - images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current })); + images.forEach((image, index) => send('image', { path: image.dataset.path, index, generation: current, revision })); const blocks = Array.from(content.querySelectorAll('pre > code.language-mermaid')); for (const [index, block] of blocks.entries()) { try { @@ -289,7 +290,7 @@ async function render({ text, fragment, scroll, title, keepPosition, revision, c restorePosition({ fragment, scroll }); document.documentElement.classList.add('rendered'); if (!search.hidden) updateSearch(false); - send('rendered'); + send('rendered', { revision }); } content.addEventListener('change', ({ target }) => { @@ -350,7 +351,7 @@ bridge.addEventListener('message', ({ data }) => { document.documentElement.classList.remove('rendered'); content.replaceChildren(); } - if (message.action === 'render') void render(message).catch(() => send('failed')); + if (message.action === 'render') void render(message).catch(() => send('failed', { revision: message.revision })); if (message.action === 'task-result' && message.revision === previewRevision && pendingTask) { if (!message.saved) pendingTask.target.checked = !pendingTask.checked; pendingTask = undefined; diff --git a/src/files_main.cpp b/src/files_main.cpp index 2ac21d5..edcd69a 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -506,6 +506,10 @@ std::wstring panelCaption(const Panel &panel) } Panel panels[2]; +HWND quickViewWindow{}; +int quickViewSource{}; +void refreshQuickView(const Panel &panel); +void toggleQuickView(HWND owner); FilesTerminal terminal; std::mutex pendingTerminalOutputMutex; std::string pendingTerminalOutput; @@ -1161,6 +1165,7 @@ void swapPanels(HWND window) // Move the controls with their contents to retain the cursor and scroll position. std::swap(panels[0],panels[1]); active=1-active; + if(quickViewWindow) quickViewSource=1-quickViewSource; for(auto &command:terminalCommands) if(command.panel>=0) command.panel=1-command.panel; for(int i=0;i<2;++i) @@ -1228,12 +1233,15 @@ void layout(HWND window,bool activeOnly) place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), textHeight); int headingHeight=panels[i].wide?textHeight:0; const int listWidth=std::max(0,end-x-8-scrollBarWidth(panels[i].list)); + const bool panelVisible=!terminalVisible && (!quickViewWindow || i==quickViewSource); + ShowWindow(panels[i].path,panelVisible?SW_SHOWNA:SW_HIDE); + ShowWindow(panels[i].list,panelVisible?SW_SHOWNA:SW_HIDE); place(panels[i].heading,x+5,textHeight+10,listWidth,headingHeight); - ShowWindow(panels[i].heading,!terminalVisible && panels[i].wide?SW_SHOWNA:SW_HIDE); + ShowWindow(panels[i].heading,panelVisible && panels[i].wide?SW_SHOWNA:SW_HIDE); place(panels[i].list, x + 5, textHeight+10+headingHeight,listWidth, std::max(0, panelBottom-textHeight-10-headingHeight)); place(panels[i].selectionSummary,x+8,panelBottom+4,std::max(0,end-x-16),summaryHeight); - ShowWindow(panels[i].selectionSummary,summaryHeight?SW_SHOWNA:SW_HIDE); + ShowWindow(panels[i].selectionSummary,panelVisible && summaryHeight?SW_SHOWNA:SW_HIDE); } place(menuBar,0,0,width,textHeight+4); const int menuEdges[]{0,7,15,27,38,46}; @@ -1285,6 +1293,14 @@ void layout(HWND window,bool activeOnly) const int right=((i+1)*unit+refreshExtra)*width/total; place(commands[i],left,height-textHeight,right-left,textHeight); } + if(quickViewWindow) + { + const int left=quickViewSource==0?middle+2:0; + const int right=quickViewSource==0?width:middle-2; + SetWindowPos(quickViewWindow,nullptr,left+5,4,std::max(0,right-left-10), + std::max(0,panelBottom+summaryHeight+textHeight),SWP_NOZORDER|SWP_NOACTIVATE); + ShowWindow(quickViewWindow,terminalVisible?SW_HIDE:SW_SHOWNA); + } if(IsWindowVisible(panelSearchPopup)) placePanelSearch(window); RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN); } @@ -1322,11 +1338,6 @@ bool stopDirectoryScan() void showTerminal(HWND owner,bool show) { terminalVisible=show; - for(const auto &panel:panels) - { - ShowWindow(panel.path,show?SW_HIDE:SW_SHOWNA); - ShowWindow(panel.list,show?SW_HIDE:SW_SHOWNA); - } layout(owner); SetFocus(terminalInput); } @@ -1371,6 +1382,7 @@ void invalidatePanelCursorChange(HWND list,LRESULT previous) void activatePanel(int index) { + if(quickViewWindow && index!=quickViewSource) return; const auto previous=active; active=index; showFileDetails(panels[index]); @@ -2096,6 +2108,7 @@ void updateSelectionSummary(const Panel &panel) void showFileDetails(const Panel &panel) { + refreshQuickView(panel); if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return; if(panel.findOrigin) { @@ -2472,6 +2485,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul if(visible) SendMessageW(panel.list,WM_SETREDRAW,TRUE,0); InvalidateRect(panel.list,nullptr,FALSE); updateSelectionSummary(panel); + refreshQuickView(panel); if(finding && &panel==&panels[active]) showFileDetails(panel); else if(partial && &panel==&panels[active]) setStatus(L"Partial: "+std::to_wstring(folders.size()+files.size())); @@ -2892,6 +2906,7 @@ void selectDrive() else if(menuIndex==2 && (row==6 || row==7)) runActivePeerAction(owner,row==7); else if(menuIndex==2 && row==8) compareSelectedFiles(owner); else if(menuIndex==2 && row==9) findLocalFiles(owner,panels[active]); + else if(menuIndex==2 && row==10) toggleQuickView(owner); else { const int command=menuIndex==1?113+static_cast(row):110+static_cast(row); @@ -3284,6 +3299,7 @@ void pollDriveQueries(HWND owner) void chooseDrive(int index,bool fromMenu) { + if(quickViewWindow && index!=quickViewSource) toggleQuickView(GetParent(picker)); folderPicker.reset(); commandPicker=false; if (!fromMenu) showMenu(false); @@ -3439,6 +3455,53 @@ ks::files::TextDialogs textWindowDialogs() },chooseTextSaveOptions}; } +void refreshQuickView(const Panel &panel) +{ + if(!quickViewWindow || &panel!=&panels[quickViewSource]) return; + const auto row=currentPanelRow(panel); + const bool file=!panel.peer && !panel.ftp && row!=LB_ERR && + panel.sizes[row]!=L"Folder" && panel.sizes[row]!=L"Up"; + ks::files::previewQuickViewFile(quickViewWindow,file?panel.rows[row]:fs::path{}); +} + +void toggleQuickView(HWND owner) +{ + if(quickViewWindow) + { + DestroyWindow(std::exchange(quickViewWindow,nullptr)); + layout(owner); + restoreCommandFocus(); + return; + } + const auto &panel=panels[active]; + if(panel.peer || panel.ftp || terminalVisible) + { + setStatus(L"Quick View requires a visible local file pane."); + return; + } + try {quickViewWindow=ks::files::createQuickView(owner,textWindowDialogs());} + catch(const std::exception &) {} + if(!quickViewWindow) + { + setStatus(L"Could not open Quick View."); + return; + } + quickViewSource=active; + refreshQuickView(panel); + layout(owner); +} + +bool handleQuickViewKey(HWND window,const MSG &message) +{ + if(message.message!=WM_KEYDOWN || message.wParam!='Q' || terminalVisible || + !commandLineAvailable(window) || + !(GetKeyState(VK_CONTROL)&0x8000) || + ((GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) + return false; + if(!(message.lParam&(1LL<<30))) toggleQuickView(window); + return true; +} + ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile); void openSelectedText(const Panel &panel, bool edit, bool external) @@ -5342,6 +5405,11 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) { const auto sourceFtp=source.ftp; const bool ftpRename=move && sourceFtp && !ftpProfileList(source); + if(quickViewWindow && &destination!=&panels[quickViewSource] && !ftpRename) + { + setStatus(L"Close Quick View to use the destination pane."); + return; + } if(destination.findOrigin && !ftpRename) { setStatus(L"Open a destination folder in the other panel before copying or moving files."); @@ -6577,13 +6645,14 @@ void openMenu(HWND window, int index) rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts", L"View externally\tAlt+F3",L"Edit externally\tAlt+F4", L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(), - L"Find files\tAlt+F7"}; + L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q"}; } commandActions.clear(); if(index==2) { commandActions={0,3,-1,1,2,4,5,8}; if(!panels[active].peer && !panels[active].ftp) commandActions.insert(commandActions.begin()+1,9); + if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10); if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7}); } else @@ -6794,6 +6863,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) { if(message==filesPreferencesChanged) { + if(quickViewWindow) SendNotifyMessageW(quickViewWindow,message,wp,lp); if(reinterpret_cast(wp)!=window) { loadFilesPreferences(window); @@ -6835,6 +6905,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) drivePeerReplyReceived=true; return TRUE; } + case ks::files::quickViewToggleMessage: + if(quickViewWindow && !copyInProgress && !FilesModalDialog::activeFor(window)) toggleQuickView(window); + return 0; case directoryScanReady: if(!FilesModalDialog::activeFor(window)) collectDirectoryScans(); return 0; @@ -7046,7 +7119,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) const RECT divider{box.left+1,box.bottom-2,box.right-1,box.bottom-1}; box.bottom=std::max(box.bottom,details.bottom+6); FrameRect(dc,&box,border); - paintScrollPosition(window,dc,panel.list,colors[PanelBlue]); + if(IsWindowVisible(panel.list)) paintScrollPosition(window,dc,panel.list,colors[PanelBlue]); InflateRect(&box,-3,-3); FrameRect(dc,&box,border); FillRect(dc,÷r,border); @@ -7511,6 +7584,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) remoteCommandThread.request_stop(); remoteCommandThread.join(); } + if(quickViewWindow) DestroyWindow(std::exchange(quickViewWindow,nullptr)); ks::files::textWindowOwnerClosed(); return 0; } @@ -7596,7 +7670,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) if(message.hwnd==window && message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST && GetFocus()==terminalInput) message.hwnd=terminalInput; - if(handleLocalPathKey(window,message)) continue; + if(handleQuickViewKey(window,message) || handleLocalPathKey(window,message)) continue; if(message.hwnd==terminalInput && message.message==WM_KEYDOWN && !(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) && diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index 999b5a7..7e5d4c5 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -740,13 +740,13 @@ class TextWindow { public: TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend, - std::string_view fragment,TextOpenOptions options) + std::string_view fragment,TextOpenOptions options,bool quickView=false) : original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()), - edit(editable), draft(options.draft), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), + edit(editable), draft(options.draft), embedded(quickView), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), search{dialogs}, previewFragment(fragment) { if (backend) remote=std::make_unique(*backend,original); - else document=std::make_unique(draft?std::filesystem::path{}:original,edit,options.encoding); + else if(!embedded) document=std::make_unique(draft?std::filesystem::path{}:original,edit,options.encoding); if(options.encoding!=TextEncoding::automatic) { newFormat.encoding=options.encoding; @@ -772,6 +772,7 @@ public: HWND window{}, editor{}; bool handleKey(const MSG &message); void goToFragment(std::string_view fragment); + void previewFile(const std::filesystem::path &path); std::filesystem::path original; const std::string peerId; @@ -780,7 +781,7 @@ private: std::unique_ptr document; std::wstring filename; bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{}; - bool draft{}; + bool draft{}, embedded{}; TextSaveFormat newFormat; std::filesystem::path pendingSavePath; HICON smallIcon{},largeIcon{}; @@ -862,6 +863,20 @@ private: static constexpr UINT_PTR openTimer = 2; static constexpr UINT_PTR previewTimer = 3; static constexpr UINT_PTR navigationTimer = 4; + static constexpr UINT_PTR quickViewTimer = 5; + struct QuickDocument + { + std::unique_ptr document; + std::string firstPage; + std::optional markdown; + }; + std::future quickLoading; + std::filesystem::path quickPath; + uint64_t quickRequest{}, quickReading{}; + ULONGLONG quickReadyAt{}; + std::wstring quickError; + std::optional quickMarkdown; + void pollQuickView(); static constexpr UINT trimUndo = WM_APP + 1; static constexpr UINT previewFailed = WM_APP + 2; static constexpr UINT openPreviewLink = WM_APP + 3; @@ -890,7 +905,7 @@ private: void invalidateStatus() const; void invalidateHints() const; - void initializeDocument(); + void initializeDocument(std::optional firstPage={}); void finishOpen(); void createMenu(); void releaseMenu(); @@ -906,7 +921,7 @@ private: void updateLineNumberMargin(); void applyLineEnding(); void installLexer(); - void loadPage(uint64_t index); + void loadPage(uint64_t index,std::optional cached={}); void stagePage(); void go(uint64_t index); void saveFile(bool closeWhenDone); @@ -1206,7 +1221,7 @@ void TextWindow::reloadPreferences() if (!fontChanged && profile == prefs) return; prefs = std::move(profile); filesFont = font; - if (fontChanged) + if (fontChanged && !embedded) { releaseMenu(); createMenu(); @@ -1294,9 +1309,9 @@ void TextWindow::applyLineEnding() send(SCI_SETEOLMODE, choices[prefs.lineEnding]); } -void TextWindow::loadPage(uint64_t index) +void TextWindow::loadPage(uint64_t index,std::optional cached) { - auto data = document->readPage(index); + auto data=cached?std::move(*cached):document->readPage(index); const auto offset = document->boundary(index); page = index; pageOffset = offset; @@ -1344,19 +1359,99 @@ void TextWindow::go(uint64_t index) loadPage(index); } -void TextWindow::initializeDocument() +void TextWindow::initializeDocument(std::optional firstPage) { - automatic=detectLanguage(original,document->readPage(0)); + if(!firstPage) firstPage=document->readPage(0); + automatic=detectLanguage(original,*firstPage); language=automatic; if(canPreview()) ShowWindow(editor,SW_HIDE); - releaseMenu(); - createMenu(); + if(!embedded) + { + releaseMenu(); + createMenu(); + if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment}); + } installLexer(); - loadPage(0); - if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment}); + loadPage(0,std::move(firstPage)); updatePreview(); } +std::string readMarkdownDocument(TextDocument &document) +{ + std::string text; + for(uint64_t index=0;index task([path=quickPath] { + auto source=std::make_unique(path,false); + auto first=source->readPage(0); + if(first.find('\0')!=std::string::npos) + throw std::runtime_error("Binary preview is unavailable."); + std::optional markdown; + if(source->size()<=TextDocument::editLimit && detectLanguage(path,first).lexer=="markdown") + markdown=readMarkdownDocument(*source); + source->releaseReadHandle(); + return QuickDocument{std::move(source),std::move(first),std::move(markdown)}; + }); + quickLoading=task.get_future(); + std::thread(std::move(task)).detach(); +} + void TextWindow::finishOpen() { if(!opening.valid() || opening.wait_for(std::chrono::milliseconds(0))!=std::future_status::ready) return; @@ -1602,6 +1697,12 @@ bool TextWindow::startPreviewBrowser() { const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0; const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0; + if(embedded) + { + if(!ctrl || alt || key!='Q') return false; + PostMessageW(GetParent(window),quickViewToggleMessage,0,0); + return true; + } if(!alt && ((ctrl && key=='F') || key==VK_F3)) { const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0; @@ -1684,12 +1785,10 @@ void TextWindow::renderPreview(bool keepPosition) { applyMarkdownPreferences(loadTextPreferences().markdown); previewDeadline=GetTickCount64()+30000; - previewText.clear(); - for(uint64_t index=0;indexpages();++index) - previewText+=document->readPage(index); + previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document); if(!remote) document->releaseReadHandle(); nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision}, - {"canSave",!remote || remote->revision.editable}, + {"canSave",!embedded && (!remote || remote->revision.editable)},{"compact",embedded}, {"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)}, {"keepPosition",keepPosition}}; if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll; @@ -1706,7 +1805,7 @@ void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences void TextWindow::refreshPreview() { - if(remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()(revision),0); return; } if(action=="rendered") { - PostMessageW(window,previewRendered,0,0); + PostMessageW(window,previewRendered,static_cast(revision),0); return; } if(action=="save-task") @@ -2054,8 +2156,10 @@ void TextWindow::layout() RECT area{}; GetClientRect(window, &area); const auto row = chromeHeight(); - MoveWindow(editor, 0, 2 * row, area.right, std::max(0L, area.bottom - 3 * row), TRUE); - preview.layout({0,2*row,area.right,std::max(2*row,area.bottom-row)},previewWanted); + const int top=embedded?row:2*row; + const LONG bottom=std::max(top,area.bottom-(embedded?0:row)); + MoveWindow(editor,0,top,area.right,bottom-top,TRUE); + preview.layout({0,top,area.right,bottom},previewWanted && (!embedded || previewVisible)); ShowWindow(editor,document && !previewWanted?SW_SHOWNA:SW_HIDE); invalidate(); } @@ -2121,6 +2225,24 @@ void TextWindow::paint() const auto row = chromeHeight(); const auto brush = static_cast(GetStockObject(DC_BRUSH)); SetDCBrushColor(dc, color(TextColor::background)); + if(embedded) + { + FillRect(dc,&client,brush); + auto font=filesFont.font; + font.lfHeight=-MulDiv(filesFont.tenthsOfPoint,GetDpiForWindow(window),720); + const auto chromeFont=CreateFontIndirectW(&font); + std::wstring label=L"Quick View"; + if(!quickPath.empty()) label+=L" · "+quickPath.filename().native(); + if(!quickError.empty()) label+=L" · "+quickError; + else if(quickPath.empty()) label+=L" · Select a local text file"; + else if(!document || (previewWanted && !previewVisible)) label+=L" · Loading…"; + else if(!previewVisible && pageTotal>1) label+=L" · First page"; + drawEditorStatus(dc,{0,0,client.right,row},chromeFont,color(TextColor::chromebg), + color(TextColor::chrome),scale(6),label); + if(chromeFont) DeleteObject(chromeFont); + EndPaint(window,&paint); + return; + } const RECT body{0,2*row,client.right,std::max(2*row,client.bottom-row)}; FillRect(dc, &body, brush); SetDCBrushColor(dc, color(TextColor::chromebg)); @@ -2339,6 +2461,7 @@ void TextWindow::notify(const SCNotification ¬ice) bool TextWindow::handleKey(const MSG &message) { + if(embedded) return false; const auto key = message.wParam; if (message.hwnd != editor) return false; if (message.message == WM_SYSKEYDOWN && (message.lParam & (1LL << 29))) @@ -2387,7 +2510,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, const auto &state=*static_cast *>(create->lpCreateParams); state->window=window; textWindows.emplace(window,state); - textWindowOrder.push_back(window); + if(!state->embedded) textWindowOrder.push_back(window); } const auto found=textWindows.find(window); if(found==textWindows.end()) return DefWindowProcW(window,message,wparam,lparam); @@ -2428,7 +2551,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, MSG key{child,msg,wp,lp}; if(state->handleKey(key)) return 0; } - if(msg==WM_XBUTTONUP && !state->edit) + if(msg==WM_XBUTTONUP && !state->edit && !state->embedded) { SendMessageW(state->window,WM_COMMAND, GET_XBUTTON_WPARAM(wp)==XBUTTON1?historyBack:historyForward,0); @@ -2447,9 +2570,13 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, state->remote->download(state->edit,[state](uint64_t,uint64_t){return !state->cancelOpen;}); }); } + else if(self->embedded) self->applyPreferences(); else self->initializeDocument(); - self->updateIcons(GetDpiForWindow(window)); - self->updateTaskbarGroup(); + if(!self->embedded) + { + self->updateIcons(GetDpiForWindow(window)); + self->updateTaskbarGroup(); + } self->layout(); return 0; case WM_ERASEBKGND: return 1; @@ -2465,10 +2592,10 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, self->layout(); return 0; } - case WM_SETFOCUS: self->focusContent(); return 0; + case WM_SETFOCUS: if(!self->embedded) self->focusContent(); return 0; case cycleWindow: cycleTextWindows(window,wparam!=0); return 0; case WM_KEYDOWN: - if(self->previewWanted && !self->previewVisible) + if(!self->embedded && self->previewWanted && !self->previewVisible) { if(wparam==VK_F6) self->toggleMode(); if(wparam==VK_ESCAPE || wparam==VK_F10 || @@ -2476,13 +2603,15 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, return 0; } break; - case previewFailed: self->stopPreview(); return 0; + case previewFailed: + if(!self->embedded || !wparam || wparam==self->previewRevision) self->stopPreview(); + return 0; case savePreviewTask: self->startMarkdownTask(); return 0; case previewRendered: - if(self->previewWanted) + if(self->previewWanted && (!self->embedded || wparam==self->previewRevision)) { self->previewVisible=true; - self->syncNavigation(); + if(!self->embedded) self->syncNavigation(); self->layout(); if(GetForegroundWindow()==window) self->focusContent(); } @@ -2511,6 +2640,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, return 0; } case WM_COMMAND: + if(self->embedded) return 0; if (LOWORD(wparam) >= 600 && LOWORD(wparam) < 605) self->openMenu(LOWORD(wparam) - 600); else self->command(LOWORD(wparam)); return 0; @@ -2526,6 +2656,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, if (wparam == openTimer) self->finishOpen(); if (wparam == previewTimer) self->pollImages(); if (wparam == navigationTimer) self->finishNavigation(); + if (wparam == quickViewTimer) self->pollQuickView(); return 0; case trimUndo: if (self->undoBytes >= 32 * TextDocument::pageBytes) @@ -2538,7 +2669,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, return 0; case WM_DESTROY: if(self->cancelNavigation) *self->cancelNavigation=true; - self->updateTaskbarGroup(true); + if(!self->embedded) self->updateTaskbarGroup(true); self->stopPreview(false); self->releaseMenu(); return 0; @@ -2552,7 +2683,8 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, } catch (const std::exception &error) { - self->search.style.message(window, wide(error.what()).c_str()); + if(self->embedded) self->quickError=wide(error.what()); + else self->search.style.message(window, wide(error.what()).c_str()); self->invalidate(); return message == WM_CREATE ? -1 : 0; } @@ -2711,6 +2843,37 @@ HWND findOpenDocument(const std::filesystem::path &path,std::string_view id) return search.match; } +bool registerTextWindowClass(HINSTANCE instance) +{ + static const bool registered=[instance] + { + WNDCLASSW type{}; + type.hInstance=instance; + type.hCursor=LoadCursorW(nullptr,IDC_ARROW); + type.hIcon=LoadIconW(instance,MAKEINTRESOURCEW(1)); + type.lpfnWndProc=TextWindow::procedure; + type.lpszClassName=windowClass; + return Scintilla_RegisterClasses(instance) && RegisterClassW(&type); + }(); + return registered; +} + +HWND createQuickView(HWND owner,TextDialogs dialogs) +{ + const auto instance=GetModuleHandleW(nullptr); + if(!registerTextWindowClass(instance)) return nullptr; + auto state=std::make_shared(std::filesystem::path{},false,dialogs,nullptr, + std::string_view{},TextOpenOptions{},true); + return CreateWindowExW(0,windowClass,L"Quick View",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS, + 0,0,0,0,owner,reinterpret_cast(158),instance,&state); +} + +void previewQuickViewFile(HWND window,const std::filesystem::path &path) +{ + if(const auto preview=textWindows.find(window);preview!=textWindows.end()) + preview->second->previewFile(path); +} + static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options) { @@ -2733,17 +2896,7 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool } const auto instance=GetModuleHandleW(nullptr); - static const bool registered=[instance] - { - WNDCLASSW type{}; - type.hInstance=instance; - type.hCursor=LoadCursorW(nullptr,IDC_ARROW); - type.hIcon=LoadIconW(instance,MAKEINTRESOURCEW(1)); - type.lpfnWndProc=TextWindow::procedure; - type.lpszClassName=windowClass; - return Scintilla_RegisterClasses(instance) && RegisterClassW(&type); - }(); - if(!registered) throw std::runtime_error("Cannot register the text window."); + if(!registerTextWindowClass(instance)) throw std::runtime_error("Cannot register the text window."); auto state=std::make_shared(original,edit,dialogs,backend,fragment,options); const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+ (backend?backend->name+L" · ":std::wstring{})+path.wstring(); diff --git a/src/files_text_window.h b/src/files_text_window.h index 6cb80c2..3816952 100644 --- a/src/files_text_window.h +++ b/src/files_text_window.h @@ -80,6 +80,10 @@ struct RemoteTextSource const RemoteTextRevision &)> upload; }; +inline constexpr UINT quickViewToggleMessage=WM_APP+31; +HWND createQuickView(HWND owner,TextDialogs dialogs); +void previewQuickViewFile(HWND window,const std::filesystem::path &path); + void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false, TextOpenOptions options={}); diff --git a/tests/files_quick_view.ps1 b/tests/files_quick_view.ps1 new file mode 100644 index 0000000..24130fd --- /dev/null +++ b/tests/files_quick_view.ps1 @@ -0,0 +1,101 @@ +param( + [string]$Executable = "$PSScriptRoot/../build/files-cmake/KSwitcher.Files.exe" +) +$ErrorActionPreference = 'Stop' +Add-Type @' +using System; +using System.Runtime.InteropServices; +public static class FilesQuickViewProbe { + [DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr parent, int id); + [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window); + [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window); + [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra); + public static bool Activate(IntPtr window) { + if (GetForegroundWindow() == window) return true; + keybd_event(0x12, 0, 0, UIntPtr.Zero); + keybd_event(0x12, 0, 2, UIntPtr.Zero); + SetForegroundWindow(window); + return GetForegroundWindow() == window; + } +} +'@ + +function Wait-Until([scriptblock]$Condition) { + for ($attempt = 0; $attempt -lt 100; $attempt++) { + if (& $Condition) { return } + Start-Sleep -Milliseconds 50 + } + throw "Timed out waiting for: $Condition" +} + +$exe = (Resolve-Path $Executable).Path +$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files') +$names = 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement' +$saved = @{} +foreach ($name in $names) { + if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) } +} +$fixture = [IO.Directory]::CreateTempSubdirectory('ks-files-quick-view-') +try { + $left = $fixture.CreateSubdirectory('left') + $right = $fixture.CreateSubdirectory('right') + $document = Join-Path $left.FullName 'preview.txt' + [IO.File]::WriteAllText($document, 'Quick View fixture') + $key.SetValue('LeftWide', 1, 'DWord') + $key.SetValue('RightWide', 1, 'DWord') + $key.SetValue('LeftPath', $left.FullName, 'String') + $key.SetValue('RightPath', $right.FullName, 'String') + $key.SetValue('LeftCursor', $document, 'String') + $key.DeleteValue('RightCursor', $false) + $key.DeleteValue('WindowPlacement', $false) + + $process = Start-Process -FilePath $exe -PassThru + Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero } + $window = $process.MainWindowHandle + Wait-Until { [FilesQuickViewProbe]::Activate($window) } + $keyboard = New-Object -ComObject WScript.Shell + $leftList = [FilesQuickViewProbe]::GetDlgItem($window, 102) + $rightList = [FilesQuickViewProbe]::GetDlgItem($window, 103) + $rightHeading = [FilesQuickViewProbe]::GetDlgItem($window, 141) + $rightPath = [FilesQuickViewProbe]::GetDlgItem($window, 143) + if (!($leftList -and $rightList -and $rightHeading -and $rightPath)) { + throw 'Expected both file panels in the test window.' + } + Wait-Until { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) } + $keyboard.SendKeys('^q') + Wait-Until { + $hostWindow = [FilesQuickViewProbe]::GetDlgItem($window, 158) + $hostWindow -ne [IntPtr]::Zero -and [FilesQuickViewProbe]::IsWindowVisible($hostWindow) + } + foreach ($control in $rightList, $rightHeading, $rightPath) { + if ([FilesQuickViewProbe]::IsWindowVisible($control)) { + throw 'A file panel control can draw over the Quick View content.' + } + } + if (![FilesQuickViewProbe]::IsWindowVisible($leftList)) { throw 'Quick View hid the source panel.' } + + $keyboard.SendKeys('^q') + Wait-Until { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero } + foreach ($control in $rightList, $rightHeading, $rightPath) { + if (![FilesQuickViewProbe]::IsWindowVisible($control)) { + throw 'A file panel control remained hidden after closing Quick View.' + } + } + 'Quick View hides the covered list and chrome, then restores the same controls.' +} finally { + if ($process -and !$process.HasExited) { + [void]$process.CloseMainWindow() + if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() } + } + foreach ($name in $names) { + if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) } + else { $key.DeleteValue($name, $false) } + } + $key.Dispose() + $path = [IO.Path]::GetFullPath($fixture.FullName) + if ([IO.Path]::GetDirectoryName($path) -eq [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -and + [IO.Path]::GetFileName($path).StartsWith('ks-files-quick-view-')) { + [IO.Directory]::Delete($path, $true) + } +} From 2a4df70079d4e85572075c1e9c64a91fe2b1684a Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 13:36:50 +0200 Subject: [PATCH 06/61] Copy the full path of the current file panel item Refs #90 --- FILES-UI.md | 4 ++++ src/files_main.cpp | 46 ++++++++++++++++++++++++++++++++++++++++------ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/FILES-UI.md b/FILES-UI.md index 07ef715..3d781d0 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -204,6 +204,10 @@ Warning і початковий фокус на No. Незбережені зміни у примусово закритих вікнах втрачаються. Закриття процесів і результат записуються до `kswitcher.log`. +- **Commands → Copy full path** або **Ctrl+Shift+C** копіює повний шлях + файла чи папки під курсором як текст. У LAN- і FTP-панелях текст включає + адресу віддаленого джерела. Для рядка `..` команда не змінює буфер. + - Ctrl+F вставляє повний шлях елемента під курсором активної панелі в позицію курсора командного рядка або замінює виділення. Подвійні лапки додаються лише до шляхів із пробілами. На рядку `..` вставляється шлях папки, diff --git a/src/files_main.cpp b/src/files_main.cpp index edcd69a..9c2b306 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -1661,12 +1661,18 @@ void clearTerminalSelection() terminalView.post(L"clear-selection"); } +bool copyFilesText(HWND owner,const std::wstring &value,const wchar_t *failure) +{ + try {ks::writeClipboard(owner,ks::textClip(value));} + catch(const std::exception &) {setStatus(failure);return false;} + return true; +} + void copyTerminalText(HWND owner) { const auto value=terminalSelection.empty()?terminalInputText():terminalSelection; if(value.empty()) return; - try { ks::writeClipboard(owner,ks::textClip(value)); } - catch(const std::exception &) { setStatus(L"Could not copy terminal text."); } + copyFilesText(owner,value,L"Could not copy terminal text."); } LRESULT currentPanelRow(const Panel &panel) @@ -1703,8 +1709,29 @@ void copyPanelNames(HWND owner) names+=path.filename().native(); } if(names.empty()) return; - try { ks::writeClipboard(owner,ks::textClip(names)); } - catch(const std::exception &) { setStatus(L"Could not copy file names."); } + copyFilesText(owner,names,L"Could not copy file names."); +} + +void copyFullPanelPath(HWND owner,const Panel &panel) +{ + const auto row=currentPanelRow(panel); + if(row==LB_ERR || panel.sizes[row]==L"Up" || ftpProfileList(panel)) return; + const auto &path=panel.rows[row]; + auto value=path.native(); + if(panel.ftp) + { + const auto &profile=*panel.ftp; + const auto host=profile.host.find(L':')!=std::wstring::npos && !profile.host.starts_with(L"[")? + L"["+profile.host+L"]":profile.host; + value=L"FTP "+host+L":"+std::to_wstring(profile.port)+L" · "+ftpPath(path); + } + else if(panel.peer) + { + auto host=panel.peer->name; + if(!panel.peer->address.empty()) host+=L" ("+ks::wide(panel.peer->address)+L")"; + value=host+L" · "+value; + } + if(copyFilesText(owner,value,L"Could not copy the full path.")) setStatus(L"Full path copied."); } void copyCommandLineOrPanelNames(HWND owner) @@ -2907,6 +2934,7 @@ void selectDrive() else if(menuIndex==2 && row==8) compareSelectedFiles(owner); else if(menuIndex==2 && row==9) findLocalFiles(owner,panels[active]); else if(menuIndex==2 && row==10) toggleQuickView(owner); + else if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]); else { const int command=menuIndex==1?113+static_cast(row):110+static_cast(row); @@ -6645,12 +6673,13 @@ void openMenu(HWND window, int index) rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts", L"View externally\tAlt+F3",L"Edit externally\tAlt+F4", L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(), - L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q"}; + L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q", + L"Copy full path\tCtrl+Shift+C"}; } commandActions.clear(); if(index==2) { - commandActions={0,3,-1,1,2,4,5,8}; + commandActions={0,3,11,-1,1,2,4,5,8}; if(!panels[active].peer && !panels[active].ftp) commandActions.insert(commandActions.begin()+1,9); if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10); if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7}); @@ -7829,6 +7858,11 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0; const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0; + if(ctrl && shift && message.wParam=='C' && !terminalVisible && commandLineAvailable(window)) + { + if(!(message.lParam & (1LL<<30))) copyFullPanelPath(window,panels[active]); + continue; + } if(shift && !ctrl && message.wParam==VK_F4 && !terminalVisible) { if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window)) From 07ed4cf724f05d9cf8d13aed15e11c29357fae66 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 13:50:30 +0200 Subject: [PATCH 07/61] Support Windows file clipboard in Files Refs #91 --- FILES-UI.md | 7 +++ src/files_main.cpp | 93 +++++++++++++++++++++++++++++++---- src/files_path_navigation.inl | 1 + src/platform.cpp | 71 ++++++++++++++++++++++++++ src/platform.h | 3 ++ 5 files changed, 165 insertions(+), 10 deletions(-) diff --git a/FILES-UI.md b/FILES-UI.md index 3d781d0..6995cf3 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -204,6 +204,13 @@ Warning і початковий фокус на No. Незбережені зміни у примусово закритих вікнах втрачаються. Закриття процесів і результат записуються до `kswitcher.log`. +- У файловій панелі Ctrl+C копіює позначені або поточний локальний + елемент у файловий буфер Windows. Ctrl+V вставляє файли й папки в + поточний локальний каталог через звичайний діалог Copy і показує + конфлікти та прогрес. Клік або навігація у файловій панелі вибирають + файловий контекст. Клік у командному рядку або введення тексту + повертають текстовий контекст Ctrl+C / Ctrl+V. + - **Commands → Copy full path** або **Ctrl+Shift+C** копіює повний шлях файла чи папки під курсором як текст. У LAN- і FTP-панелях текст включає адресу віддаленого джерела. Для рядка `..` команда не змінює буфер. diff --git a/src/files_main.cpp b/src/files_main.cpp index 9c2b306..490cd3c 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -508,6 +508,7 @@ std::wstring panelCaption(const Panel &panel) Panel panels[2]; HWND quickViewWindow{}; int quickViewSource{}; +bool panelClipboardContext=true; void refreshQuickView(const Panel &panel); void toggleQuickView(HWND owner); FilesTerminal terminal; @@ -1712,6 +1713,23 @@ void copyPanelNames(HWND owner) copyFilesText(owner,names,L"Could not copy file names."); } +void copyPanelFiles(HWND owner,const Panel &panel) +{ + if(panel.peer || panel.ftp) + { + setStatus(L"File clipboard copy requires local files."); + return; + } + const auto paths=selectedPanelPaths(panel); + if(paths.empty()) return; + try + { + ks::writeClipboard(owner,ks::fileDropClip(paths)); + setStatus(std::to_wstring(paths.size())+(paths.size()==1?L" item copied":L" items copied")+L" to the file clipboard."); + } + catch(const std::exception &) {setStatus(L"Could not copy files to the clipboard.");} +} + void copyFullPanelPath(HWND owner,const Panel &panel) { const auto row=currentPanelRow(panel); @@ -2023,6 +2041,7 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U if(message==WM_KILLFOCUS) resetCompletion(); if(message==WM_LBUTTONDOWN || message==WM_RBUTTONDOWN) { + panelClipboardContext=false; clearTerminalSelection(); hideCompletion(); } @@ -2067,7 +2086,11 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U } if(message==WM_KEYDOWN && !terminalVisible && wp==VK_TAB) { - if(plainPanelTab()) activatePanel(1-active); + if(plainPanelTab()) + { + panelClipboardContext=true; + activatePanel(1-active); + } return 0; } if(message==WM_KEYDOWN && !terminalVisible && @@ -3599,7 +3622,7 @@ struct CopyRequest std::future validation; std::wstring ftpDestination; bool upload{}; - bool ftpRename{}; + bool ftpRename{}, externalSources{}; }; bool directoryExists(const FilesPeer *peer,const fs::path &path) @@ -4213,9 +4236,10 @@ CopyDestination validateCopyDestination(CopyRequest request,const std::wstring & else request.newName.clear(); } const auto sourceDirectory=request.sources.front().parent_path(); - const auto destination=request.move || request.newName.empty()?request.destination:sourceDirectory; + const bool renameInSource=!request.externalSources && !request.move && !request.newName.empty(); + const auto destination=renameInSource?sourceDirectory:request.destination; std::error_code error; - const auto peer=request.move || request.newName.empty()?request.destinationPeer:request.sourcePeer; + const auto peer=renameInSource?request.sourcePeer:request.destinationPeer; if(!directoryExists(peer,destination)) throw std::runtime_error(ks::utf8(L"The destination folder is unavailable.")); const bool sameHost=(!peer && !request.sourcePeer) || @@ -4373,6 +4397,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) snapshot.move=request.move; snapshot.ftpDestination=request.ftpDestination; snapshot.upload=request.upload; + snapshot.externalSources=request.externalSources; std::packaged_task validation( [snapshot=std::move(snapshot),value=std::move(value), source=peer(request.sourcePeer),other=peer(request.otherPeer)]() mutable { @@ -5429,7 +5454,7 @@ void pruneSearchResults(Panel &panel,const std::set &removed) updateSelectionSummary(panel); } -void copySelection(HWND owner,Panel &source,Panel &destination,bool move) +void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::vector external={}) { const auto sourceFtp=source.ftp; const bool ftpRename=move && sourceFtp && !ftpProfileList(source); @@ -5465,6 +5490,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) CopyRequest request{{},ftpRename?source.directory:destination.directory}; request.move=move; request.ftpRename=ftpRename; + request.externalSources=!external.empty(); if(ftp) { request.ftpDestination=panelLocation(destination); @@ -5473,7 +5499,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) request.otherDirectory=destination.directory; request.sourcePeer=source.peer?&*source.peer:nullptr; request.otherPeer=request.destinationPeer=destination.peer?&*destination.peer:nullptr; - request.sources=selectedPanelPaths(source); + request.sources=request.externalSources?std::move(external):selectedPanelPaths(source); if(request.sources.empty()) return; if(ftpRename && request.sources.size()!=1) { @@ -5486,7 +5512,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) if(result!=IDOK) return; const bool renamed=!request.newName.empty(); - const bool renameInSource=renamed && !move && !ftp; + const bool renameInSource=renamed && !move && !ftp && !request.externalSources; const auto targetDirectory=renameInSource?request.sources.front().parent_path():request.destination; const auto *targetPeer=renameInSource?request.sourcePeer:request.destinationPeer; const auto peerId=[](const FilesPeer *peer){return peer?peer->id:std::string{};}; @@ -5578,7 +5604,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move) ++copied; if(move && fromSearch) removed.insert(path); results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget); - progress.ui.invoke([&] { + if(!request.externalSources) progress.ui.invoke([&] { const auto row=std::find(source.rows.begin(),source.rows.end(),path); if(row!=source.rows.end()) source.marked[row-source.rows.begin()]=false; InvalidateRect(source.list,nullptr,FALSE); @@ -6042,8 +6068,33 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) warningBrush=nullptr; } +bool pastePanelFiles(HWND owner,Panel &panel) +{ + if(!IsClipboardFormatAvailable(CF_HDROP)) return false; + if(panel.peer || panel.ftp || panel.findOrigin) + { + setStatus(L"Open a local folder before pasting files."); + return true; + } + std::vector paths; + try {paths=ks::readClipboardFilePaths(owner);} + catch(const std::exception &) + { + setStatus(L"Could not read file paths from the clipboard."); + return true; + } + if(paths.empty()) + { + setStatus(L"The clipboard has no usable file paths."); + return true; + } + copySelection(owner,panel,panel,false,std::move(paths)); + return true; +} + void selectPanelEdge(Panel &panel,bool first) { + panelClipboardContext=true; activatePanel(static_cast(&panel-panels)); const auto count=SendMessageW(panel.list,LB_GETCOUNT,0,0); if(count<=0) return; @@ -6459,7 +6510,11 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT if(message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK || (message==WM_MOUSEMOVE && (wp&MK_LBUTTON) && GetCapture()==window)) { - if(message==WM_LBUTTONDOWN) clearTerminalSelection(); + if(message==WM_LBUTTONDOWN) + { + panelClipboardContext=true; + clearTerminalSelection(); + } auto &panel=panels[index]; const auto count=SendMessageW(window,LB_GETCOUNT,0,0); if(count<=0) @@ -6512,6 +6567,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT const bool rangeKey=wp==VK_UP || wp==VK_DOWN || wp==VK_LEFT || wp==VK_RIGHT; if(message==WM_KEYDOWN && (wp==VK_INSERT || (rangeKey && (GetKeyState(VK_SHIFT)&0x8000)))) { + panelClipboardContext=true; auto &panel=panels[index]; const auto row=SendMessageW(window,LB_GETCURSEL,0,0); if(row<0 || static_cast(row)>=panel.marked.size()) return 0; @@ -6553,6 +6609,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT { if(plainPanelTab()) { + panelClipboardContext=true; activatePanel(1-index); SetFocus(terminalInput); } @@ -6598,7 +6655,11 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT (wp==VK_UP || wp==VK_DOWN || wp==VK_PRIOR || wp==VK_NEXT || wp==VK_HOME || wp==VK_END); const auto previous=movesCursor?SendMessageW(window,LB_GETCURSEL,0,0):LB_ERR; auto result=DefSubclassProc(window,message,wp,lp); - if(movesCursor) invalidatePanelCursorChange(window,previous); + if(movesCursor) + { + panelClipboardContext=true; + invalidatePanelCursorChange(window,previous); + } if(message==WM_LBUTTONUP && GetFocus()==window) restoreCommandFocus(); if(message==WM_PAINT && hasPanelSizeColumn(panels[index])) { @@ -7545,6 +7606,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) case WM_COMMAND: if(reinterpret_cast(lp)==terminalInput && HIWORD(wp)==EN_CHANGE) { + panelClipboardContext=false; clearTerminalSelection(); resetCompletion(); } @@ -7858,6 +7920,17 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0; const bool shift=(GetKeyState(VK_SHIFT)&0x8000)!=0; + const bool fileClipboard=!terminalVisible && (panelFocused || panelClipboardContext) && + commandLineAvailable(window); + if(fileClipboard && ctrl && !shift && (message.wParam=='C' || message.wParam=='V')) + { + if(!(message.lParam&(1LL<<30))) + { + if(message.wParam=='C') copyPanelFiles(window,panels[active]); + else if(!pastePanelFiles(window,panels[active])) SendMessageW(terminalInput,WM_PASTE,0,0); + } + continue; + } if(ctrl && shift && message.wParam=='C' && !terminalVisible && commandLineAvailable(window)) { if(!(message.lParam & (1LL<<30))) copyFullPanelPath(window,panels[active]); diff --git a/src/files_path_navigation.inl b/src/files_path_navigation.inl index b2ab625..3415f20 100644 --- a/src/files_path_navigation.inl +++ b/src/files_path_navigation.inl @@ -331,6 +331,7 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_ ReleaseCapture(); const int index=GetDlgCtrlID(window)-142; if(index<0 || index>=2) return 0; + panelClipboardContext=true; auto &panel=panels[index]; if(!localNavigationAvailable(panel)) { diff --git a/src/platform.cpp b/src/platform.cpp index 978f588..fd9f044 100644 --- a/src/platform.cpp +++ b/src/platform.cpp @@ -486,6 +486,77 @@ Clip textClip(const std::wstring &text) memcpy(f.data.data(), text.c_str(), f.data.size()); return Clip{{std::move(f)}}; } + +Clip fileDropClip(std::span paths) +{ + std::wstring names; + for(const auto &path:paths) + { + if(!path.is_absolute() || path.native().find(L'\0')!=std::wstring::npos) + throw std::invalid_argument("A file clipboard path must be absolute and contain no nulls."); + names+=path.native(); + names+=L'\0'; + } + if(paths.empty()) names+=L'\0'; + names+=L'\0'; + DROPFILES header{}; + header.pFiles=sizeof(header); + header.fWide=TRUE; + Format files{CF_HDROP,{},Bytes(sizeof(header)+names.size()*sizeof(wchar_t))}; + memcpy(files.data.data(),&header,sizeof(header)); + memcpy(files.data.data()+sizeof(header),names.data(),names.size()*sizeof(wchar_t)); + const DWORD effect=DROPEFFECT_COPY; + Format preferred{0,CFSTR_PREFERREDDROPEFFECT,Bytes(sizeof(effect))}; + memcpy(preferred.data.data(),&effect,sizeof(effect)); + return Clip{{std::move(files),std::move(preferred)}}; +} + +std::vector fileDropPaths(HANDLE medium) +{ + const auto size=medium?GlobalSize(medium):0; + if(size(GlobalLock(medium)); + if(!bytes) return {}; + DROPFILES header{}; + memcpy(&header,bytes,sizeof(header)); + bool terminated=false; + if(header.pFiles>=sizeof(header) && header.pFiles(0))!=bytes+size; + else if(header.pFiles%alignof(wchar_t)==0) + { + const auto names=reinterpret_cast(start); + const auto end=names+(size-header.pFiles)/sizeof(wchar_t); + terminated=std::search_n(names,end,2,L'\0')!=end; + } + } + GlobalUnlock(medium); + if(!terminated) return {}; + const auto drop=reinterpret_cast(medium); + const UINT count=DragQueryFileW(drop,UINT(-1),nullptr,0); + std::vector paths; + std::set seen; + for(UINT index=0;index32767) continue; + std::wstring name(length+1,L'\0'); + if(DragQueryFileW(drop,index,name.data(),length+1)!=length) continue; + name.resize(length); + auto path=std::filesystem::path(std::move(name)).lexically_normal(); + if(path.is_absolute() && seen.insert(path).second) paths.push_back(std::move(path)); + } + return paths; +} + +std::vector readClipboardFilePaths(HWND window) +{ + ClipboardLock lock(window); + return fileDropPaths(GetClipboardData(CF_HDROP)); +} + std::wstring Clip::text() const { for (const auto &f : formats) diff --git a/src/platform.h b/src/platform.h index 20d2429..7e0b1e4 100644 --- a/src/platform.h +++ b/src/platform.h @@ -59,6 +59,9 @@ Clip readClipboard(HWND, size_t limit = 32 * 1024 * 1024, DWORD writeClipboard(HWND, const Clip &); DWORD writeClipboardGuarded(HWND, const Clip &, std::optional expected); Clip textClip(const std::wstring &); +Clip fileDropClip(std::span paths); +std::vector fileDropPaths(HANDLE medium); +std::vector readClipboardFilePaths(HWND window); bool chord(WORD key, UINT modifiers = 0); bool chord(std::span keys); struct SystemVolume From 31473baa49acf858f4b0a0d7860e1d119f47044a Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 14:01:43 +0200 Subject: [PATCH 08/61] Add Windows file drag and drop to Files Refs #92 --- FILES-UI.md | 11 ++ src/files_drag_drop.inl | 239 ++++++++++++++++++++++++++++++++++++++++ src/files_main.cpp | 83 ++++++++++---- 3 files changed, 309 insertions(+), 24 deletions(-) create mode 100644 src/files_drag_drop.inl diff --git a/FILES-UI.md b/FILES-UI.md index 6995cf3..06e90f4 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -555,6 +555,17 @@ Warning і початковий фокус на No. - Розкриті списки й історія Far використовують спільний попап із бірюзовим тлом, світлою рамкою та чорним вибраним рядком. Попап прилягає до обох країв бірюзового поля, стрілка лишається праворуч за межами списку. Історія групується за датами. Довгі списки прокручуються, Enter вибирає рядок, Escape закриває список і повертає фокус до поля. - Повторно використовуй спільне оформлення. Текст, дії та стан операції передавай із коду конкретної операції. Наприклад, Warning повертає відповідь і стан прапорця, а копіювання вирішує, чи застосувати відповідь до наступних конфліктів. +## Перетягування файлів + +- Перетягування з Explorer або іншої локальної панелі відкриває діалог + Drop files із повним шляхом призначення та кнопками Copy, Move і Cancel. + Якщо курсор над папкою, призначенням є ця папка. В інших випадках + призначенням є поточна папка панелі. Cancel або Esc скасовує дію. +- Copy і Move відкривають наявний діалог операції з її параметрами, + перевіркою призначення, розв’язанням конфліктів і прогресом. Віддалені + панелі, результати пошуку й віртуальні елементи Explorer без локального + шляху не підтримують перетягування. Files повідомляє причину в рядку стану. + ## Діалог Copy - Вирівнюй підпис Existing files по вертикальному центру списку. Ширше поле списку починається ближче до підпису, а його правий край збігається з правим краєм поля імені. diff --git a/src/files_drag_drop.inl b/src/files_drag_drop.inl new file mode 100644 index 0000000..065f760 --- /dev/null +++ b/src/files_drag_drop.inl @@ -0,0 +1,239 @@ +constexpr UINT panelDropReady=WM_APP+33; + +struct PanelDrop +{ + HWND source{}, target{}; + fs::path directory, destination; + std::vector paths; +}; + +std::optional pendingPanelDrop; +HWND draggingPanel{}; +std::optional panelDragStart; + +bool localDropPanel(const Panel &panel) +{ + return !panel.peer && !panel.ftp && !panel.findOrigin && panel.directory.is_absolute(); +} + +LRESULT panelRowAt(HWND window,POINT point,LRESULT top,LRESULT count) +{ + const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,MAKELPARAM(point.x,point.y)); + // LB_ITEMFROMPOINT only returns the low 16 bits of the row index. + constexpr LRESULT rowRange=1<<16; + auto row=(top&~(rowRange-1))|LOWORD(hit); + if(row=0 && row(&bounds))!=LB_ERR && + PtInRect(&bounds,point)?row:LB_ERR; +} + +FORMATETC fileDropFormat() +{ + return {CF_HDROP,nullptr,DVASPECT_CONTENT,-1,TYMED_HGLOBAL}; +} + +template +class DragInterface : public Interface +{ +public: + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid,void **out) override + { + if(!out) return E_POINTER; + *out=nullptr; + if(iid!=IID_IUnknown && iid!=__uuidof(Interface)) return E_NOINTERFACE; + *out=static_cast(this); + AddRef(); + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override {return ++references;} + ULONG STDMETHODCALLTYPE Release() override + { + const auto count=--references; + if(!count) delete static_cast(this); + return count; + } + +private: + ULONG references{1}; +}; + +class PanelDropTarget final : public DragInterface +{ +public: + explicit PanelDropTarget(HWND window) : target(window) {} + + HRESULT STDMETHODCALLTYPE DragEnter(IDataObject *data,DWORD,POINTL,DWORD *effect) override + { + auto format=fileDropFormat(); + filesystem=data->QueryGetData(&format)==S_OK; + return updateEffect(effect); + } + HRESULT STDMETHODCALLTYPE DragOver(DWORD,POINTL,DWORD *effect) override + { + return updateEffect(effect); + } + HRESULT STDMETHODCALLTYPE DragLeave() override + { + filesystem=false; + return S_OK; + } + HRESULT STDMETHODCALLTYPE Drop(IDataObject *data,DWORD,POINTL location,DWORD *effect) override + { + updateEffect(effect); + filesystem=false; + if(*effect==DROPEFFECT_NONE) return S_OK; + *effect=DROPEFFECT_NONE; + auto format=fileDropFormat(); + STGMEDIUM medium{}; + if(FAILED(data->GetData(&format,&medium))) + { + setStatus(L"Could not read local paths from the drop."); + return S_OK; + } + std::vector paths; + try + { + if(medium.tymed==TYMED_HGLOBAL) paths=ks::fileDropPaths(medium.hGlobal); + } + catch(const std::exception &) {} + ReleaseStgMedium(&medium); + if(paths.empty()) + { + setStatus(L"The drop contains no usable file or folder paths."); + return S_OK; + } + + try + { + const auto &panel=panels[GetDlgCtrlID(target)-102]; + POINT point{location.x,location.y}; + ScreenToClient(target,&point); + const auto row=panelRowAt(target,point,SendMessageW(target,LB_GETTOPINDEX,0,0), + static_cast(panel.rows.size())); + const auto &destination=row!=LB_ERR && panel.sizes[row]==L"Folder"?panel.rows[row]:panel.directory; + pendingPanelDrop=PanelDrop{draggingPanel,target,panel.directory,destination,std::move(paths)}; + if(PostMessageW(GetParent(target),panelDropReady,0,0)) + { + // Files performs the requested move after confirmation. + *effect=DROPEFFECT_COPY; + } + else pendingPanelDrop.reset(); + } + catch(const std::exception &) + { + setStatus(L"Could not prepare the drop."); + } + return S_OK; + } + +private: + HRESULT updateEffect(DWORD *effect) + { + const auto allowed=*effect; + *effect=DROPEFFECT_NONE; + if(!filesystem || !(allowed&DROPEFFECT_COPY)) + setStatus(L"Drag files or folders from a Windows filesystem."); + else if(target==draggingPanel) + setStatus(L"Drop files onto the other panel."); + else if(!localDropPanel(panels[GetDlgCtrlID(target)-102])) + setStatus(L"Open a local folder in the destination panel before dropping files."); + else if(!copyInProgress && !pendingPanelDrop && !FilesModalDialog::activeFor(GetParent(target))) + *effect=DROPEFFECT_COPY; + return S_OK; + } + + HWND target; + bool filesystem{}; +}; + +class PanelDragSource final : public DragInterface +{ +public: + HRESULT STDMETHODCALLTYPE QueryContinueDrag(BOOL escape,DWORD keys) override + { + if(escape) return DRAGDROP_S_CANCEL; + return keys&MK_LBUTTON?S_OK:DRAGDROP_S_DROP; + } + HRESULT STDMETHODCALLTYPE GiveFeedback(DWORD) override {return DRAGDROP_S_USEDEFAULTCURSORS;} +}; + +void beginPanelDrag(HWND window) +{ + auto &panel=panels[GetDlgCtrlID(window)-102]; + if(!localDropPanel(panel)) + { + setStatus(L"Drag files or folders from an open local folder."); + return; + } + auto paths=selectedPanelPaths(panel); + if(paths.empty()) return; + std::vector items; + items.reserve(paths.size()); + const auto clear=[&](void *){for(auto item:items) CoTaskMemFree(const_cast(item));}; + const std::unique_ptr cleanup(&items,clear); + for(const auto &path:paths) + { + PIDLIST_ABSOLUTE item{}; + if(FAILED(SHParseDisplayName(path.c_str(),nullptr,&item,0,nullptr))) + { + setStatus(L"Windows could not prepare the selected files or folders for dragging."); + return; + } + items.push_back(item); + } + IShellItemArray *array{}; + if(FAILED(SHCreateShellItemArrayFromIDLists(static_cast(items.size()),items.data(),&array))) + { + setStatus(L"Windows could not prepare the selected files or folders for dragging."); + return; + } + IDataObject *data{}; + const auto result=array->BindToHandler(nullptr,BHID_DataObject,IID_PPV_ARGS(&data)); + array->Release(); + if(FAILED(result)) + { + setStatus(L"Windows could not prepare the selected files or folders for dragging."); + return; + } + const auto source=new(std::nothrow) PanelDragSource; + if(source) + { + draggingPanel=window; + DWORD effect{}; + DoDragDrop(data,source,DROPEFFECT_COPY,&effect); + draggingPanel=nullptr; + source->Release(); + } + data->Release(); +} + +void performPanelDrop(HWND owner) +{ + if(!pendingPanelDrop) return; + auto drop=std::move(*pendingPanelDrop); + pendingPanelDrop.reset(); + auto index=GetDlgCtrlID(drop.target)-102; + if(index<0 || index>=static_cast(std::size(panels))) return; + auto &panel=panels[index]; + if(!localDropPanel(panel) || panel.directory!=drop.directory || !IsWindowVisible(drop.target)) + { + setStatus(L"The destination panel changed. Drop the files again."); + return; + } + if(copyInProgress || FilesModalDialog::activeFor(owner)) + { + setStatus(L"Finish the current operation before dropping files."); + return; + } + + const auto text=L"Destination folder:\r\n"+drop.destination.native(); + const auto answer=showFilesNotice(owner,text.c_str(),L"Drop files", + {.tone=FilesNoticeTone::neutral,.chooseTransfer=true}); + if(answer!=IDYES && answer!=IDNO) return; + auto &source=drop.source?panels[GetDlgCtrlID(drop.source)-102]:panel; + activatePanel(index); + panelClipboardContext=true; + copySelection(owner,source,panel,answer==IDNO,std::move(drop.paths),std::move(drop.destination)); +} diff --git a/src/files_main.cpp b/src/files_main.cpp index 490cd3c..6a69336 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -648,7 +648,7 @@ struct FilesNoticeOptions bool *remember{}; FilesNoticeTone tone{FilesNoticeTone::dialog}; bool processes{}; - bool saveChanges{}; + bool saveChanges{}, chooseTransfer{}; }; INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={}); void openMenu(HWND window, int index); @@ -4309,7 +4309,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) SetDlgItemTextW(dialog,pathField,!single && !request.ftpDestination.empty()? request.ftpDestination.c_str():fieldText.c_str()); SendDlgItemMessageW(dialog,pathField,EM_SETREADONLY,!single && !request.move,0); - if(request.move) SetDlgItemTextW(dialog,IDOK,L"&Rename"); + if(request.move) SetDlgItemTextW(dialog,IDOK,request.externalSources?L"&Move":L"&Rename"); fitFarEditToLine(GetDlgItem(dialog,pathField)); layoutDialogButtons(dialog,214,{IDOK,IDCANCEL}); installFarCheckbox(GetDlgItem(dialog,214),FarCheckboxSurface::gray); @@ -4837,7 +4837,7 @@ void layoutFilesNotice(HWND dialog) bottom+=textHeight; } place(102,bottom+dialogRowGap()+4,1); - if(notice.options.saveChanges) layoutDialogButtons(dialog,102,{IDYES,IDNO,IDCANCEL}); + if(notice.options.saveChanges || notice.options.chooseTransfer) layoutDialogButtons(dialog,102,{IDYES,IDNO,IDCANCEL}); else if(notice.options.confirm) layoutDialogButtons(dialog,102,{IDYES,IDNO}); else if(notice.options.processes) layoutDialogButtons(dialog,102,{showProcessesButton,IDOK}); else layoutDialogButtons(dialog,102,{IDOK}); @@ -4861,7 +4861,7 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) notice.options.tone==FilesNoticeTone::neutral?FarCheckboxSurface::gray:FarCheckboxSurface::dialog); ShowWindow(checkbox,SW_SHOW); } - if(notice.options.confirm || notice.options.saveChanges) + if(notice.options.confirm || notice.options.saveChanges || notice.options.chooseTransfer) { ShowWindow(GetDlgItem(window,IDOK),SW_HIDE); ShowWindow(GetDlgItem(window,IDYES),SW_SHOW); @@ -4873,6 +4873,13 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) SetDlgItemTextW(window,IDNO,L"&Discard"); ShowWindow(GetDlgItem(window,IDCANCEL),SW_SHOW); } + if(notice.options.chooseTransfer) + { + SetDlgItemTextW(window,IDYES,L"&Copy"); + SetDlgItemTextW(window,IDNO,L"&Move"); + SetDlgItemTextW(window,IDCANCEL,L"Ca&ncel"); + ShowWindow(GetDlgItem(window,IDCANCEL),SW_SHOW); + } if(notice.options.processes) ShowWindow(GetDlgItem(window,showProcessesButton),SW_SHOW); RECT caption{},text{}; if(const auto dc=GetDC(window)) @@ -4885,12 +4892,12 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) } const auto inset=dialogFrameMetrics(GetDpiForWindow(window)).content(); const auto minimum=std::max({24L*cellWidth,caption.right+6*cellWidth, - notice.options.remember || notice.options.processes || notice.options.saveChanges?34L*cellWidth:0L})+2*inset; + notice.options.remember || notice.options.processes || notice.options.saveChanges || notice.options.chooseTransfer?34L*cellWidth:0L})+2*inset; const auto width=std::clamp(text.right+cellWidth+2*inset,minimum,std::max(minimum,60L*cellWidth+2*inset)); SetWindowPos(window,nullptr,0,0,width,1,SWP_NOMOVE|SWP_NOZORDER|SWP_NOACTIVATE); layoutFilesNotice(window); FilesModalDialog::fitWidthToOwner(window,minimum,layoutFilesNotice); - const auto defaultButton=notice.options.saveChanges?IDCANCEL:notice.options.confirm?IDNO:IDOK; + const auto defaultButton=(notice.options.saveChanges || notice.options.chooseTransfer)?IDCANCEL:notice.options.confirm?IDNO:IDOK; SendMessageW(window,DM_SETDEFID,defaultButton,0); SetFocus(GetDlgItem(window,defaultButton)); return FALSE; @@ -5454,7 +5461,8 @@ void pruneSearchResults(Panel &panel,const std::set &removed) updateSelectionSummary(panel); } -void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::vector external={}) +void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::vector external={}, + fs::path targetFolder={}) { const auto sourceFtp=source.ftp; const bool ftpRename=move && sourceFtp && !ftpProfileList(source); @@ -5487,7 +5495,8 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve setStatus(L"A copy is already in progress."); return; } - CopyRequest request{{},ftpRename?source.directory:destination.directory}; + if(targetFolder.empty()) targetFolder=ftpRename?source.directory:destination.directory; + CopyRequest request{{},targetFolder}; request.move=move; request.ftpRename=ftpRename; request.externalSources=!external.empty(); @@ -5496,7 +5505,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve request.ftpDestination=panelLocation(destination); request.upload=destinationFtp.has_value(); } - request.otherDirectory=destination.directory; + request.otherDirectory=ftpRename?destination.directory:targetFolder; request.sourcePeer=source.peer?&*source.peer:nullptr; request.otherPeer=request.destinationPeer=destination.peer?&*destination.peer:nullptr; request.sources=request.externalSources?std::move(external):selectedPanelPaths(source); @@ -5643,12 +5652,12 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve { if(fromSearch) pruneSearchResults(source,removed); else open(source,source.directory); - if(!ftpRename) open(destination,destination.directory); + if(!ftpRename && &source!=&destination) open(destination,destination.directory); if(!fromSearch && renamed && copied && (sameHost || ftpRename)) { const auto renamedPath=progress.renamedTarget.empty()? targetDirectory/request.newName:progress.renamedTarget; - selectPanelPath(source,renamedPath); + selectPanelPath(request.externalSources?destination:source,renamedPath); } } else @@ -6504,9 +6513,25 @@ void openOrCreateText(HWND owner,const Panel &panel) void editFtpProfile(Panel &panel,bool create); +#include "files_drag_drop.inl" + LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR) { const auto index=GetDlgCtrlID(window)-102; + if(message==WM_NCDESTROY) RevokeDragDrop(window); + if(message==WM_CAPTURECHANGED) panelDragStart.reset(); + if(message==WM_MOUSEMOVE && (wp&MK_LBUTTON) && GetCapture()==window && panelDragStart) + { + const auto dpi=GetDpiForWindow(window); + if(std::abs(GET_X_LPARAM(lp)-panelDragStart->x)>=GetSystemMetricsForDpi(SM_CXDRAG,dpi) || + std::abs(GET_Y_LPARAM(lp)-panelDragStart->y)>=GetSystemMetricsForDpi(SM_CYDRAG,dpi)) + { + ReleaseCapture(); + beginPanelDrag(window); + restoreCommandFocus(); + } + return 0; + } if(message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK || (message==WM_MOUSEMOVE && (wp&MK_LBUTTON) && GetCapture()==window)) { @@ -6523,16 +6548,9 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT return 0; } const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; - // LB_ITEMFROMPOINT only returns the low 16 bits of the row index. - const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp); const auto top=SendMessageW(window,LB_GETTOPINDEX,0,0); - constexpr LRESULT rowRange=1<<16; - auto row=(top&~(rowRange-1))|LOWORD(hit); - if(row(&bounds))!=LB_ERR && - PtInRect(&bounds,point); + const auto row=panelRowAt(window,point,top,count); + const bool rowHit=row!=LB_ERR; const auto previous=SendMessageW(window,LB_GETCURSEL,0,0); const auto target=rowHit?row:point.y>=0 && message==WM_LBUTTONDOWN?count-1:previous; if(target!=previous && index!=active) @@ -6554,7 +6572,11 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT invalidatePanelCursorChange(window,previous); } activatePanel(index); - if(message==WM_LBUTTONDOWN) SetCapture(window); + if(message==WM_LBUTTONDOWN) + { + if(rowHit && panel.sizes[row]!=L"Up") panelDragStart=point; + SetCapture(window); + } if(message==WM_LBUTTONDBLCLK && rowHit) enter(panel); return 0; } @@ -6998,6 +7020,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) case ks::files::quickViewToggleMessage: if(quickViewWindow && !copyInProgress && !FilesModalDialog::activeFor(window)) toggleQuickView(window); return 0; + case panelDropReady: + performPanelDrop(window); + return 0; case directoryScanReady: if(!FilesModalDialog::activeFor(window)) collectDirectoryScans(); return 0; @@ -7109,6 +7134,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) openOn(panel,saved.is_absolute()?saved:root,false,{},savedPanelPath(panelCursorKeys[i]), saved.is_absolute() && saved!=root?root:fs::path{}); SetWindowSubclass(panel.list, panelKeys, 1, 0); + if(auto target=new(std::nothrow) PanelDropTarget(panel.list)) + { + RegisterDragDrop(panel.list,target); + target->Release(); + } SetWindowSubclass(panel.path,pathBarInput,1,0); installScrollBar(panel.list,window,firstPanelScrollBar+i); } @@ -7659,6 +7689,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) DestroyWindow(window); return 0; case WM_DESTROY: + pendingPanelDrop.reset(); for(auto &panel:panels) if(panel.folderSizeJob) panel.folderSizeJob->stop.request_stop(); KillTimer(window,terminalTimer); @@ -7736,12 +7767,16 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) type.lpszClassName = L"KSwitcher.Files"; if (!registerFarEdit(instance) || !RegisterClassW(&type)) return 1; + const auto com=OleInitialize(nullptr); auto window = CreateWindowW(type.lpszClassName, L"KSwitcher Files — local prototype", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, CW_USEDEFAULT, 900, 540, nullptr, nullptr, instance, nullptr); - if (!window) return 1; + if(!window) + { + if(SUCCEEDED(com)) OleUninitialize(); + return 1; + } if(!restorePlacement(window)) ShowWindow(window, show); SetFocus(terminalInput); - const auto com=CoInitializeEx(nullptr,COINIT_APARTMENTTHREADED); MSG message{}; for(;;) { @@ -8055,6 +8090,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) DeleteObject(blue); DeleteObject(teal); DeleteObject(terminalBackground); - if(SUCCEEDED(com)) CoUninitialize(); + if(SUCCEEDED(com)) OleUninitialize(); return 0; } From 2545886092917610a4328c6537f63159e65484e9 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 14:12:11 +0200 Subject: [PATCH 09/61] Add per-panel sorting and file filters Refs #93 --- FILES-UI.md | 21 ++- src/files_find.inl | 47 ++++- src/files_find_scan.inl | 3 +- src/files_main.cpp | 383 ++++++++++++++++++++++++++++---------- src/files_panel_order.inl | 51 +++++ 5 files changed, 394 insertions(+), 111 deletions(-) create mode 100644 src/files_panel_order.inl diff --git a/FILES-UI.md b/FILES-UI.md index 06e90f4..c260d7a 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -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–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options. +- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F9 керують сортуванням і фільтром активної панелі. Ctrl+F10–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options. ## Налаштування Files @@ -489,8 +489,23 @@ Warning і початковий фокус на No. - Process multiple names дозволяє розділити імена комами або крапками з комою. Якщо такий символ є частиною імені, візьми ім’я в подвійні лапки. Діалог створює елементи у поточному каталозі, оновлює панель і ставить курсор на останній створений елемент. При помилці в середині списку вже створені елементи зберігаються. - Після F5 або F6 успішно оброблені елементи коротко підсвічуються в панелі, що показує папку призначення. Підсвітка тексту відрізняється від курсора й не переносить фокус. -- У широкому режимі ширина під вирівняні розширення залежить від найдовшого розширення в поточній панелі. За вузької панелі залишай місце для імені та колонки Size. - Розділювач Size проходить по одній вертикалі в заголовку та списку, а праві краї підпису й значень вирівняні. +- **Left/Right → Sort by** та Ctrl+F3, Ctrl+F4, Ctrl+F5 і Ctrl+F6 сортують + відповідну панель за іменем, розширенням, розміром і часом зміни. + Повторний вибір того самого стовпця змінює напрямок. Клік по заголовку + Wide виконує ту саму команду. Стрілка показує поточний напрямок. + Ctrl+F7 перемикає пріоритет папок. За вимкненого пріоритету папки й файли + сортуються разом. Рядок `..` лишається першим. Сортування, напрямок і + пріоритет папок зберігаються окремо для кожної панелі. +- Ctrl+F8 відкриває фільтр імен файлів без урахування регістру. Маска + підтримує `*` і `?` так само, як Find files. Папки залишаються доступними + для навігації. Порожнє поле або `*` вимикає фільтр. Позначки повертаються + для прихованих фільтром елементів, які ще є в поточній папці. + Ctrl+F9 перемикає показ прихованих та системних елементів окремо для + кожної панелі. Типово їх видно. Маска діє до закриття вікна. +- Wide показує Name, Ext, Size і Modified. Modified відображає місцеву + дату, а сортування враховує повний час зміни. За вузької панелі лишаються + Name та Size. Ext враховує параметри вирівнювання розширень. + Межі стовпців збігаються в заголовку та списку. - Бірюзовий курсор поточного рядка видно в активній панелі. Кожна панель зберігає свою позицію курсора. Коли панелі видимі, F5 і F6 з командного рядка діють на активну панель. - Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший. diff --git a/src/files_find.inl b/src/files_find.inl index 2aa1506..d561864 100644 --- a/src/files_find.inl +++ b/src/files_find.inl @@ -1,20 +1,37 @@ constexpr int findMask=480, findHidden=481, findFooter=482, findLabel=483; -INT_PTR CALLBACK findFilesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +struct FileMaskPrompt +{ + Panel::FindOptions options; + bool filter{}; +}; + +INT_PTR CALLBACK fileMaskDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) { if(message==WM_DRAWITEM) { paintDialogButton(*reinterpret_cast(lp),RGB(192,192,192),RGB(0,0,0),true); return TRUE; } - if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" Find files ",false,{findFooter})) + const auto *prompt=reinterpret_cast(message==WM_INITDIALOG?lp:GetWindowLongPtrW(dialog,DWLP_USER)); + const bool filter=prompt && prompt->filter; + const auto title=filter?L" Panel filter ":L" Find files "; + if(const auto painted=paintCopyDialog(dialog,message,wp,lp,title,false,{findFooter})) return painted; if(message==WM_INITDIALOG) { - const auto &options=*reinterpret_cast(lp); + const auto &options=prompt->options; SetWindowLongPtrW(dialog,DWLP_USER,lp); + if(filter) + { + SetWindowTextW(dialog,L"Panel filter"); + SetDlgItemTextW(dialog,findLabel,L"File &name or mask (blank clears)"); + SetDlgItemTextW(dialog,findHidden,L"Show &hidden and system files"); + SetDlgItemTextW(dialog,IDOK,L"&Apply"); + } prepareTextDialog(dialog); layoutDialogContent(dialog,findLabel); + fitFarEditToLine(GetDlgItem(dialog,findMask)); for(const auto id:{IDOK,IDCANCEL}) { const auto button=GetDlgItem(dialog,id); @@ -32,12 +49,12 @@ INT_PTR CALLBACK findFilesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } if(message==WM_COMMAND && LOWORD(wp)==IDOK) { - auto &options=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + auto &options=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER))->options; wchar_t mask[256]{}; GetDlgItemTextW(dialog,findMask,mask,static_cast(std::size(mask))); if(std::wstring_view(mask).find_first_of(L"/\\:")!=std::wstring_view::npos) { - showFilesNotice(dialog,L"Enter a file name or mask without a path.",L"Find files"); + showFilesNotice(dialog,L"Enter a file name or mask without a path.",filter?L"Panel filter":L"Find files"); SetFocus(GetDlgItem(dialog,findMask)); return TRUE; } @@ -74,8 +91,22 @@ void findLocalFiles(HWND owner,Panel &panel) setStatus(L"Wait for the current scan to finish."); return; } - auto options=panel.findOrigin?panel.findOrigin->options:Panel::FindOptions{}; + FileMaskPrompt prompt{panel.findOrigin?panel.findOrigin->options:Panel::FindOptions{}}; if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner, - findFilesDialog,reinterpret_cast(&options))!=IDOK) return; - startFileSearch(panel,std::move(options)); + fileMaskDialog,reinterpret_cast(&prompt))!=IDOK) return; + startFileSearch(panel,std::move(prompt.options)); +} + +void editPanelFilter(HWND owner,Panel &panel) +{ + if(!panelViewAvailable(panel)) return; + FileMaskPrompt prompt{{panel.view.mask,panel.view.showHidden},true}; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(116),owner, + fileMaskDialog,reinterpret_cast(&prompt))!=IDOK) return; + auto &options=prompt.options; + if(options.mask==L"*") options.mask.clear(); + if(panel.view.mask==options.mask && panel.view.showHidden==options.includeHidden) return; + panel.view.mask=std::move(options.mask); + panel.view.showHidden=options.includeHidden; + updatePanelView(panel); } diff --git a/src/files_find_scan.inl b/src/files_find_scan.inl index 6600b5a..246dd9b 100644 --- a/src/files_find_scan.inl +++ b/src/files_find_scan.inl @@ -51,8 +51,7 @@ std::unique_ptr scanFileMatches(const Panel::ScanRequest &req else if(matchesFileMask(path.filename().native(),request.find->mask)) { result->files.push_back(path); - result->metadata.emplace(path,FolderEntryMetadata{entry.attributes,entry.size}); - result->timestamps.emplace(path,entry.modified); + result->metadata.emplace(path,FolderEntryMetadata{entry.attributes,entry.size,entry.modified}); } return true; }); diff --git a/src/files_main.cpp b/src/files_main.cpp index 6a69336..e05353f 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -126,7 +126,7 @@ struct Handle struct FolderEntryMetadata { DWORD attributes; - ULONGLONG size; + ULONGLONG size, modified; }; DWORD enableBackupPrivilege() @@ -174,7 +174,8 @@ DWORD listElevatedFolder(const fs::path &directory, const std::wstring &pipeName if(name!=L"." && name!=L"..") { const FolderEntryMetadata metadata{entry->FileAttributes, - static_cast(entry->EndOfFile.QuadPart)}; + static_cast(entry->EndOfFile.QuadPart), + static_cast(entry->LastWriteTime.QuadPart)}; std::wstring row(sizeof(metadata)/sizeof(wchar_t),L'\0'); memcpy(row.data(),&metadata,sizeof(metadata)); row.append(name); @@ -397,6 +398,21 @@ struct LocalNavigation } }; +enum class PanelSort { name, extension, size, modified }; +struct PanelView +{ + PanelSort sort{PanelSort::name}; + bool descending{}, foldersFirst{true}, showHidden{true}; + std::wstring mask; +}; + +struct DirectoryRow +{ + fs::path path; + uint64_t value{}; + bool folder{}; +}; + struct Panel { HWND path{}, list{}, heading{}; @@ -442,6 +458,8 @@ struct Panel DWORD error{}; }; std::optional findOrigin; + PanelView view; + std::set filteredMarks; struct ScanRequest { fs::path directory, selection, fallback; @@ -458,18 +476,18 @@ struct Panel DirectoryWatch watch; std::vector folders, files; std::map metadata; - std::map timestamps; DWORD error{}; bool opened{}; std::wstring failure; fs::path ftpInitialDirectory; + std::vector ordered; }; std::optional scanRequest; std::future> scan; std::stop_source scanStop; std::shared_ptr scanEntriesRead; bool scanSuperseded{}; - std::map timestamps; + std::map metadata; std::vector rows; std::vector sizes; std::vector dimmed; @@ -497,7 +515,7 @@ std::wstring panelLocation(const Panel &panel) bool hasPanelSizeColumn(const Panel &panel) { - return panel.wide && !panel.findOrigin; + return panel.wide && !panel.findOrigin && !ftpProfileList(panel); } std::wstring panelCaption(const Panel &panel) @@ -712,6 +730,24 @@ fs::path savedPanelPath(const wchar_t *key) } constexpr const wchar_t *panelModeKeys[]{L"LeftWide",L"RightWide"}; +constexpr const wchar_t *panelViewKeys[]{L"LeftViewOrder",L"RightViewOrder"}; + +void loadPanelView(int index) +{ + const auto settings=preference(panelViewKeys[index],0); + auto &view=panels[index].view; + view.sort=static_cast(settings&3); + view.descending=(settings&4)!=0; + view.foldersFirst=(settings&8)==0; + view.showHidden=(settings&16)==0; +} + +void savePanelView(int index) +{ + const auto &view=panels[index].view; + savePreference(panelViewKeys[index],static_cast(view.sort) | + (view.descending?4:0) | (view.foldersFirst?0:8) | (view.showHidden?0:16)); +} void setMode(int index, bool wide) { @@ -727,9 +763,41 @@ LOGFONTW displayFont{}; int fontPoints=110; int textHeight=20, cellWidth=9; -LONG panelSizeColumn(const RECT &bounds) +constexpr size_t nameColumn=0, extensionColumn=1, sizeColumn=2, dateColumn=3; + +std::array panelColumns(const Panel &panel,RECT bounds) { - return std::max(bounds.left,bounds.right-(sizeWidth+2)*static_cast(cellWidth)); + auto columns=std::array{bounds,bounds,bounds,bounds}; + const auto nameMinimum=10L*cellWidth; + const auto sizeWidthPx=(sizeWidth+2L)*cellWidth; + const auto dateWidth=12L*cellWidth; + const auto extensionLength=std::max(alignExtensions?panel.fileExtensionLength:0, + alignFolders?panel.folderExtensionLength:0); + const auto extensionWidth=(std::clamp(static_cast(extensionLength),4L,12L)+2)*cellWidth; + const LONG available=bounds.right-bounds.left; + const bool showDate=available>=nameMinimum+sizeWidthPx+dateWidth; + columns[dateColumn].left=showDate?bounds.right-dateWidth:bounds.right; + columns[sizeColumn].right=columns[dateColumn].left; + columns[sizeColumn].left=std::max(bounds.left,columns[sizeColumn].right-sizeWidthPx); + columns[extensionColumn].right=columns[sizeColumn].left; + const bool showExtension=(alignExtensions || alignFolders) && + columns[sizeColumn].left-bounds.left>=nameMinimum+extensionWidth; + columns[extensionColumn].left=columns[sizeColumn].left-(showExtension?extensionWidth:0); + columns[nameColumn].right=columns[extensionColumn].left; + return columns; +} + +void paintPanelColumnLines(HDC dc,const std::array &columns) +{ + SetDCBrushColor(dc,colors[Frame]); + const auto brush=static_cast(GetStockObject(DC_BRUSH)); + for(size_t i=1;i=column.right || column.left<=columns[nameColumn].left) continue; + const RECT line{column.left,column.top,column.left+1,column.bottom}; + FillRect(dc,&line,brush); + } } constexpr UINT refreshProgressLayout=WM_APP+1; @@ -1177,6 +1245,7 @@ void swapPanels(HWND window) SetWindowLongPtrW(panel.path,GWLP_ID,142+i); SetWindowLongPtrW(panel.selectionSummary,GWLP_ID,154+i); savePreference(panelModeKeys[i],panel.wide); + savePanelView(i); } notifyFilesPreferences(window); layout(window); @@ -2156,6 +2225,15 @@ void updateSelectionSummary(const Panel &panel) if(hadSummary!=hasSelectionSummary()) layout(GetParent(panel.list)); } +std::optional localFileTime(uint64_t ticks) +{ + if(!ticks) return {}; + const FILETIME stamp{static_cast(ticks),static_cast(ticks>>32)}; + SYSTEMTIME utc{},local{}; + if(FileTimeToSystemTime(&stamp,&utc) && SystemTimeToTzSpecificLocalTime(nullptr,&utc,&local)) return local; + return {}; +} + void showFileDetails(const Panel &panel) { refreshQuickView(panel); @@ -2176,27 +2254,25 @@ void showFileDetails(const Panel &panel) auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0); if(!panel.wide || !showDetails || row<0 || static_cast(row)>=panel.rows.size()) { - setStatus(L""); + setStatus(panel.view.mask.empty()?L"":L"Filter: "+panel.view.mask); return; } const auto &path=panel.rows[row]; - WIN32_FILE_ATTRIBUTE_DATA data{}; - SYSTEMTIME modified{}; + uint64_t ticks{}; + if(const auto found=panel.metadata.find(path); found!=panel.metadata.end()) ticks=found->second.modified; + if(!ticks && !panel.peer && !panel.ftp) + { + WIN32_FILE_ATTRIBUTE_DATA data{}; + if(GetFileAttributesExW(path.c_str(),GetFileExInfoStandard,&data)) + { + const auto &stamp=data.ftLastWriteTime; + ticks=(uint64_t(stamp.dwHighDateTime)<<32)|stamp.dwLowDateTime; + } + } wchar_t date[64]{}; - bool haveTime=false; - if(const auto found=panel.timestamps.find(path); found!=panel.timestamps.end()) - { - data.ftLastWriteTime={static_cast(found->second),static_cast(found->second>>32)}; - haveTime=true; - } - else if(!panel.peer && !panel.ftp) haveTime=GetFileAttributesExW(path.c_str(),GetFileExInfoStandard,&data)!=FALSE; - if(haveTime && FileTimeToSystemTime(&data.ftLastWriteTime,&modified)) - { - SYSTEMTIME local{}; - if(SystemTimeToTzSpecificLocalTime(nullptr,&modified,&local)) - swprintf_s(date,L" %04u-%02u-%02u %02u:%02u",unsigned(local.wYear), - unsigned(local.wMonth),unsigned(local.wDay),unsigned(local.wHour),unsigned(local.wMinute)); - } + if(const auto time=localFileTime(ticks)) + swprintf_s(date,L" %04u-%02u-%02u %02u:%02u",unsigned(time->wYear), + unsigned(time->wMonth),unsigned(time->wDay),unsigned(time->wHour),unsigned(time->wMinute)); std::wstring details; if(statusFields&1) details=path.filename().wstring(); if(statusFields&2) @@ -2211,17 +2287,23 @@ void showFileDetails(const Panel &panel) std::wstring timestamp=date; if((statusFields&4) && timestamp.size()>=12) details+=timestamp.substr(0,12); if((statusFields&8) && timestamp.size()>=18) details+=timestamp.substr(12); + if(!panel.view.mask.empty()) + { + if(!details.empty()) details+=L" "; + details+=L"Filter: "+panel.view.mask; + } setStatus(details); } #include "files_find_scan.inl" +#include "files_panel_order.inl" std::unique_ptr scanDirectory(const Panel::ScanRequest &request, std::atomic_size_t &entriesRead,std::stop_token stop) { if(request.find) return scanFileMatches(request,entriesRead,stop); auto result=std::make_unique(); - auto &[watch,folders,files,metadata,timestamps,error,opened,failure,ftpInitialDirectory]=*result; + auto &[watch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered]=*result; const auto &directory=request.directory; const auto &peer=request.peer; if(stop.stop_requested()) @@ -2239,9 +2321,8 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque if(directory.empty()) ftpInitialDirectory=ftp.initialDirectory(); error=listFtpDirectory(ftp,directory.empty()?ftpInitialDirectory:directory,[&](const fs::path &path,const FileInfo &info) { - if(!metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size}).second) return true; + if(!metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size,info.modified}).second) return true; (info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path); - if(info.modified) timestamps.emplace(path,info.modified); entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed); return !stop.stop_requested(); }); @@ -2258,8 +2339,6 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque } } opened=failure.empty() && (error!=ERROR_CANCELLED || !metadata.empty()); - std::sort(folders.begin(),folders.end()); - std::sort(files.begin(),files.end()); return result; } if(request.elevated) @@ -2269,8 +2348,6 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque if(opened) { if(error==ERROR_SUCCESS) watch.start(directory); - std::sort(folders.begin(),folders.end()); - std::sort(files.begin(),files.end()); } else if(error!=ERROR_CANCELLED) failure=error==ERROR_ACCESS_DENIED?L"Windows denied access after elevation: "+directory.wstring(): L"Could not read folder as administrator ("+std::to_wstring(error)+L"): "+directory.wstring(); @@ -2295,8 +2372,7 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque { if(stop.stop_requested()) return false; (info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path); - metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size}); - timestamps.emplace(path,info.modified); + metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size,info.modified}); entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed); return true; }); @@ -2326,15 +2402,14 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque const auto path=directory/name; const auto size=(static_cast(data.nFileSizeHigh)<<32)|data.nFileSizeLow; (data.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path); - metadata.emplace(path,FolderEntryMetadata{data.dwFileAttributes,size}); - timestamps.emplace(path,(uint64_t(data.ftLastWriteTime.dwHighDateTime)<<32)|data.ftLastWriteTime.dwLowDateTime); + const auto &stamp=data.ftLastWriteTime; + metadata.emplace(path,FolderEntryMetadata{data.dwFileAttributes,size, + (uint64_t(stamp.dwHighDateTime)<<32)|stamp.dwLowDateTime}); entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed); } while(FindNextFileW(search,&data)); if(error!=ERROR_CANCELLED) error=GetLastError(); } else if(!peer && stop.stop_requested()) error=ERROR_CANCELLED; - std::sort(folders.begin(), folders.end()); - std::sort(files.begin(), files.end()); return result; } @@ -2352,7 +2427,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul auto &peer=request.peer; const auto previousDirectory=samePanelSource(panel,peer,request.ftp)?panel.directory:fs::path{}; const bool sameDirectory=previousDirectory==directory; - auto &[nextWatch,folders,files,metadata,timestamps,error,opened,failure,ftpInitialDirectory]=scan; + auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered]=scan; const bool partial=error==ERROR_CANCELLED; if(!failure.empty()) { @@ -2405,6 +2480,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul LRESULT previousRow=0, previousTop=0; if(sameDirectory) { + if(!panel.findOrigin) markedPaths=std::move(panel.filteredMarks); previousRow=SendMessageW(panel.list,LB_GETCURSEL,0,0); previousTop=SendMessageW(panel.list,LB_GETTOPINDEX,0,0); if(previousRow>=0 && static_cast(previousRow)1) longest=std::max(longest,extension.size()-1); } - panel.marked.push_back(label!=L".." && markedPaths.contains(path)); - const auto entry=label==L".." || profiles ? FolderEntryMetadata{} : metadata.at(path); + const bool marked=label!=L".." && markedPaths.contains(path); + panel.marked.push_back(marked); + if(marked) panel.filteredMarks.erase(path); + const auto entry=label==L".." || profiles ? FolderEntryMetadata{} : panel.metadata.at(path); panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0); panel.sizes.push_back(profiles?L"":folder ? (label==L".." ? L"Up" : L"Folder") : std::to_wstring(entry.size)); @@ -2501,8 +2585,14 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul else { if(hasParent) add(parent,L"..",true); - for(const auto &folder:folders) add(folder,L"["+folder.filename().wstring()+L"]",true); - for(const auto &file:files) add(file,finding?file.lexically_relative(directory).native():file.filename().native(),false); + if(finding) + for(const auto &file:files) add(file,file.lexically_relative(directory).native(),false); + else + for(const auto &entry:ordered) + { + const auto name=entry.path.filename().native(); + add(entry.path,entry.folder?L"["+name+L"]":name,entry.folder); + } } const auto label=panelCaption(panel); SetWindowTextW(panel.path,label.c_str()); @@ -2551,9 +2641,11 @@ void startDirectoryScan(Panel &panel) panel.scanEntriesRead=std::make_shared(0); const auto owner=GetParent(panel.list); std::packaged_task()> task( - [request=*panel.scanRequest,entries=panel.scanEntriesRead,stop=panel.scanStop.get_token()] + [request=*panel.scanRequest,view=panel.view,entries=panel.scanEntriesRead,stop=panel.scanStop.get_token()] { - return scanDirectory(request,*entries,stop); + auto result=scanDirectory(request,*entries,stop); + if(result->opened && !request.find) orderDirectoryRows(*result,view); + return result; }); auto future=task.get_future(); std::thread([task=std::move(task),owner]() mutable @@ -2623,6 +2715,81 @@ void open(Panel &panel,const fs::path &directory,bool offerElevation=false) openOn(panel,directory,offerElevation,panel.peer,{},{},panel.ftp); } +bool panelViewAvailable(const Panel &panel) +{ + return !panel.findOrigin && !ftpProfileList(panel) && !panel.directory.empty() && + (!panel.scanRequest || !panel.scanRequest->find); +} + +void updatePanelView(Panel &panel) +{ + savePanelView(static_cast(&panel-panels)); + InvalidateRect(panel.heading,nullptr,FALSE); + if(panel.scanRequest) + { + panel.scanSuperseded=true; + panel.scanStop.request_stop(); + } + else open(panel,panel.directory); +} + +void sortPanel(Panel &panel,PanelSort sort) +{ + if(!panelViewAvailable(panel)) return; + if(panel.view.sort==sort) panel.view.descending=!panel.view.descending; + else + { + panel.view.sort=sort; + panel.view.descending=false; + } + updatePanelView(panel); +} + +void togglePanelView(Panel &panel,bool foldersFirst) +{ + if(!panelViewAvailable(panel)) return; + auto &value=foldersFirst?panel.view.foldersFirst:panel.view.showHidden; + value=!value; + updatePanelView(panel); +} + +void editPanelFilter(HWND owner,Panel &panel); + +void panelViewAction(HWND owner,Panel &panel,int action) +{ + if(action>=0 && action<4) sortPanel(panel,static_cast(action)); + else if(action==5) editPanelFilter(owner,panel); + else if(action==4 || action==6) togglePanelView(panel,action==4); +} + +LRESULT CALLBACK panelHeadingInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + const auto index=GetDlgCtrlID(window)-140; + auto &panel=panels[index]; + if(message==WM_LBUTTONUP && panelViewAvailable(panel)) + { + RECT bounds{}; + GetClientRect(window,&bounds); + const auto columns=panelColumns(panel,bounds); + const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; + for(size_t i=0;i(i)); + break; + } + return 0; + } + if(message==WM_SETCURSOR && panelViewAvailable(panel)) + { + SetCursor(LoadCursorW(nullptr,IDC_HAND)); + return TRUE; + } + return DefSubclassProc(window,message,wp,lp); +} + void showFtpProfiles(Panel &panel,fs::path selection={}) { openOn(panel,ftpRoot,false,{},std::move(selection),{},FtpProfile{}); @@ -2947,8 +3114,9 @@ void selectDrive() auto owner=GetParent(picker); if(menuIndex==0 || menuIndex==4) { - int index=menuIndex==4; - if(row==2) chooseDrive(index); + const int index=menuIndex==4; + if(row>2) panelViewAction(owner,panels[index],static_cast(row)-3); + else if(row==2) chooseDrive(index); else setMode(index,row==1); } else if(menuIndex==2 && row==3) showFolderShortcuts(panels[active],-1); @@ -5106,13 +5274,11 @@ struct WarningPrompt std::wstring conflictFileDetails(const FileInfo &file) { - const FILETIME stamp{static_cast(file.modified),static_cast(file.modified>>32)}; - SYSTEMTIME utc{},local{}; wchar_t date[32]=L"—"; - if(file.modified && FileTimeToSystemTime(&stamp,&utc) && SystemTimeToTzSpecificLocalTime(nullptr,&utc,&local)) - swprintf_s(date,L"%04u-%02u-%02u %02u:%02u:%02u",unsigned(local.wYear), - unsigned(local.wMonth),unsigned(local.wDay),unsigned(local.wHour), - unsigned(local.wMinute),unsigned(local.wSecond)); + if(const auto time=localFileTime(file.modified)) + swprintf_s(date,L"%04u-%02u-%02u %02u:%02u:%02u",unsigned(time->wYear), + unsigned(time->wMonth),unsigned(time->wDay),unsigned(time->wHour), + unsigned(time->wMinute),unsigned(time->wSecond)); auto bytes=std::to_wstring(file.size); for(auto position=bytes.size();position>3;) { @@ -5446,7 +5612,7 @@ void pruneSearchResults(Panel &panel,const std::set &removed) --row; const auto &path=panel.rows[row]; if(!removed.contains(path)) continue; - panel.timestamps.erase(path); + panel.metadata.erase(path); SendMessageW(panel.list,LB_DELETESTRING,row,0); panel.rows.erase(panel.rows.begin()+row); panel.sizes.erase(panel.sizes.begin()+row); @@ -6690,10 +6856,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT { RECT line{}; GetClientRect(window,&line); - line.left=panelSizeColumn(line); - line.right=line.left+1; - SetDCBrushColor(dc,colors[Frame]); - FillRect(dc,&line,static_cast(GetStockObject(DC_BRUSH))); + paintPanelColumnLines(dc,panelColumns(panels[index],line)); ReleaseDC(window,dc); } } @@ -6745,10 +6908,24 @@ void openMenu(HWND window, int index) std::vector rows; if(index==0 || index==4) { - const bool wide=panels[index==4].wide; + const auto &panel=panels[index==4]; + const bool wide=panel.wide; rows={wide?L" Brief\tCtrl+F1":L"✓ Brief\tCtrl+F1", wide?L"✓ Wide\tCtrl+F2":L" Wide\tCtrl+F2", index==0?L" Change drive\tAlt+F1":L" Change drive\tAlt+F2"}; + if(panelViewAvailable(panel)) + { + constexpr const wchar_t *sortLabels[]{L"Sort by name\tCtrl+F3",L"Sort by extension\tCtrl+F4", + L"Sort by size\tCtrl+F5",L"Sort by modified\tCtrl+F6"}; + for(size_t i=0;i(panel.view.sort)!=i?L" ":panel.view.descending?L"↓ ":L"↑ "; + rows.push_back(std::wstring(mark)+sortLabels[i]); + } + rows.push_back(panel.view.foldersFirst?L"✓ Folders first\tCtrl+F7":L" Folders first\tCtrl+F7"); + rows.push_back(panel.view.mask.empty()?L" Filter by mask…\tCtrl+F8":L"✓ Filter by mask…\tCtrl+F8"); + rows.push_back(panel.view.showHidden?L"✓ Show hidden and system\tCtrl+F9":L" Show hidden and system\tCtrl+F9"); + } } else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10"}; else if(index==2) @@ -7114,12 +7291,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) for (int i = 0; i < 2; ++i) { auto &panel = panels[i]; + loadPanelView(i); panel.path = CreateWindowW(L"STATIC", L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | SS_OWNERDRAW | SS_NOTIFY, 0, 0, 0, 0, window, reinterpret_cast(142 + static_cast(i)), instance, nullptr); panel.list = CreateWindowExW(0, L"LISTBOX", L"", WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | LBS_OWNERDRAWFIXED | LBS_HASSTRINGS, 0, 0, 0, 0, window, reinterpret_cast(102 + static_cast(i)), instance, nullptr); - panel.heading=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW, + panel.heading=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_OWNERDRAW|SS_NOTIFY, 0,0,0,0,window,reinterpret_cast(140+static_cast(i)),instance,nullptr); panel.selectionSummary=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPSIBLINGS|SS_ENDELLIPSIS, 0,0,0,0,window,reinterpret_cast(154+static_cast(i)),instance,nullptr); @@ -7140,6 +7318,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) target->Release(); } SetWindowSubclass(panel.path,pathBarInput,1,0); + SetWindowSubclass(panel.heading,panelHeadingInput,1,0); installScrollBar(panel.list,window,firstPanelScrollBar+i); } SetFocus(panels[0].list); @@ -7225,7 +7404,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) RECT box{}; GetWindowRect(panel.list,&box); MapWindowPoints(nullptr,window,reinterpret_cast(&box),2); - const LONG columnX=panelSizeColumn(box); + const LONG columnX=panelColumns(panel,box)[sizeColumn].left; box.right+=scrollBarWidth(panel.list); InflateRect(&box,2,2); box.left-=2; @@ -7308,7 +7487,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) RECT list{}; GetWindowRect(panels[index].list,&list); MapWindowPoints(nullptr,item.hwndItem,reinterpret_cast(&list),2); - const auto x=panelSizeColumn(list); + const auto x=panelColumns(panel,list)[sizeColumn].left; RECT column{x,middle,x+1,bounds.bottom}; FillRect(item.hDC,&column,lineBrush); } @@ -7338,19 +7517,23 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } if(item.CtlID==140 || item.CtlID==141) { - if(panels[item.CtlID-140].findOrigin) + const auto &panel=panels[item.CtlID-140]; + if(panel.findOrigin || ftpProfileList(panel)) { - paintText(item.hDC,item.rcItem,L"Relative path",RGB(255,255,0),colors[PanelBlue]); + paintText(item.hDC,item.rcItem,panel.findOrigin?L"Relative path":L"Name",RGB(255,255,0),colors[PanelBlue]); return TRUE; } - auto name=item.rcItem, size=item.rcItem; - size.left=panelSizeColumn(size); - name.right=size.left; - paintText(item.hDC,name,L"Name",RGB(255,255,0),colors[PanelBlue]); - paintText(item.hDC,size,L"Size",RGB(255,255,0),colors[PanelBlue],true); - RECT line{size.left,size.top,size.left+1,size.bottom}; - SetDCBrushColor(item.hDC,colors[Frame]); - FillRect(item.hDC,&line,static_cast(GetStockObject(DC_BRUSH))); + const auto columns=panelColumns(panel,item.rcItem); + constexpr const wchar_t *headings[]{L"Name",L"Ext",L"Size",L"Modified"}; + for(size_t i=0;i=columns[i].right) continue; + std::wstring label=headings[i]; + if(i==nameColumn && !panel.view.mask.empty()) label+=L" *"; + if(static_cast(panel.view.sort)==i) label+=panel.view.descending?L" ↓":L" ↑"; + paintText(item.hDC,columns[i],label.c_str(),RGB(255,255,0),colors[PanelBlue],i==sizeColumn); + } + paintPanelColumnLines(item.hDC,columns); return TRUE; } if(item.hwndItem==pickerFrame || item.hwndItem==completionFrame) @@ -7582,28 +7765,33 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) const auto &panel=panels[item.CtlID-102]; if(hasPanelSizeColumn(panel) && !ftpProfileList(panel) && item.itemID1) - { - auto end=name; - const auto width=static_cast(extensionLength)*cellWidth+5; - end.left=std::max(end.left+static_cast(cellWidth),end.right-width); - end.left=std::min(end.left,end.right); - name.right=end.left; - paintText(item.hDC,end,extension.c_str()+1,foreground,rowBackground,true,rowFont); - text=panel.rows[item.itemID].stem().wstring(); - } + const auto suffix=path.extension().native(); + const bool showSuffix=suffix.size()>1 && panel.sizes[item.itemID]!=L"Up"; + paintText(item.hDC,extension,showSuffix?suffix.c_str()+1:L"",foreground,rowBackground,true,rowFont); + if(showSuffix) text=path.stem().native(); } + auto name=columns[nameColumn]; + if(!separateExtension) name.right=extension.right; paintText(item.hDC,name,text.c_str(),foreground,rowBackground,false,rowFont); + if(date.leftsecond.modified)) + swprintf_s(modified,L"%04u-%02u-%02u",unsigned(time->wYear),unsigned(time->wMonth),unsigned(time->wDay)); + } + paintText(item.hDC,date,modified,foreground,rowBackground,true,rowFont); + } const auto &amount=panel.sizes[item.itemID]; auto visible=amount; const auto measured=folder?panel.folderSizes.find(panel.rows[item.itemID]):panel.folderSizes.end(); @@ -7616,10 +7804,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } else if(amount!=L"Folder" && amount!=L"Up") visible=formatSize(std::stoull(amount),static_cast(sizeWidth)); - paintText(item.hDC,size,visible.c_str(),foreground,rowBackground,true); - RECT line{size.left,size.top,size.left+1,size.bottom}; - SetDCBrushColor(item.hDC,colors[Frame]); - FillRect(item.hDC,&line,static_cast(GetStockObject(DC_BRUSH))); + paintText(item.hDC,columns[sizeColumn],visible.c_str(),foreground,rowBackground,true); + paintPanelColumnLines(item.hDC,columns); } } if (item.CtlType==ODT_LISTBOX && !popupRow) @@ -7940,11 +8126,12 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) !(GetKeyState(VK_SHIFT)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) && !(GetKeyState(VK_RWIN)&0x8000)) { - if(!(message.lParam & (1LL<<30)) && (message.wParam==VK_F1 || message.wParam==VK_F2)) + if(!(message.lParam & (1LL<<30)) && message.wParam<=VK_F9) { hidePicker(); showMenu(false); - setMode(active,message.wParam==VK_F2); + if(message.wParam<=VK_F2) setMode(active,message.wParam==VK_F2); + else panelViewAction(window,panels[active],static_cast(message.wParam-VK_F3)); } continue; } diff --git a/src/files_panel_order.inl b/src/files_panel_order.inl new file mode 100644 index 0000000..fe0200b --- /dev/null +++ b/src/files_panel_order.inl @@ -0,0 +1,51 @@ +std::wstring_view directoryRowName(const fs::path &path) +{ + const auto name=std::wstring_view(path.native()); + const auto slash=name.find_last_of(L"/\\"); + return slash==name.npos?name:name.substr(slash+1); +} + +std::wstring_view directoryRowExtension(std::wstring_view name) +{ + const auto dot=name.find_last_of(L'.'); + return dot==name.npos || dot==0?std::wstring_view{}:name.substr(dot+1); +} + +int compareDirectoryText(std::wstring_view left,std::wstring_view right) +{ + if(left.empty() || right.empty()) return static_cast(!left.empty())-static_cast(!right.empty()); + return CompareStringOrdinal(left.data(),static_cast(left.size()),right.data(),static_cast(right.size()),TRUE) + - CSTR_EQUAL; +} + +void orderDirectoryRows(Panel::ScanResult &result,const PanelView &view) +{ + auto &rows=result.ordered; + if(view.showHidden && view.mask.empty()) rows.reserve(result.folders.size()+result.files.size()); + const auto append=[&](std::vector &paths,bool folder) + { + for(auto &path:paths) + { + const auto &metadata=result.metadata.at(path); + const uint64_t value=view.sort==PanelSort::modified?metadata.modified: + view.sort==PanelSort::size?metadata.size:0; + const bool visible=(view.showHidden || !(metadata.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))) && + (folder || view.mask.empty() || matchesFileMask(directoryRowName(path),view.mask)); + if(visible) rows.push_back({std::move(path),value,folder}); + } + }; + append(result.folders,true); + append(result.files,false); + std::sort(rows.begin(),rows.end(),[&](const DirectoryRow &left,const DirectoryRow &right) + { + if(view.foldersFirst && left.folder!=right.folder) return left.folder; + const auto leftName=directoryRowName(left.path), rightName=directoryRowName(right.path); + int order=0; + if(view.sort==PanelSort::extension) + order=compareDirectoryText(directoryRowExtension(leftName),directoryRowExtension(rightName)); + else if(left.value!=right.value) order=left.value0:order<0; + }); +} From efe79375074fe35b575d55480d9a2beabea6e27c Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 14:19:47 +0200 Subject: [PATCH 10/61] Add a local Space Analyzer to Files Refs #94 --- FILES-UI.md | 9 + resources/files.rc | 16 ++ src/files_main.cpp | 65 ++++-- src/files_panel_order.inl | 2 +- src/files_space_analyzer.inl | 390 +++++++++++++++++++++++++++++++++++ 5 files changed, 468 insertions(+), 14 deletions(-) create mode 100644 src/files_space_analyzer.inl diff --git a/FILES-UI.md b/FILES-UI.md index c260d7a..f693363 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -455,6 +455,15 @@ Warning і початковий фокус на No. переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук з тією самою маскою й видимістю прихованих файлів. +- **Commands → Space Analyzer** аналізує поточну локальну папку у фоні + тим самим обходом, що й підрахунок розмірів F3. У дереві показано розмір + і відсоток від батьківської папки. Посилання на каталоги не обходяться. + Stop лишає часткові результати, а Rescan повторює аналіз із початку. +- View відкриває вибраний файл у спільному переглядачі Files. Show in + other panel відкриває вибрану папку або ставить курсор на файл у сусідній + панелі. Команди роботи з файлами доступні там. Якщо фільтр приховує + вибраний файл, панель показує його до зміни фільтра або переходу в іншу папку. + - Обидві панелі автоматично підхоплюють створення, зміну й видалення файлів у відкритих локальних папках. Фокус залишається там, де був, а курсор лишається на поточному елементі, якщо той ще існує. diff --git a/resources/files.rc b/resources/files.rc index 3d2630a..ceebeb9 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -432,3 +432,19 @@ BEGIN CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17 CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17 END + +118 DIALOGEX 0, 0, 385, 209 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "Space Analyzer" +FONT 10, "Consolas" +BEGIN + LTEXT "", 488, 16, 15, 353, 13, SS_PATHELLIPSIS + CONTROL "", 489, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 16, 32, 353, 131 + LTEXT "", 490, 16, 167, 353, 14, SS_ENDELLIPSIS + LTEXT "", 491, 12, 184, 1, 1, NOT WS_VISIBLE + CONTROL "S&top", 492, "Button", BS_OWNERDRAW | WS_TABSTOP, 22, 189, 46, 16 + CONTROL "&Rescan", 493, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 189, 50, 16 + CONTROL "&View", 494, "Button", BS_OWNERDRAW | WS_TABSTOP, 126, 189, 46, 16 + CONTROL "&Show in other panel", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 176, 189, 102, 16 + CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 282, 189, 50, 16 +END diff --git a/src/files_main.cpp b/src/files_main.cpp index e05353f..b1da0e3 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -287,6 +287,12 @@ struct FolderSize { uint64_t bytes{}; bool partial{}; + + void add(uint64_t amount) + { + if(amount>UINT64_MAX-bytes) partial=true; + else bytes+=amount; + } }; using FolderSizes=std::map; @@ -305,8 +311,20 @@ struct FolderSizeJob bool finished{}; }; +using FolderMeasurementObserver=std::function; + +bool listMeasuredDirectory(FilesConnection &host,const fs::path &directory,const FileVisitor &visit, + std::stop_token stop) +{ + const auto info=statFile(host,directory); + return info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY) && + !(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT) && !stop.stop_requested() && + listFiles(host,directory,visit); +} + template -FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDirectory &listDirectory) +FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDirectory &listDirectory, + const FolderMeasurementObserver &observe={}) { FolderSize size; std::vector pending{root}; @@ -314,20 +332,27 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir { const auto directory=std::move(pending.back()); pending.pop_back(); + bool complete=false; try { - if(!listDirectory(directory,[&](const fs::path &path,const FileInfo &entry) + complete=listDirectory(directory,[&](const fs::path &path,const FileInfo &entry) { if(stop.stop_requested()) return false; + if(observe) observe(path,&entry); if(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT) return true; if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY) pending.push_back(path); - else if(entry.size>UINT64_MAX-size.bytes) size.partial=true; - else size.bytes+=entry.size; + else size.add(entry.size); return true; - })) size.partial=true; + }); + } + catch(const std::exception &) {} + if(!complete) + { + size.partial=true; + if(observe) observe(directory,nullptr); } - catch(const std::exception &) {size.partial=true;} } + if(stop.stop_requested()) size.partial=true; return size; } @@ -404,6 +429,7 @@ struct PanelView PanelSort sort{PanelSort::name}; bool descending{}, foldersFirst{true}, showHidden{true}; std::wstring mask; + fs::path revealedFile; }; struct DirectoryRow @@ -670,6 +696,7 @@ struct FilesNoticeOptions }; INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={}); void openMenu(HWND window, int index); +void openSpaceAnalyzer(HWND owner,Panel &panel); void showFileDetails(const Panel &panel); void updateSelectionSummary(const Panel &panel); void editOptions(HWND owner); @@ -2663,6 +2690,8 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti std::optional navigationPosition={}) { if(directory.empty() && !ftp) return; + if(!panel.view.revealedFile.empty() && + (peer || ftp || panel.view.revealedFile.parent_path()!=directory)) panel.view.revealedFile.clear(); if(directory!=panel.directory || !samePanelSource(panel,peer,ftp)) cancelFolderSizes(panel); panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback), @@ -2723,6 +2752,7 @@ bool panelViewAvailable(const Panel &panel) void updatePanelView(Panel &panel) { + panel.view.revealedFile.clear(); savePanelView(static_cast(&panel-panels)); InvalidateRect(panel.heading,nullptr,FALSE); if(panel.scanRequest) @@ -2790,6 +2820,12 @@ LRESULT CALLBACK panelHeadingInput(HWND window,UINT message,WPARAM wp,LPARAM lp, return DefSubclassProc(window,message,wp,lp); } +void revealLocalFile(Panel &panel,const fs::path &path) +{ + panel.view.revealedFile=path; + openOn(panel,path.parent_path(),false,{},path); +} + void showFtpProfiles(Panel &panel,fs::path selection={}) { openOn(panel,ftpRoot,false,{},std::move(selection),{},FtpProfile{}); @@ -2915,10 +2951,7 @@ bool calculateFolderSizes(Panel &panel,LRESULT current) FilesConnection host(peer?&*peer:nullptr); measure([&](const fs::path &directory,const FileVisitor &visit) { - const auto info=statFile(host,directory); - return info && (info->attributes&FILE_ATTRIBUTE_DIRECTORY) && - !(info->attributes&FILE_ATTRIBUTE_REPARSE_POINT) && !stop.stop_requested() && - listFiles(host,directory,visit); + return listMeasuredDirectory(host,directory,visit,stop); }); } } @@ -3126,6 +3159,7 @@ void selectDrive() else if(menuIndex==2 && row==9) findLocalFiles(owner,panels[active]); 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 { const int command=menuIndex==1?113+static_cast(row):110+static_cast(row); @@ -3760,7 +3794,7 @@ void enter(Panel &panel) auto target = panel.rows[row]; if(panel.findOrigin) { - openOn(panel,target.parent_path(),false,{},target); + revealLocalFile(panel,target); return; } if(panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") open(panel,target,true); @@ -6890,6 +6924,7 @@ bool loadFilesPreferences(HWND window) #include "files_find.inl" #include "files_options.inl" +#include "files_space_analyzer.inl" void openMenu(HWND window, int index) { @@ -6934,13 +6969,17 @@ void openMenu(HWND window, int index) L"View externally\tAlt+F3",L"Edit externally\tAlt+F4", L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(), L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q", - L"Copy full path\tCtrl+Shift+C"}; + L"Copy full path\tCtrl+Shift+C",L"Space Analyzer"}; } commandActions.clear(); if(index==2) { commandActions={0,3,11,-1,1,2,4,5,8}; - if(!panels[active].peer && !panels[active].ftp) commandActions.insert(commandActions.begin()+1,9); + if(!panels[active].peer && !panels[active].ftp) + { + commandActions.insert(commandActions.begin()+1,9); + if(!terminalVisible) commandActions.insert(commandActions.begin()+2,12); + } if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10); if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7}); } diff --git a/src/files_panel_order.inl b/src/files_panel_order.inl index fe0200b..4513f4f 100644 --- a/src/files_panel_order.inl +++ b/src/files_panel_order.inl @@ -31,7 +31,7 @@ void orderDirectoryRows(Panel::ScanResult &result,const PanelView &view) view.sort==PanelSort::size?metadata.size:0; const bool visible=(view.showHidden || !(metadata.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))) && (folder || view.mask.empty() || matchesFileMask(directoryRowName(path),view.mask)); - if(visible) rows.push_back({std::move(path),value,folder}); + if(visible || path==view.revealedFile) rows.push_back({std::move(path),value,folder}); } }; append(result.folders,true); diff --git a/src/files_space_analyzer.inl b/src/files_space_analyzer.inl new file mode 100644 index 0000000..73b3e70 --- /dev/null +++ b/src/files_space_analyzer.inl @@ -0,0 +1,390 @@ +constexpr int spacePath=488,spaceTree=489,spaceStatus=490,spaceFooter=491; +constexpr int spaceStop=492,spaceRescan=493,spaceView=494; +constexpr UINT_PTR spaceUpdateTimer=1; +constexpr size_t spaceBatchSize=256; + +struct SpaceEvent +{ + fs::path path; + std::optional item; +}; + +struct SpaceRun +{ + std::stop_source stop; + std::mutex mutex; + std::deque> pending; + FolderSize result; + bool finished{}, stopped{}; +}; + +std::shared_ptr startSpaceRun(const fs::path &root) +{ + auto run=std::make_shared(); + std::thread([run,root] { + std::vector batch; + auto lastUpdate=GetTickCount64(); + const auto publish=[&] { + if(batch.empty()) return; + std::lock_guard lock(run->mutex); + run->pending.push_back(std::move(batch)); + batch.clear(); + lastUpdate=GetTickCount64(); + }; + FolderSize total; + const auto stop=run->stop.get_token(); + try + { + FilesConnection host(nullptr); + total=measureFolder(root,stop,[&](const fs::path &directory,const FileVisitor &visit) { + return listMeasuredDirectory(host,directory,visit,stop); + },[&](const fs::path &path,const FileInfo *info) { + batch.push_back({path,info?std::optional(*info):std::nullopt}); + if(batch.size()>=spaceBatchSize || GetTickCount64()-lastUpdate>=80) publish(); + }); + publish(); + } + catch(const std::exception &) {total.partial=true;} + std::lock_guard lock(run->mutex); + run->result=total; + run->stopped=stop.stop_requested(); + run->finished=true; + }).detach(); + return run; +} + +struct SpaceNode +{ + fs::path path; + FolderSize size; + size_t parent{}; + std::vector children; + HTREEITEM item{}; + bool folder{}, link{}, expanded{}; +}; + +struct SpaceAnalyzer +{ + fs::path root, selected; + bool selectedFolder{}; + std::shared_ptr run; + std::vector nodes; + std::map directories; + size_t files{}; + bool scanning{}; +}; + +void layoutSpaceAnalyzer(HWND dialog) +{ + RECT bounds{}; + GetClientRect(dialog,&bounds); + const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog)); + const auto inset=frame.content(); + const auto width=std::max(1L,bounds.right-2*inset); + const auto place=[&](int id,int top,int height) { + SetWindowPos(GetDlgItem(dialog,id),nullptr,inset,top,width,height,SWP_NOZORDER|SWP_NOACTIVATE); + }; + auto top=dialogListInset(frame,textHeight); + place(spacePath,top,textHeight); + top+=textHeight+dialogRowGap(); + place(spaceTree,top,9*textHeight); + top+=9*textHeight+dialogRowGap(); + place(spaceStatus,top,textHeight); + place(spaceFooter,top+textHeight+dialogRowGap(),1); + layoutDialogButtons(dialog,spaceFooter,{spaceStop,spaceRescan,spaceView,IDOK,IDCANCEL}); +} + +HTREEITEM insertSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index) +{ + auto &node=state.nodes[index]; + TVINSERTSTRUCTW insert{}; + insert.hParent=index?state.nodes[node.parent].item:TVI_ROOT; + insert.hInsertAfter=TVI_LAST; + insert.item.mask=TVIF_TEXT|TVIF_PARAM|TVIF_CHILDREN; + insert.item.pszText=LPSTR_TEXTCALLBACKW; + insert.item.lParam=static_cast(index); + insert.item.cChildren=node.folder && !node.link?I_CHILDRENCALLBACK:0; + node.item=TreeView_InsertItem(tree,&insert); + return node.item; +} + +void expandSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index) +{ + auto &node=state.nodes[index]; + if(node.expanded) return; + node.expanded=true; + for(auto child:node.children) insertSpaceNode(tree,state,child); +} + +void addSpaceEvent(HWND tree,SpaceAnalyzer &state,SpaceEvent event) +{ + if(!event.item) + { + const auto directory=state.directories.find(event.path); + if(directory==state.directories.end()) return; + for(auto i=directory->second;;i=state.nodes[i].parent) + { + state.nodes[i].size.partial=true; + if(!i) break; + } + return; + } + const auto parent=state.directories.find(event.path.parent_path()); + if(parent==state.directories.end()) return; + const auto index=state.nodes.size(); + const bool folder=(event.item->attributes&FILE_ATTRIBUTE_DIRECTORY)!=0; + const bool link=(event.item->attributes&FILE_ATTRIBUTE_REPARSE_POINT)!=0; + const auto bytes=folder || link?0:event.item->size; + if(folder) state.directories.emplace(event.path,index); + else ++state.files; + state.nodes.push_back({.path=std::move(event.path),.size={bytes,false},.parent=parent->second, + .folder=folder,.link=link}); + auto &parentNode=state.nodes[parent->second]; + parentNode.children.push_back(index); + if(parentNode.item && parentNode.expanded) + { + insertSpaceNode(tree,state,index); + if(parentNode.children.size()==1) TreeView_Expand(tree,parentNode.item,TVE_EXPAND); + } + for(auto i=parent->second;;i=state.nodes[i].parent) + { + state.nodes[i].size.add(bytes); + if(!i) break; + } +} + +std::wstring spaceNodeText(const SpaceAnalyzer &state,size_t index) +{ + const auto &node=state.nodes[index]; + const auto &parent=state.nodes[node.parent]; + auto name=node.path.filename().native(); + if(name.empty()) name=node.path.native(); + if(name.size()>196) + { + name.resize(196); + if(name.back()>=0xD800 && name.back()<=0xDBFF) name.pop_back(); + name+=L"…"; + } + if(node.link) return name+L" [link]"; + auto result=name+L" — "+formatSize(node.size.bytes); + if(node.size.partial) result+=L"+"; + if(parent.size.bytes) + { + wchar_t share[48]{}; + swprintf_s(share,L" (%.1f%%)",100.0*static_cast(node.size.bytes)/static_cast(parent.size.bytes)); + result+=share; + } + return result; +} + +std::optional selectedSpaceNode(HWND tree,const SpaceAnalyzer &state) +{ + TVITEMW item{}; + item.mask=TVIF_PARAM; + item.hItem=TreeView_GetSelection(tree); + if(item.hItem && TreeView_GetItem(tree,&item) && static_cast(item.lParam)(item.lParam); + return {}; +} + +void updateSpaceTree(HWND dialog,SpaceAnalyzer &state) +{ + const auto tree=GetDlgItem(dialog,spaceTree); + const auto budget=GetTickCount64()+15; + bool finished=false,stopped=false,changed=false; + do + { + std::vector batch; + { + std::lock_guard lock(state.run->mutex); + if(!state.run->pending.empty()) + { + batch=std::move(state.run->pending.front()); + state.run->pending.pop_front(); + } + else if(state.run->finished) + { + finished=true; + stopped=state.run->stopped; + state.nodes[0].size.partial|=state.run->result.partial; + } + } + if(batch.empty()) break; + if(!changed) SendMessageW(tree,WM_SETREDRAW,FALSE,0); + changed=true; + for(auto &event:batch) addSpaceEvent(tree,state,std::move(event)); + } while(GetTickCount64()stop.stop_requested(); + auto status=finished?(stopped?L"Stopped · partial":state.nodes[0].size.partial?L"Partial results":L"Complete"): + stopping?L"Stopping…":L"Scanning…"; + SetDlgItemTextW(dialog,spaceStatus,(std::wstring(status)+L" · "+std::to_wstring(state.files)+L" files · shares of parent").c_str()); + if(finished) + { + EnableWindow(GetDlgItem(dialog,spaceStop),FALSE); + EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE); + KillTimer(dialog,spaceUpdateTimer); + } +} + +void rescanSpace(HWND dialog,SpaceAnalyzer &state) +{ + const auto tree=GetDlgItem(dialog,spaceTree); + TreeView_DeleteAllItems(tree); + state.nodes.clear(); + state.nodes.push_back({.path=state.root,.folder=true,.expanded=true}); + state.directories.clear(); + state.directories.emplace(state.root,0); + state.files=0; + state.scanning=true; + TreeView_SelectItem(tree,insertSpaceNode(tree,state,0)); + EnableWindow(GetDlgItem(dialog,spaceView),FALSE); + EnableWindow(GetDlgItem(dialog,spaceRescan),FALSE); + try + { + state.run=startSpaceRun(state.root); + EnableWindow(GetDlgItem(dialog,spaceStop),TRUE); + SetTimer(dialog,spaceUpdateTimer,60,nullptr); + updateSpaceTree(dialog,state); + } + catch(const std::exception &) + { + EnableWindow(GetDlgItem(dialog,spaceStop),FALSE); + EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE); + state.scanning=false; + SetDlgItemTextW(dialog,spaceStatus,L"Could not start folder analysis."); + } +} + +INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + auto &state=*reinterpret_cast(lp); + SetWindowLongPtrW(dialog,DWLP_USER,lp); + prepareTextDialog(dialog); + SetDlgItemTextW(dialog,spacePath,state.root.c_str()); + const auto tree=GetDlgItem(dialog,spaceTree); + TreeView_SetBkColor(tree,RGB(255,255,255)); + TreeView_SetTextColor(tree,RGB(0,0,0)); + layoutSpaceAnalyzer(dialog); + const auto inset=dialogFrameMetrics(GetDpiForWindow(dialog)).content(); + FilesModalDialog::fitWidthToOwner(dialog,54*cellWidth+2*inset,layoutSpaceAnalyzer); + SendMessageW(dialog,DM_SETDEFID,IDCANCEL,0); + rescanSpace(dialog,state); + SetFocus(tree); + return FALSE; + } + const auto state=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(!state) return FALSE; + const auto tree=GetDlgItem(dialog,spaceTree); + if(message==WM_TIMER && wp==spaceUpdateTimer) + { + updateSpaceTree(dialog,*state); + return TRUE; + } + if(message==WM_NOTIFY) + { + const auto *notification=reinterpret_cast(lp); + if(notification->hwndFrom==tree) + { + if(notification->code==TVN_GETDISPINFOW) + { + auto &item=reinterpret_cast(lp)->item; + const auto index=static_cast(item.lParam); + if(index>=state->nodes.size()) return TRUE; + const auto &node=state->nodes[index]; + if(item.mask&TVIF_CHILDREN) item.cChildren=node.folder && !node.link && + (state->scanning || !node.children.empty())?1:0; + if((item.mask&TVIF_TEXT) && item.pszText && item.cchTextMax>0) + { + const auto text=spaceNodeText(*state,index); + lstrcpynW(item.pszText,text.c_str(),item.cchTextMax); + } + return TRUE; + } + if(notification->code==TVN_ITEMEXPANDINGW) + { + const auto &item=*reinterpret_cast(lp); + const auto index=static_cast(item.itemNew.lParam); + if(item.action==TVE_EXPAND && indexnodes.size()) expandSpaceNode(tree,*state,index); + } + if(notification->code==TVN_SELCHANGEDW) + { + const auto selected=selectedSpaceNode(tree,*state); + EnableWindow(GetDlgItem(dialog,spaceView),selected && !state->nodes[*selected].folder); + EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value()); + } + } + } + if(message==WM_COMMAND) + { + const auto command=LOWORD(wp); + if(command==spaceStop && IsWindowEnabled(GetDlgItem(dialog,spaceStop))) + { + state->run->stop.request_stop(); + EnableWindow(GetDlgItem(dialog,spaceStop),FALSE); + updateSpaceTree(dialog,*state); + return TRUE; + } + if(command==spaceRescan && IsWindowEnabled(GetDlgItem(dialog,spaceRescan))) + { + rescanSpace(dialog,*state); + return TRUE; + } + if(command==IDOK || command==spaceView) + { + if(const auto selected=selectedSpaceNode(tree,*state)) + { + const auto &node=state->nodes[*selected]; + if(command==spaceView && node.folder) return TRUE; + state->selected=node.path; + state->selectedFolder=node.folder; + FilesModalDialog::finish(dialog,command); + } + return TRUE; + } + } + if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(message==WM_DESTROY) + { + if(state->run) state->run->stop.request_stop(); + KillTimer(dialog,spaceUpdateTimer); + } + return paintCopyDialog(dialog,message,wp,lp,L" Space Analyzer ",false,{spaceFooter}); +} + +void openSpaceAnalyzer(HWND owner,Panel &panel) +{ + if(panel.peer || panel.ftp || panel.directory.empty()) + { + setStatus(L"Space Analyzer requires an open local folder."); + return; + } + const auto origin=static_cast(&panel-panels); + SpaceAnalyzer state{.root=panel.directory}; + const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(118),owner, + spaceAnalyzerDialog,reinterpret_cast(&state)); + if(answer==spaceView) + { + ks::files::openTextWindow(owner,state.selected,false,textWindowDialogs(),nullptr); + return; + } + if(answer!=IDOK) return; + + if(quickViewWindow) toggleQuickView(owner); + if(terminalVisible) showTerminal(owner,false); + const auto index=1-origin; + auto &other=panels[index]; + activatePanel(index); + panelClipboardContext=true; + if(state.selectedFolder) openOn(other,state.selected,true,{}); + else revealLocalFile(other,state.selected); +} From ea6338e9b9cbe0eb1807fdccdde9eccd7890c489 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 14:34:06 +0200 Subject: [PATCH 11/61] Analyze volume usage and add a Files treemap Refs #95 --- CMakeLists.txt | 5 + FILES-UI.md | 19 +- resources/files.rc | 8 +- src/files_main.cpp | 26 ++- src/files_space_analyzer.inl | 262 +++++++++++++++++++++++--- src/files_space_map.inl | 190 +++++++++++++++++++ tests/files_commands_ui.ps1 | 65 +++++++ tests/files_comparison_splitter.ps1 | 95 ++-------- tests/files_space_analyzer_layout.ps1 | 62 ++++++ 9 files changed, 613 insertions(+), 119 deletions(-) create mode 100644 src/files_space_map.inl create mode 100644 tests/files_commands_ui.ps1 create mode 100644 tests/files_space_analyzer_layout.ps1 diff --git a/CMakeLists.txt b/CMakeLists.txt index c02d213..1b47474 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -198,6 +198,11 @@ add_test(NAME files-comparison-splitter -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_comparison_splitter.ps1" -Executable "$") set_tests_properties(files-comparison-splitter PROPERTIES RUN_SERIAL TRUE TIMEOUT 35) +add_test(NAME files-space-analyzer-layout + COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass + -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_layout.ps1" + -Executable "$") +set_tests_properties(files-space-analyzer-layout PROPERTIES RUN_SERIAL TRUE TIMEOUT 25) find_program(KSWITCHER_NODE NAMES node) if(KSWITCHER_NODE) add_test(NAME files-terminal-enter diff --git a/FILES-UI.md b/FILES-UI.md index f693363..fdd341d 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -455,10 +455,21 @@ Warning і початковий фокус на No. переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук з тією самою маскою й видимістю прихованих файлів. -- **Commands → Space Analyzer** аналізує поточну локальну папку у фоні - тим самим обходом, що й підрахунок розмірів F3. У дереві показано розмір - і відсоток від батьківської папки. Посилання на каталоги не обходяться. - Stop лишає часткові результати, а Rescan повторює аналіз із початку. +- **Commands → Space Analyzer** показує місткість і вільне місце за даними + Windows перед скануванням. Volume вибирає корінь тому, Folder повертає + поточну локальну папку, Start запускає фоновий аналіз тим самим обходом, + що й підрахунок розмірів F3. Посилання на каталоги всередині області + сканування позначаються як link. Stop залишає часткові результати, а + Rescan повторює аналіз із початку. +- Дерево показує логічний розмір, зайняті байти та частку логічного розміру + від батьківської папки. Знак + позначає частковий підрахунок. Зайняті байти + підсумовуються за файловими записами, включно з окремими іменами для + жорстких посилань. Службові дані файлової системи в цей підсумок не входять. + Відсутні дані про зайняті байти позначаються в рядку стану. +- Treemap показує дочірні елементи вибраної папки прямокутниками, + пропорційними до їхнього логічного розміру. Дрібні елементи доступні в + дереві. Клік по плитці відкриває точний елемент у сусідній панелі. Стрілки + переводять фокус між плитками, Enter відкриває плитку у фокусі. - View відкриває вибраний файл у спільному переглядачі Files. Show in other panel відкриває вибрану папку або ставить курсор на файл у сусідній панелі. Команди роботи з файлами доступні там. Якщо фільтр приховує diff --git a/resources/files.rc b/resources/files.rc index ceebeb9..6145898 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -433,17 +433,21 @@ BEGIN CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17 END -118 DIALOGEX 0, 0, 385, 209 +118 DIALOGEX 0, 0, 420, 209 STYLE DS_SETFONT | DS_CENTER | WS_POPUP CAPTION "Space Analyzer" FONT 10, "Consolas" BEGIN LTEXT "", 488, 16, 15, 353, 13, SS_PATHELLIPSIS + LTEXT "", 495, 16, 28, 353, 13, SS_ENDELLIPSIS + CONTROL "Vo&lume", 496, "Button", BS_OWNERDRAW | WS_TABSTOP, 16, 43, 64, 16 + CONTROL "Tree&map", 497, "Button", BS_OWNERDRAW | WS_TABSTOP, 84, 43, 64, 16 + CONTROL "", 498, "Static", SS_OWNERDRAW | SS_NOTIFY | WS_TABSTOP | NOT WS_VISIBLE, 16, 60, 353, 105 CONTROL "", 489, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 16, 32, 353, 131 LTEXT "", 490, 16, 167, 353, 14, SS_ENDELLIPSIS LTEXT "", 491, 12, 184, 1, 1, NOT WS_VISIBLE CONTROL "S&top", 492, "Button", BS_OWNERDRAW | WS_TABSTOP, 22, 189, 46, 16 - CONTROL "&Rescan", 493, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 189, 50, 16 + CONTROL "St&art", 493, "Button", BS_OWNERDRAW | WS_TABSTOP, 72, 189, 50, 16 CONTROL "&View", 494, "Button", BS_OWNERDRAW | WS_TABSTOP, 126, 189, 46, 16 CONTROL "&Show in other panel", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 176, 189, 102, 16 CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 282, 189, 50, 16 diff --git a/src/files_main.cpp b/src/files_main.cpp index b1da0e3..a83ca53 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -4046,26 +4046,34 @@ LONG farDialogButtonWidth(HWND button) return (characters+5)*cellWidth; } +LONG dialogButtonWidth(HWND dialog,int id,bool native) +{ + if(!native) return farDialogButtonWidth(GetDlgItem(dialog,id)); + const auto bounds=dialogControlBounds(dialog,id); + return bounds.right-bounds.left; +} + +LONG dialogButtonGroupWidth(HWND dialog,std::initializer_list controls,bool native=false) +{ + const auto gap=dialogColumnGap(); + LONG width=-gap; + for(const auto id:controls) width+=dialogButtonWidth(dialog,id,native)+gap; + return std::max(0L,width); +} + void groupDialogButtons(HWND dialog,std::initializer_list controls,bool native=false) { RECT client{}; GetClientRect(dialog,&client); const auto gap=dialogColumnGap(); - const auto width=[&](int id) - { - if(!native) return farDialogButtonWidth(GetDlgItem(dialog,id)); - const auto bounds=dialogControlBounds(dialog,id); - return bounds.right-bounds.left; - }; - LONG rowWidth=-gap; - for(const auto id:controls) rowWidth+=width(id)+gap; + const auto rowWidth=dialogButtonGroupWidth(dialog,controls,native); if(rowWidth>client.right) return; auto x=native?dialogControlBounds(dialog,*(controls.end()-1)).right-rowWidth: (client.right-rowWidth)/2; for(const auto id:controls) { const auto bounds=dialogControlBounds(dialog,id); - const auto buttonWidth=width(id); + const auto buttonWidth=dialogButtonWidth(dialog,id,native); SetWindowPos(GetDlgItem(dialog,id),nullptr,x,bounds.top,buttonWidth,bounds.bottom-bounds.top, SWP_NOZORDER|SWP_NOACTIVATE); x+=buttonWidth+gap; diff --git a/src/files_space_analyzer.inl b/src/files_space_analyzer.inl index 73b3e70..0605fc9 100644 --- a/src/files_space_analyzer.inl +++ b/src/files_space_analyzer.inl @@ -1,12 +1,84 @@ constexpr int spacePath=488,spaceTree=489,spaceStatus=490,spaceFooter=491; constexpr int spaceStop=492,spaceRescan=493,spaceView=494; +constexpr int spaceCapacity=495,spaceScope=496,spaceMapButton=497,spaceMap=498; constexpr UINT_PTR spaceUpdateTimer=1; +constexpr UINT_PTR spaceVolumeTimer=2; constexpr size_t spaceBatchSize=256; +constexpr std::initializer_list spaceFooterButtons{spaceStop,spaceRescan,spaceView,IDOK,IDCANCEL}; + +struct SpaceVolume +{ + fs::path root; + std::optional> capacity; +}; + +std::future readSpaceVolume(const fs::path &folder) +{ + std::packaged_task task([folder] { + SpaceVolume result; + std::wstring root(32768,L'\0'); + if(GetVolumePathNameW(folder.c_str(),root.data(),static_cast(root.size()))) + { + root.resize(wcslen(root.c_str())); + result.root=fs::path(std::move(root)); + } + ULARGE_INTEGER total{},free{}; + if(GetDiskFreeSpaceExW(result.root.empty()?folder.c_str():result.root.c_str(),&free,&total,nullptr)) + result.capacity=std::pair{total.QuadPart,free.QuadPart}; + return result; + }); + auto result=task.get_future(); + std::thread(std::move(task)).detach(); + return result; +} + +std::optional 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(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(metadata.AllocationSize.QuadPart); + return {}; +} + +struct SpaceAllocation +{ + FolderSize known; + size_t measured{}, unavailable{}; + + void add(std::optional size) + { + if(size) + { + ++measured; + known.add(*size); + } + else ++unavailable; + } +}; + +struct SpaceTile +{ + RECT box; + size_t node; +}; struct SpaceEvent { fs::path path; std::optional item; + std::optional allocated; }; struct SpaceRun @@ -18,10 +90,10 @@ struct SpaceRun bool finished{}, stopped{}; }; -std::shared_ptr startSpaceRun(const fs::path &root) +std::shared_ptr startSpaceRun(const fs::path &root,bool volume) { auto run=std::make_shared(); - std::thread([run,root] { + std::thread([run,root,volume] { std::vector batch; auto lastUpdate=GetTickCount64(); const auto publish=[&] { @@ -37,9 +109,12 @@ std::shared_ptr startSpaceRun(const fs::path &root) { FilesConnection host(nullptr); total=measureFolder(root,stop,[&](const fs::path &directory,const FileVisitor &visit) { + if(volume && directory==root) return !stop.stop_requested() && listFiles(host,directory,visit); return listMeasuredDirectory(host,directory,visit,stop); },[&](const fs::path &path,const FileInfo *info) { - batch.push_back({path,info?std::optional(*info):std::nullopt}); + const auto allocate=info && !(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)); + batch.push_back({path,info?std::optional(*info):std::nullopt, + allocate?allocatedFileBytes(path,info->attributes):std::nullopt}); if(batch.size()>=spaceBatchSize || GetTickCount64()-lastUpdate>=80) publish(); }); publish(); @@ -57,6 +132,7 @@ struct SpaceNode { fs::path path; FolderSize size; + SpaceAllocation allocated; size_t parent{}; std::vector children; HTREEITEM item{}; @@ -65,13 +141,17 @@ struct SpaceNode struct SpaceAnalyzer { - fs::path root, selected; - bool selectedFolder{}; + fs::path folder, root, selected; + SpaceVolume volume; + std::future pendingVolume; + bool selectedFolder{}, volumeScope{}, mapVisible{}; std::shared_ptr run; std::vector nodes; std::map directories; - size_t files{}; - bool scanning{}; + size_t files{}, mapFolder{}, selectedTile{}; + std::vector tiles; + ULONGLONG lastMapUpdate{}; + bool scanning{}, hasResults{}; }; void layoutSpaceAnalyzer(HWND dialog) @@ -86,12 +166,25 @@ void layoutSpaceAnalyzer(HWND dialog) }; auto top=dialogListInset(frame,textHeight); place(spacePath,top,textHeight); + top+=textHeight; + place(spaceCapacity,top,textHeight); top+=textHeight+dialogRowGap(); + const auto buttonHeight=textHeight; + auto x=inset; + for(const auto id:{spaceScope,spaceMapButton}) + { + const auto button=GetDlgItem(dialog,id); + const auto width=std::max(12L*cellWidth,farDialogButtonWidth(button)); + SetWindowPos(button,nullptr,x,top,width,buttonHeight,SWP_NOZORDER|SWP_NOACTIVATE); + x+=width+dialogColumnGap(); + } + top+=buttonHeight+dialogRowGap(); place(spaceTree,top,9*textHeight); + place(spaceMap,top,9*textHeight); top+=9*textHeight+dialogRowGap(); place(spaceStatus,top,textHeight); place(spaceFooter,top+textHeight+dialogRowGap(),1); - layoutDialogButtons(dialog,spaceFooter,{spaceStop,spaceRescan,spaceView,IDOK,IDCANCEL}); + layoutDialogButtons(dialog,spaceFooter,spaceFooterButtons); } HTREEITEM insertSpaceNode(HWND tree,SpaceAnalyzer &state,size_t index) @@ -139,6 +232,7 @@ void addSpaceEvent(HWND tree,SpaceAnalyzer &state,SpaceEvent event) else ++state.files; state.nodes.push_back({.path=std::move(event.path),.size={bytes,false},.parent=parent->second, .folder=folder,.link=link}); + if(!folder && !link) state.nodes[index].allocated.add(event.allocated); auto &parentNode=state.nodes[parent->second]; parentNode.children.push_back(index); if(parentNode.item && parentNode.expanded) @@ -149,10 +243,25 @@ void addSpaceEvent(HWND tree,SpaceAnalyzer &state,SpaceEvent event) for(auto i=parent->second;;i=state.nodes[i].parent) { state.nodes[i].size.add(bytes); + if(!folder && !link) state.nodes[i].allocated.add(event.allocated); if(!i) break; } } +std::wstring spaceLogicalSize(const SpaceNode &node) +{ + return formatSize(node.size.bytes)+(node.size.partial?L"+ logical":L" logical"); +} + +std::wstring spaceAllocatedSize(const SpaceNode &node) +{ + const auto &allocation=node.allocated; + if(!allocation.measured && allocation.unavailable) return L"— on disk"; + auto result=formatSize(allocation.known.bytes); + if(allocation.unavailable || allocation.known.partial || node.size.partial) result+=L"+"; + return result+L" on disk"; +} + std::wstring spaceNodeText(const SpaceAnalyzer &state,size_t index) { const auto &node=state.nodes[index]; @@ -165,9 +274,9 @@ std::wstring spaceNodeText(const SpaceAnalyzer &state,size_t index) if(name.back()>=0xD800 && name.back()<=0xDBFF) name.pop_back(); name+=L"…"; } + if(!state.hasResults) return name; if(node.link) return name+L" [link]"; - auto result=name+L" — "+formatSize(node.size.bytes); - if(node.size.partial) result+=L"+"; + auto result=name+L" — "+spaceLogicalSize(node)+L" · "+spaceAllocatedSize(node); if(parent.size.bytes) { wchar_t share[48]{}; @@ -187,6 +296,8 @@ std::optional selectedSpaceNode(HWND tree,const SpaceAnalyzer &state) return {}; } +#include "files_space_map.inl" + void updateSpaceTree(HWND dialog,SpaceAnalyzer &state) { const auto tree=GetDlgItem(dialog,spaceTree); @@ -216,21 +327,29 @@ void updateSpaceTree(HWND dialog,SpaceAnalyzer &state) } while(GetTickCount64()=200))) + layoutSpaceMap(GetDlgItem(dialog,spaceMap),state); if(changed || finished) InvalidateRect(tree,nullptr,FALSE); const bool stopping=state.run->stop.stop_requested(); auto status=finished?(stopped?L"Stopped · partial":state.nodes[0].size.partial?L"Partial results":L"Complete"): stopping?L"Stopping…":L"Scanning…"; - SetDlgItemTextW(dialog,spaceStatus,(std::wstring(status)+L" · "+std::to_wstring(state.files)+L" files · shares of parent").c_str()); + const auto &allocation=state.nodes[0].allocated; + auto label=std::wstring(status)+L" · "+std::to_wstring(state.files)+L" files"; + if(allocation.unavailable || allocation.known.partial) label+=L" · on-disk sizes partial"; + else label+=state.mapVisible?L" · logical size by area":L" · logical shares of parent"; + SetDlgItemTextW(dialog,spaceStatus,label.c_str()); if(finished) { EnableWindow(GetDlgItem(dialog,spaceStop),FALSE); EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE); + EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() && + !sameLocalFolder(state.volume.root,state.folder)); KillTimer(dialog,spaceUpdateTimer); } } -void rescanSpace(HWND dialog,SpaceAnalyzer &state) +void resetSpaceResults(HWND dialog,SpaceAnalyzer &state,bool scanning) { const auto tree=GetDlgItem(dialog,spaceTree); TreeView_DeleteAllItems(tree); @@ -239,13 +358,60 @@ void rescanSpace(HWND dialog,SpaceAnalyzer &state) state.directories.clear(); state.directories.emplace(state.root,0); state.files=0; - state.scanning=true; + state.mapFolder=0; + state.tiles.clear(); + state.selectedTile=0; + state.scanning=scanning; + state.hasResults=scanning; TreeView_SelectItem(tree,insertSpaceNode(tree,state,0)); + if(state.mapVisible) layoutSpaceMap(GetDlgItem(dialog,spaceMap),state); EnableWindow(GetDlgItem(dialog,spaceView),FALSE); + EnableWindow(GetDlgItem(dialog,IDOK),!state.mapVisible); +} + +void prepareSpaceScope(HWND dialog,SpaceAnalyzer &state) +{ + state.run.reset(); + const auto scope=state.volumeScope?state.volume.root:state.folder; + state.root=scope; + SetDlgItemTextW(dialog,spacePath,scope.c_str()); + SetDlgItemTextW(dialog,spaceScope,state.volumeScope?L"&Folder":L"Vo&lume"); + SetDlgItemTextW(dialog,spaceRescan,L"St&art"); + SetDlgItemTextW(dialog,spaceStatus,L"Ready to scan"); + EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE); + EnableWindow(GetDlgItem(dialog,spaceStop),FALSE); + resetSpaceResults(dialog,state,false); + layoutSpaceAnalyzer(dialog); +} + +void updateSpaceVolume(HWND dialog,SpaceAnalyzer &state) +{ + if(!state.pendingVolume.valid() || + state.pendingVolume.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return; + try {state.volume=state.pendingVolume.get();} + catch(const std::exception &) {} + KillTimer(dialog,spaceVolumeTimer); + std::wstring caption=L"Volume capacity unavailable"; + if(const auto capacity=state.volume.capacity) + { + caption=L"Capacity "+formatSize(capacity->first)+L" · Free "+formatSize(capacity->second); + if(!state.volume.root.empty()) caption+=L" · "+state.volume.root.native(); + } + SetDlgItemTextW(dialog,spaceCapacity,caption.c_str()); + EnableWindow(GetDlgItem(dialog,spaceScope), + !state.volume.root.empty() && !sameLocalFolder(state.volume.root,state.folder)); + prepareSpaceScope(dialog,state); +} + +void rescanSpace(HWND dialog,SpaceAnalyzer &state) +{ + resetSpaceResults(dialog,state,true); + SetDlgItemTextW(dialog,spaceRescan,L"&Rescan"); EnableWindow(GetDlgItem(dialog,spaceRescan),FALSE); + EnableWindow(GetDlgItem(dialog,spaceScope),FALSE); try { - state.run=startSpaceRun(state.root); + state.run=startSpaceRun(state.root,state.volumeScope); EnableWindow(GetDlgItem(dialog,spaceStop),TRUE); SetTimer(dialog,spaceUpdateTimer,60,nullptr); updateSpaceTree(dialog,state); @@ -255,7 +421,9 @@ void rescanSpace(HWND dialog,SpaceAnalyzer &state) EnableWindow(GetDlgItem(dialog,spaceStop),FALSE); EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE); state.scanning=false; - SetDlgItemTextW(dialog,spaceStatus,L"Could not start folder analysis."); + EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() && + !sameLocalFolder(state.volume.root,state.folder)); + SetDlgItemTextW(dialog,spaceStatus,L"Could not start space analysis."); } } @@ -266,21 +434,49 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l auto &state=*reinterpret_cast(lp); SetWindowLongPtrW(dialog,DWLP_USER,lp); prepareTextDialog(dialog); - SetDlgItemTextW(dialog,spacePath,state.root.c_str()); + SetDlgItemTextW(dialog,spacePath,state.folder.c_str()); + SetDlgItemTextW(dialog,spaceCapacity,L"Reading volume capacity…"); const auto tree=GetDlgItem(dialog,spaceTree); + SetWindowSubclass(GetDlgItem(dialog,spaceMap),spaceMapInput,1,reinterpret_cast(&state)); TreeView_SetBkColor(tree,RGB(255,255,255)); TreeView_SetTextColor(tree,RGB(0,0,0)); layoutSpaceAnalyzer(dialog); const auto inset=dialogFrameMetrics(GetDpiForWindow(dialog)).content(); - FilesModalDialog::fitWidthToOwner(dialog,54*cellWidth+2*inset,layoutSpaceAnalyzer); + // Rescan is one character wider than the initial Start label. + const auto minimum=dialogButtonGroupWidth(dialog,spaceFooterButtons)+cellWidth+2*inset; + FilesModalDialog::fitWidthToOwner(dialog,minimum,layoutSpaceAnalyzer); SendMessageW(dialog,DM_SETDEFID,IDCANCEL,0); - rescanSpace(dialog,state); + resetSpaceResults(dialog,state,false); + EnableWindow(GetDlgItem(dialog,spaceScope),FALSE); + EnableWindow(GetDlgItem(dialog,spaceRescan),FALSE); + EnableWindow(GetDlgItem(dialog,spaceStop),FALSE); + try + { + state.pendingVolume=readSpaceVolume(state.folder); + SetTimer(dialog,spaceVolumeTimer,60,nullptr); + updateSpaceVolume(dialog,state); + } + catch(const std::exception &) + { + SetDlgItemTextW(dialog,spaceCapacity,L"Volume capacity unavailable"); + prepareSpaceScope(dialog,state); + } SetFocus(tree); return FALSE; } const auto state=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); if(!state) return FALSE; const auto tree=GetDlgItem(dialog,spaceTree); + if(message==WM_DRAWITEM && wp==spaceMap) + { + paintSpaceMap(*reinterpret_cast(lp),*state); + return TRUE; + } + if(message==WM_TIMER && wp==spaceVolumeTimer) + { + updateSpaceVolume(dialog,*state); + return TRUE; + } if(message==WM_TIMER && wp==spaceUpdateTimer) { updateSpaceTree(dialog,*state); @@ -315,8 +511,8 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l if(notification->code==TVN_SELCHANGEDW) { const auto selected=selectedSpaceNode(tree,*state); - EnableWindow(GetDlgItem(dialog,spaceView),selected && !state->nodes[*selected].folder); - EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value()); + EnableWindow(GetDlgItem(dialog,spaceView),!state->mapVisible && selected && !state->nodes[*selected].folder); + EnableWindow(GetDlgItem(dialog,IDOK),!state->mapVisible && selected.has_value()); } } } @@ -330,6 +526,18 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l updateSpaceTree(dialog,*state); return TRUE; } + if(command==spaceScope && IsWindowEnabled(GetDlgItem(dialog,spaceScope))) + { + state->volumeScope=!state->volumeScope; + prepareSpaceScope(dialog,*state); + return TRUE; + } + if(command==spaceMapButton) + { + showSpaceMap(dialog,*state,!state->mapVisible); + if(state->run) updateSpaceTree(dialog,*state); + return TRUE; + } if(command==spaceRescan && IsWindowEnabled(GetDlgItem(dialog,spaceRescan))) { rescanSpace(dialog,*state); @@ -337,14 +545,9 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l } if(command==IDOK || command==spaceView) { - if(const auto selected=selectedSpaceNode(tree,*state)) - { - const auto &node=state->nodes[*selected]; - if(command==spaceView && node.folder) return TRUE; - state->selected=node.path; - state->selectedFolder=node.folder; - FilesModalDialog::finish(dialog,command); - } + if(!state->mapVisible) + if(const auto selected=selectedSpaceNode(tree,*state)) + finishSpaceSelection(dialog,*state,*selected,command); return TRUE; } } @@ -357,6 +560,7 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l { if(state->run) state->run->stop.request_stop(); KillTimer(dialog,spaceUpdateTimer); + KillTimer(dialog,spaceVolumeTimer); } return paintCopyDialog(dialog,message,wp,lp,L" Space Analyzer ",false,{spaceFooter}); } @@ -369,7 +573,7 @@ void openSpaceAnalyzer(HWND owner,Panel &panel) return; } const auto origin=static_cast(&panel-panels); - SpaceAnalyzer state{.root=panel.directory}; + SpaceAnalyzer state{.folder=panel.directory,.root=panel.directory}; const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(118),owner, spaceAnalyzerDialog,reinterpret_cast(&state)); if(answer==spaceView) diff --git a/src/files_space_map.inl b/src/files_space_map.inl new file mode 100644 index 0000000..571670a --- /dev/null +++ b/src/files_space_map.inl @@ -0,0 +1,190 @@ +void finishSpaceSelection(HWND dialog,SpaceAnalyzer &state,size_t selected,int action) +{ + if(selected>=state.nodes.size()) return; + const auto &node=state.nodes[selected]; + if(action==spaceView && node.folder) return; + state.selected=node.path; + state.selectedFolder=node.folder; + FilesModalDialog::finish(dialog,action); +} + +void divideSpaceTiles(std::span nodes,std::span prefix,RECT bounds, + LONG margin,std::vector &tiles) +{ + const auto width=bounds.right-bounds.left, height=bounds.bottom-bounds.top; + if(widthprefix.begin()+1 && middle-pivot[-1]<*pivot-middle)) --pivot; + const auto offset=static_cast(pivot-prefix.begin()); + const auto share=(*pivot-prefix.front())/total; + auto first=bounds, second=bounds; + if(width>=height) + { + const auto split=bounds.left+std::clamp(static_cast(width*share+0.5L),1L,width-1); + first.right=second.left=split; + } + else + { + const auto split=bounds.top+std::clamp(static_cast(height*share+0.5L),1L,height-1); + first.bottom=second.top=split; + } + divideSpaceTiles(nodes.first(offset),prefix.first(offset+1),first,margin,tiles); + divideSpaceTiles(nodes.subspan(offset),prefix.subspan(offset),second,margin,tiles); +} + +void layoutSpaceMap(HWND map,SpaceAnalyzer &state) +{ + state.lastMapUpdate=GetTickCount64(); + const auto previous=state.selectedTile::max(); + state.tiles.clear(); + state.selectedTile=0; + if(state.mapFolder>=state.nodes.size()) return; + std::vector items; + for(auto index:state.nodes[state.mapFolder].children) + if(state.nodes[index].size.bytes) items.push_back(index); + std::sort(items.begin(),items.end(),[&](size_t left,size_t right) { + const auto a=state.nodes[left].size.bytes, b=state.nodes[right].size.bytes; + return a!=b?a>b:left prefix{0}; + prefix.reserve(items.size()+1); + for(auto index:items) prefix.push_back(prefix.back()+state.nodes[index].size.bytes); + RECT bounds{}; + GetClientRect(map,&bounds); + const auto minimum=std::max(4,MulDiv(8,GetDpiForWindow(map),96)); + divideSpaceTiles(items,prefix,bounds,minimum,state.tiles); + for(size_t index=0;index(GetStockObject(DC_BRUSH)); + const auto focused=GetFocus()==paint.hwndItem; + for(size_t index=0;index=3*cellWidth && bounds.bottom-bounds.top>=textHeight) + { + const auto name=node.path.filename().native(); + DrawTextW(paint.hDC,name.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS); + bounds.top+=textHeight; + if(bounds.bottom-bounds.top>=textHeight) + { + const auto logical=spaceLogicalSize(node); + DrawTextW(paint.hDC,logical.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS); + bounds.top+=textHeight; + if(bounds.bottom-bounds.top>=textHeight) + { + const auto allocated=spaceAllocatedSize(node); + DrawTextW(paint.hDC,allocated.c_str(),-1,&bounds,DT_SINGLELINE|DT_NOPREFIX|DT_END_ELLIPSIS); + } + } + } + } +} + +LRESULT CALLBACK spaceMapInput(HWND map,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR payload) +{ + auto &state=*reinterpret_cast(payload); + if(message==WM_SIZE && state.mapVisible) layoutSpaceMap(map,state); + if(message==WM_SETFOCUS || message==WM_KILLFOCUS) InvalidateRect(map,nullptr,FALSE); + if(message==WM_LBUTTONDOWN) + { + SetFocus(map); + return 0; + } + if(message==WM_LBUTTONUP) + { + const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; + for(const auto &tile:state.tiles) + if(PtInRect(&tile.box,point)) + { + finishSpaceSelection(GetParent(map),state,tile.node,IDOK); + break; + } + return 0; + } + if(message==WM_GETDLGCODE) + { + const auto *key=reinterpret_cast(lp); + return DLGC_WANTARROWS|(key && key->message==WM_KEYDOWN && wp==VK_RETURN?DLGC_WANTMESSAGE:0); + } + if(message==WM_KEYDOWN && !state.tiles.empty()) + { + if(wp==VK_RETURN) + { + finishSpaceSelection(GetParent(map),state,state.tiles[state.selectedTile].node,IDOK); + return 0; + } + if(wp==VK_DOWN || wp==VK_RIGHT || wp==VK_UP || wp==VK_LEFT) + { + auto &index=state.selectedTile; + if(wp==VK_DOWN || wp==VK_RIGHT) index=(index+1)%state.tiles.size(); + else index=index?index-1:state.tiles.size()-1; + InvalidateRect(map,nullptr,FALSE); + return 0; + } + } + return DefSubclassProc(map,message,wp,lp); +} + +void showSpaceMap(HWND dialog,SpaceAnalyzer &state,bool show) +{ + const auto tree=GetDlgItem(dialog,spaceTree), map=GetDlgItem(dialog,spaceMap); + state.mapVisible=show; + if(show) + { + const auto index=selectedSpaceNode(tree,state).value_or(0); + const auto &node=state.nodes[index]; + state.mapFolder=node.folder && !node.link?index:node.parent; + layoutSpaceMap(map,state); + } + ShowWindow(tree,show?SW_HIDE:SW_SHOW); + ShowWindow(map,show?SW_SHOW:SW_HIDE); + SetDlgItemTextW(dialog,spaceMapButton,show?L"Tr&ee":L"Tree&map"); + const auto selection=selectedSpaceNode(tree,state); + EnableWindow(GetDlgItem(dialog,spaceView),!show && selection && !state.nodes[*selection].folder); + EnableWindow(GetDlgItem(dialog,IDOK),!show && selection.has_value()); + SetFocus(show?map:tree); +} diff --git a/tests/files_commands_ui.ps1 b/tests/files_commands_ui.ps1 new file mode 100644 index 0000000..38efd08 --- /dev/null +++ b/tests/files_commands_ui.ps1 @@ -0,0 +1,65 @@ +Add-Type @' +using System; +using System.Text; +using System.Runtime.InteropServices; + +public static class FilesCommandsUi { + [StructLayout(LayoutKind.Sequential)] + public struct Rect { public int Left, Top, Right, Bottom; } + [StructLayout(LayoutKind.Sequential)] + public struct Point { public int X, Y; } + [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect rect); + [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr window, IntPtr after, int x, int y, int width, int height, uint flags); + [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr window, int command); + [DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr window); + [DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id); + [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window); + [DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra); + [DllImport("user32.dll", CharSet=CharSet.Unicode)] + public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title); + [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window); + [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid); + [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); + [DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect); + [DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr window, ref Point point); + [DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags); + [DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint msg, IntPtr w, IntPtr l); + [DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l); + [DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")] + public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text); + public static bool Activate(IntPtr window) { + if (GetForegroundWindow() == window) return true; + keybd_event(18, 0, 0, UIntPtr.Zero); + keybd_event(18, 0, 2, UIntPtr.Zero); + SetForegroundWindow(window); + return GetForegroundWindow() == window; + } +} +'@ + +function Wait-For([string]$Name, [scriptblock]$Condition) { + for ($attempt = 0; $attempt -lt 50; ++$attempt) { + $value = & $Condition + if ($value) { return $value } + Start-Sleep -Milliseconds 100 + } + throw "Timed out waiting for $Name." +} + +function Invoke-FilesCommand([IntPtr]$Window, [string]$LabelPattern) { + [void][FilesCommandsUi]::Post($Window, 273, [IntPtr]132, [IntPtr]::Zero) + $picker = [FilesCommandsUi]::GetDlgItem($Window, 121) + [void](Wait-For 'the Commands menu' { [FilesCommandsUi]::IsWindowVisible($picker) }) + $count = [FilesCommandsUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() + for ($row = 0; $row -lt $count; ++$row) { + $label = [Text.StringBuilder]::new(128) + [void][FilesCommandsUi]::Read($picker, 393, [IntPtr]$row, $label) + if ($label.ToString() -like $LabelPattern) { + [void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$row, [IntPtr]::Zero) + [void][FilesCommandsUi]::Post($Window, 273, [IntPtr](0x20000 + 121), $picker) + return + } + } + throw "Missing Files command matching $LabelPattern." +} diff --git a/tests/files_comparison_splitter.ps1 b/tests/files_comparison_splitter.ps1 index 9e8a294..41f4fe7 100644 --- a/tests/files_comparison_splitter.ps1 +++ b/tests/files_comparison_splitter.ps1 @@ -2,50 +2,7 @@ param([Parameter(Mandatory)][string]$Executable) $ErrorActionPreference = 'Stop' Add-Type -AssemblyName System.Drawing -Add-Type @' -using System; -using System.Text; -using System.Runtime.InteropServices; - -public static class ComparisonSplitterUi { - [StructLayout(LayoutKind.Sequential)] - public struct Rect { public int Left, Top, Right, Bottom; } - [StructLayout(LayoutKind.Sequential)] - public struct Point { public int X, Y; } - [DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id); - [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); - [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr window); - [DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra); - [DllImport("user32.dll", CharSet=CharSet.Unicode)] - public static extern IntPtr FindWindowEx(IntPtr parent, IntPtr after, string className, string title); - [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window); - [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid); - [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); - [DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect); - [DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr window, ref Point point); - [DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags); - [DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint msg, IntPtr w, IntPtr l); - [DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l); - [DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")] - public static extern IntPtr Read(IntPtr window, uint msg, IntPtr w, StringBuilder text); - public static bool Activate(IntPtr window) { - if (GetForegroundWindow() == window) return true; - keybd_event(18, 0, 0, UIntPtr.Zero); - keybd_event(18, 0, 2, UIntPtr.Zero); - SetForegroundWindow(window); - return GetForegroundWindow() == window; - } -} -'@ - -function Wait-For([string]$Name, [scriptblock]$Condition) { - for ($attempt = 0; $attempt -lt 50; ++$attempt) { - $value = & $Condition - if ($value) { return $value } - Start-Sleep -Milliseconds 100 - } - throw "Timed out waiting for $Name." -} +. "$PSScriptRoot/files_commands_ui.ps1" $preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files') $names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance' @@ -57,7 +14,7 @@ foreach ($name in $names) { } $temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\') $root = Join-Path $temp ('ks-files-splitter-' + [Guid]::NewGuid().ToString('N')) -$dpi = [ComparisonSplitterUi]::SetThreadDpiAwarenessContext([IntPtr](-4)) +$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4)) $process = $null try { $left = Join-Path $root 'left' @@ -78,52 +35,40 @@ try { if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle } } foreach ($id in 102, 103) { - $panel = [ComparisonSplitterUi]::GetDlgItem($main, $id) + $panel = [FilesCommandsUi]::GetDlgItem($main, $id) [void](Wait-For 'the test file in the panel' { - [ComparisonSplitterUi]::Send($panel, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() -eq 2 + [FilesCommandsUi]::Send($panel, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() -eq 2 }) - [void][ComparisonSplitterUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero) + [void][FilesCommandsUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero) } - [void][ComparisonSplitterUi]::Post($main, 273, [IntPtr]132, [IntPtr]::Zero) - $picker = [ComparisonSplitterUi]::GetDlgItem($main, 121) - [void](Wait-For 'the Commands menu' { [ComparisonSplitterUi]::IsWindowVisible($picker) }) - $row = -1 - $count = [ComparisonSplitterUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt64() - for ($i = 0; $i -lt $count; ++$i) { - $label = [Text.StringBuilder]::new(128) - [void][ComparisonSplitterUi]::Read($picker, 393, [IntPtr]$i, $label) - if ($label.ToString() -like 'Compare files*') { $row = $i; break } - } - if ($row -lt 0) { throw 'Missing Compare files command.' } - [void][ComparisonSplitterUi]::Send($picker, 390, [IntPtr]$row, [IntPtr]::Zero) - [void][ComparisonSplitterUi]::Post($main, 273, [IntPtr](0x20000 + 121), $picker) + Invoke-FilesCommand $main 'Compare files*' $list = Wait-For 'the foreground comparison list' { $dialog = [IntPtr]::Zero - while (($dialog = [ComparisonSplitterUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) { + while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) { [uint32]$ownerPid = 0 - [void][ComparisonSplitterUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid) + [void][FilesCommandsUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid) if ($ownerPid -ne $process.Id) { continue } - $control = [ComparisonSplitterUi]::GetDlgItem($dialog, 402) - if ([ComparisonSplitterUi]::IsWindowVisible($control) -and [ComparisonSplitterUi]::Activate($dialog)) { + $control = [FilesCommandsUi]::GetDlgItem($dialog, 402) + if ([FilesCommandsUi]::IsWindowVisible($control) -and [FilesCommandsUi]::Activate($dialog)) { return $control } } } - $bounds = [ComparisonSplitterUi+Rect]::new() - [void][ComparisonSplitterUi]::GetClientRect($list, [ref]$bounds) + $bounds = [FilesCommandsUi+Rect]::new() + [void][FilesCommandsUi]::GetClientRect($list, [ref]$bounds) $middle = [int]($bounds.Right / 2) $destination = [int]($bounds.Right * 0.65) $mouseY = 30 -shl 16 - [void][ComparisonSplitterUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle)) + [void][FilesCommandsUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle)) for ($x = $middle + 5; $x -lt $destination; $x += 5) { - [void][ComparisonSplitterUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x)) - [void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101) + [void][FilesCommandsUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x)) + [void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101) } - [void][ComparisonSplitterUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination)) - [void][ComparisonSplitterUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101) - $origin = [ComparisonSplitterUi+Point]::new() - [void][ComparisonSplitterUi]::ClientToScreen($list, [ref]$origin) + [void][FilesCommandsUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination)) + [void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101) + $origin = [FilesCommandsUi+Point]::new() + [void][FilesCommandsUi]::ClientToScreen($list, [ref]$origin) $bitmap = [Drawing.Bitmap]::new($bounds.Right, 1) try { $graphics = [Drawing.Graphics]::FromImage($bitmap) @@ -146,7 +91,7 @@ try { else { $preferences.DeleteValue($name, $false) } } $preferences.Dispose() - if ($dpi) { [void][ComparisonSplitterUi]::SetThreadDpiAwarenessContext($dpi) } + if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) } if (Test-Path -LiteralPath $root) { $resolved = (Resolve-Path -LiteralPath $root).Path if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-files-splitter-*') { diff --git a/tests/files_space_analyzer_layout.ps1 b/tests/files_space_analyzer_layout.ps1 new file mode 100644 index 0000000..ef88939 --- /dev/null +++ b/tests/files_space_analyzer_layout.ps1 @@ -0,0 +1,62 @@ +param([Parameter(Mandatory)][string]$Executable) + +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/files_commands_ui.ps1" + +$dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4)) +$process = $null +try { + $process = Start-Process -FilePath (Resolve-Path -LiteralPath $Executable) -PassThru + $main = Wait-For 'the Files window' { + $process.Refresh() + if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle } + } + [void][FilesCommandsUi]::ShowWindow($main, 9) + $width = [int](350 * [FilesCommandsUi]::GetDpiForWindow($main) / 96) + if (![FilesCommandsUi]::SetWindowPos($main, [IntPtr]::Zero, 0, 0, $width, 0, 22)) { + throw 'Could not narrow the Files window.' + } + Invoke-FilesCommand $main 'Space Analyzer' + $dialog = Wait-For 'the visible Space Analyzer' { + $candidate = [IntPtr]::Zero + while (($candidate = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $candidate, '#32770', 'Space Analyzer')) -ne [IntPtr]::Zero) { + [uint32]$owner = 0 + [void][FilesCommandsUi]::GetWindowThreadProcessId($candidate, [ref]$owner) + if ($owner -eq $process.Id -and [FilesCommandsUi]::IsWindowVisible($candidate)) { return $candidate } + } + } + + $outer = [FilesCommandsUi+Rect]::new() + if (![FilesCommandsUi]::GetWindowRect($dialog, [ref]$outer)) { throw 'Could not measure the Space Analyzer.' } + $previousRight = $outer.Left + $firstLeft = 0 + $midY = 0 + foreach ($id in 492, 493, 494, 1, 2) { + $button = [FilesCommandsUi]::GetDlgItem($dialog, $id) + $rect = [FilesCommandsUi+Rect]::new() + if (![FilesCommandsUi]::IsWindowVisible($button) -or ![FilesCommandsUi]::GetWindowRect($button, [ref]$rect)) { + throw "Space Analyzer footer button $id was unavailable." + } + if ($rect.Left -le $previousRight -or $rect.Right -ge $outer.Right -or $rect.Bottom -ge $outer.Bottom) { + throw "Space Analyzer footer button $id was clipped or overlapped at narrow width." + } + if ($id -eq 492) { + $firstLeft = $rect.Left + $midY = $rect.Top + $rect.Bottom + } elseif ([Math]::Abs($midY - $rect.Top - $rect.Bottom) -gt 1) { + throw "Space Analyzer footer button $id was outside the shared button row." + } + $previousRight = $rect.Right + } + if ([Math]::Abs(($firstLeft + $previousRight) - ($outer.Left + $outer.Right)) -gt 2) { + throw 'Space Analyzer footer buttons were off center.' + } + 'Verified the full and centered Space Analyzer footer at narrow width.' +} finally { + # End this fixture without saving its temporary window dimensions. + if ($process -and !$process.HasExited) { + $process.Kill() + $process.WaitForExit() + } + if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) } +} From 24fbf72d60fd88da25b77733c69f43c3f1564829 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 14:47:33 +0200 Subject: [PATCH 12/61] Add Sunburst and indexed NTFS volume traversal Refs #96 --- FILES-UI.md | 7 ++ resources/files.rc | 3 + src/files_main.cpp | 48 ++++----- src/files_ntfs_space.inl | 198 +++++++++++++++++++++++++++++++++++ src/files_space_analyzer.inl | 117 ++++++++++++++++----- src/files_space_map.inl | 84 +++++++++++---- src/files_space_sunburst.inl | 149 ++++++++++++++++++++++++++ src/files_win32_directory.h | 42 ++++++++ 8 files changed, 574 insertions(+), 74 deletions(-) create mode 100644 src/files_ntfs_space.inl create mode 100644 src/files_space_sunburst.inl create mode 100644 src/files_win32_directory.h diff --git a/FILES-UI.md b/FILES-UI.md index fdd341d..4808cc8 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -470,6 +470,13 @@ Warning і початковий фокус на No. пропорційними до їхнього логічного розміру. Дрібні елементи доступні в дереві. Клік по плитці відкриває точний елемент у сусідній панелі. Стрілки переводять фокус між плитками, Enter відкриває плитку у фокусі. +- Sunburst показує до трьох рівнів вкладеності секторами за логічним + розміром. Клік по сектору та Enter у відповідному рядку списку ведуть + до одного елемента. Обраний рядок підсвічує відповідний сектор. +- Під час аналізу всього NTFS-тому Files використовує індекс MFT за + наявності доступу Windows. Звичайний обхід працює без такого доступу. + Обидва режими перераховують доступні записи каталогів, ураховують + жорсткі посилання за їхніми іменами та позначають недоступні гілки. - View відкриває вибраний файл у спільному переглядачі Files. Show in other panel відкриває вибрану папку або ставить курсор на файл у сусідній панелі. Команди роботи з файлами доступні там. Якщо фільтр приховує diff --git a/resources/files.rc b/resources/files.rc index 6145898..3141a9a 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -442,6 +442,9 @@ BEGIN LTEXT "", 495, 16, 28, 353, 13, SS_ENDELLIPSIS CONTROL "Vo&lume", 496, "Button", BS_OWNERDRAW | WS_TABSTOP, 16, 43, 64, 16 CONTROL "Tree&map", 497, "Button", BS_OWNERDRAW | WS_TABSTOP, 84, 43, 64, 16 + CONTROL "S&unburst", 499, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 43, 64, 16 + LTEXT "Sunburst items", 501, 171, 43, 201, 16, NOT WS_VISIBLE + LISTBOX 500, 171, 60, 201, 105, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | NOT WS_VISIBLE CONTROL "", 498, "Static", SS_OWNERDRAW | SS_NOTIFY | WS_TABSTOP | NOT WS_VISIBLE, 16, 60, 353, 105 CONTROL "", 489, "SysTreeView32", WS_TABSTOP | WS_BORDER | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, 16, 32, 353, 131 LTEXT "", 490, 16, 167, 353, 14, SS_ENDELLIPSIS diff --git a/src/files_main.cpp b/src/files_main.cpp index a83ca53..7c909f3 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -1,9 +1,12 @@ #include #include #include +#include #include #include #include +#include +#include #include #include #include @@ -22,6 +25,7 @@ #include #include #include "files_terminal.h" +#include "files_win32_directory.h" #include "files_command_completion.h" #include "files_text_window.h" #include "files_menu_navigation.h" @@ -48,7 +52,12 @@ using ks::lan::fileRequest; using ks::lan::filePath; using ks::lan::checkFileReply; -struct FileInfo { DWORD attributes; uint64_t size, modified; }; +struct FileInfo +{ + DWORD attributes; + uint64_t size, modified; + std::optional allocated{}; +}; FileInfo fileInfo(const Json &row) { return {row.at("attributes"),row.at("size"),row.at("modified")}; @@ -164,32 +173,17 @@ DWORD listElevatedFolder(const fs::path &directory, const std::wstring &pipeName FILE_FLAG_BACKUP_SEMANTICS,nullptr)}; if(folder.value==INVALID_HANDLE_VALUE) return GetLastError(); - alignas(FILE_ID_BOTH_DIR_INFO) unsigned char buffer[16384]; - while(GetFileInformationByHandleEx(folder.value,FileIdBothDirectoryInfo,buffer,sizeof(buffer))) - { - auto entry=reinterpret_cast(buffer); - for(;;) - { - std::wstring_view name(entry->FileName,entry->FileNameLength/sizeof(wchar_t)); - if(name!=L"." && name!=L"..") - { - const FolderEntryMetadata metadata{entry->FileAttributes, - static_cast(entry->EndOfFile.QuadPart), - static_cast(entry->LastWriteTime.QuadPart)}; - std::wstring row(sizeof(metadata)/sizeof(wchar_t),L'\0'); - memcpy(row.data(),&metadata,sizeof(metadata)); - row.append(name); - DWORD written{}; - if(!WriteFile(pipe.value,row.data(),static_cast(row.size()*sizeof(wchar_t)),&written,nullptr)) - return GetLastError(); - } - if(!entry->NextEntryOffset) break; - entry=reinterpret_cast( - reinterpret_cast(entry)+entry->NextEntryOffset); - } - } - const auto error=GetLastError(); - return error==ERROR_NO_MORE_FILES?ERROR_SUCCESS:error; + return ks::files::visitDirectoryRecords(folder.value,[&](const FILE_ID_BOTH_DIR_INFO &entry,std::wstring_view name) { + const FolderEntryMetadata metadata{entry.FileAttributes,static_cast(entry.EndOfFile.QuadPart), + static_cast(entry.LastWriteTime.QuadPart)}; + std::wstring row(sizeof(metadata)/sizeof(wchar_t),L'\0'); + memcpy(row.data(),&metadata,sizeof(metadata)); + row.append(name); + DWORD written{}; + if(!WriteFile(pipe.value,row.data(),static_cast(row.size()*sizeof(wchar_t)),&written,nullptr)) + return GetLastError(); + return static_cast(ERROR_SUCCESS); + }); } struct ElevatedHelper diff --git a/src/files_ntfs_space.inl b/src/files_ntfs_space.inl new file mode 100644 index 0000000..b19df99 --- /dev/null +++ b/src/files_ntfs_space.inl @@ -0,0 +1,198 @@ +constexpr DWORD spaceFileShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE; + +bool sameVolumeRoot(const fs::path &directory,const fs::path &root) +{ + if(root.empty()) return false; + const auto comparable=[](const fs::path &path) { + auto value=std::wstring_view(path.native()); + if(!value.empty() && (value.back()==L'\\' || value.back()==L'/')) value.remove_suffix(1); + return value; + }; + const auto left=comparable(directory),right=comparable(root); + return !left.empty() && !right.empty() && CompareStringOrdinal(left.data(),static_cast(left.size()), + right.data(),static_cast(right.size()),TRUE)==CSTR_EQUAL; +} + +fs::path spaceScanPath(fs::path path) +{ + if(!path.has_filename() && path.has_relative_path()) return path.parent_path(); + return path; +} + +bool isNtfsVolume(const fs::path &root) +{ + wchar_t filesystem[16]{}; + return GetVolumeInformationW(root.c_str(),nullptr,0,nullptr,nullptr,nullptr,filesystem, + static_cast(std::size(filesystem))) && std::wstring_view(filesystem)==L"NTFS"; +} + +using NtfsDirectoryIds=std::set; + +bool appendMftDirectories(std::span records,NtfsDirectoryIds &directories) +{ + struct UsnRow + { + DWORD length; + WORD major,minor; + DWORDLONG id,parent; + USN usn; + LARGE_INTEGER time; + DWORD reason,source,security,attributes; + WORD nameLength,nameOffset; + }; + constexpr auto header=offsetof(UsnRow,nameOffset)+sizeof(WORD); + static_assert(header==60); + while(!records.empty()) + { + if(records.size()records.size()) return false; + if((row.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(row.attributes&FILE_ATTRIBUTE_REPARSE_POINT)) + directories.insert(row.id); + records=records.subspan(row.length); + } + return true; +} + +bool isExpectedNtfsDirectory(HANDLE handle,const fs::path &directory) +{ + std::wstring name(MAX_PATH,L'\0'); + const auto getName=[&] { + return GetFinalPathNameByHandleW(handle,name.data(),static_cast(name.size()), + FILE_NAME_OPENED|VOLUME_NAME_DOS); + }; + auto length=getName(); + if(length>=name.size()) + { + name.resize(length+1); + length=getName(); + } + if(!length || length>=name.size()) return false; + name.resize(length); + constexpr std::wstring_view devicePrefix=LR"(\\?\)"; + const auto &expected=directory.native(); + std::wstring_view actual(name); + if(actual.starts_with(devicePrefix) && !std::wstring_view(expected).starts_with(devicePrefix)) + actual.remove_prefix(devicePrefix.size()); + return CompareStringOrdinal(actual.data(),static_cast(actual.size()),expected.data(), + static_cast(expected.size()),TRUE)==CSTR_EQUAL; +} + +bool readMftDirectoryIds(const fs::path &root,NtfsDirectoryIds &directories,std::stop_token stop) +{ + wchar_t name[64]{}; + if(!GetVolumeNameForVolumeMountPointW(root.c_str(),name,static_cast(std::size(name)))) return false; + const auto length=wcslen(name); + if(!length || name[length-1]!=L'\\') return false; + name[length-1]=L'\0'; + const Handle volume{CreateFileW(name,GENERIC_READ,spaceFileShare,nullptr,OPEN_EXISTING,0,nullptr)}; + if(volume.value==INVALID_HANDLE_VALUE) return false; + struct Enumeration {DWORDLONG first; USN low,high;}; + static_assert(sizeof(Enumeration)==24); + Enumeration request{0,0,std::numeric_limits::max()}; + auto buffer=std::vector(512*1024); + while(!stop.stop_requested()) + { + DWORD bytes{}; + if(!DeviceIoControl(volume.value,FSCTL_ENUM_USN_DATA,&request,sizeof(request),buffer.data(), + static_cast(buffer.size()),&bytes,nullptr)) + return GetLastError()==ERROR_HANDLE_EOF && !directories.empty(); + DWORDLONG next{}; + if(bytesbuffer.size()) return false; + memcpy(&next,buffer.data(),sizeof(next)); + if(next<=request.first) return false; + if(!appendMftDirectories(std::span(buffer).subspan(sizeof(next),bytes-sizeof(next)), + directories)) return false; + request.first=next; + } + return false; +} + +class NtfsSpaceWalk +{ +public: + NtfsSpaceWalk(const fs::path &root,const fs::path &mount,std::stop_token stop) : root(root), + volumeHint{CreateFileW(root.c_str(),FILE_READ_ATTRIBUTES,spaceFileShare,nullptr,OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS,nullptr)} + { + if(volumeHint.value!=INVALID_HANDLE_VALUE) + { + try {indexed=readMftDirectoryIds(mount,mft,stop);} + catch(const std::exception &) {} + } + if(!indexed) mft.clear(); + } + + bool usedMft() const { return usedIndex; } + + bool list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop,FilesConnection &fallback) + { + const bool atRoot=directory==root; + const auto known=byPath.extract(directory); + constexpr DWORD openFlags=FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT; + Handle handle{INVALID_HANDLE_VALUE}; + if(known && mft.contains(known.mapped())) + { + FILE_ID_DESCRIPTOR id{}; + id.dwSize=sizeof(id); + id.Type=FileIdType; + id.FileId.QuadPart=static_cast(known.mapped()); + handle.value=OpenFileById(volumeHint.value,&id,FILE_LIST_DIRECTORY|FILE_READ_ATTRIBUTES, + spaceFileShare,nullptr,openFlags); + if(handle.value!=INVALID_HANDLE_VALUE) + { + if(isExpectedNtfsDirectory(handle.value,directory)) usedIndex=true; + else + { + CloseHandle(handle.value); + handle.value=INVALID_HANDLE_VALUE; + } + } + } + if(handle.value==INVALID_HANDLE_VALUE) + handle.value=CreateFileW(directory.c_str(),FILE_LIST_DIRECTORY|FILE_READ_ATTRIBUTES, + spaceFileShare,nullptr,OPEN_EXISTING,atRoot?FILE_FLAG_BACKUP_SEMANTICS:openFlags,nullptr); + if(handle.value==INVALID_HANDLE_VALUE) return false; + + FILE_ATTRIBUTE_TAG_INFO tag{}; + if(!GetFileInformationByHandleEx(handle.value,FileAttributeTagInfo,&tag,sizeof(tag)) || + !(tag.FileAttributes&FILE_ATTRIBUTE_DIRECTORY) || + (!atRoot && (tag.FileAttributes&FILE_ATTRIBUTE_REPARSE_POINT))) return false; + + bool emitted=false; + const auto status=ks::files::visitDirectoryRecords(handle.value,[&](const FILE_ID_BOTH_DIR_INFO &row, + std::wstring_view name) -> DWORD + { + if(stop.stop_requested()) return ERROR_CANCELLED; + const auto path=directory/name; + const auto attributes=row.FileAttributes; + const auto directoryEntry=(attributes&FILE_ATTRIBUTE_DIRECTORY)!=0; + if(directoryEntry && !(attributes&FILE_ATTRIBUTE_REPARSE_POINT) && indexed) + { + const auto id=static_cast(row.FileId.QuadPart); + if(mft.contains(id)) byPath.try_emplace(path,id); + } + FileInfo entry{attributes,static_cast(row.EndOfFile.QuadPart), + static_cast(row.LastWriteTime.QuadPart)}; + if(!(attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT| + FILE_ATTRIBUTE_COMPRESSED|FILE_ATTRIBUTE_SPARSE_FILE)) && row.AllocationSize.QuadPart>=0) + entry.allocated=static_cast(row.AllocationSize.QuadPart); + emitted=true; + return visit(path,entry)?ERROR_SUCCESS:ERROR_CANCELLED; + }); + if(!emitted && (status==ERROR_NOT_SUPPORTED || status==ERROR_INVALID_PARAMETER || status==ERROR_INVALID_FUNCTION)) + { + if(atRoot) return !stop.stop_requested() && listFiles(fallback,directory,visit); + return listMeasuredDirectory(fallback,directory,visit,stop); + } + return status==ERROR_SUCCESS; + } + +private: + fs::path root; + Handle volumeHint; + NtfsDirectoryIds mft; + std::map byPath; + bool indexed{}, usedIndex{}; +}; diff --git a/src/files_space_analyzer.inl b/src/files_space_analyzer.inl index 0605fc9..219e818 100644 --- a/src/files_space_analyzer.inl +++ b/src/files_space_analyzer.inl @@ -1,6 +1,7 @@ constexpr int spacePath=488,spaceTree=489,spaceStatus=490,spaceFooter=491; constexpr int spaceStop=492,spaceRescan=493,spaceView=494; constexpr int spaceCapacity=495,spaceScope=496,spaceMapButton=497,spaceMap=498; +constexpr int spaceSunburstButton=499,spaceSunburstList=500,spaceSunburstLabel=501; constexpr UINT_PTR spaceUpdateTimer=1; constexpr UINT_PTR spaceVolumeTimer=2; constexpr size_t spaceBatchSize=256; @@ -74,6 +75,17 @@ struct SpaceTile size_t node; }; +#include "files_ntfs_space.inl" + +struct SpaceSector +{ + size_t node; + unsigned ring; + double start,end; +}; + +enum class SpaceDisplay { tree, treemap, sunburst }; + struct SpaceEvent { fs::path path; @@ -87,13 +99,13 @@ struct SpaceRun std::mutex mutex; std::deque> pending; FolderSize result; - bool finished{}, stopped{}; + bool finished{}, stopped{}, indexed{}; }; -std::shared_ptr startSpaceRun(const fs::path &root,bool volume) +std::shared_ptr startSpaceRun(const fs::path &root,const fs::path &mount) { auto run=std::make_shared(); - std::thread([run,root,volume] { + std::thread([run,root,mount] { std::vector batch; auto lastUpdate=GetTickCount64(); const auto publish=[&] { @@ -108,13 +120,28 @@ std::shared_ptr startSpaceRun(const fs::path &root,bool volume) try { FilesConnection host(nullptr); + const bool volume=!mount.empty(); + std::optional ntfs; + if(volume && isNtfsVolume(mount)) ntfs.emplace(root,mount,stop); + bool indexReported=false; total=measureFolder(root,stop,[&](const fs::path &directory,const FileVisitor &visit) { + if(ntfs) + { + const auto result=ntfs->list(directory,visit,stop,host); + if(!indexReported && ntfs->usedMft()) + { + std::lock_guard lock(run->mutex); + run->indexed=indexReported=true; + } + return result; + } if(volume && directory==root) return !stop.stop_requested() && listFiles(host,directory,visit); return listMeasuredDirectory(host,directory,visit,stop); },[&](const fs::path &path,const FileInfo *info) { const auto allocate=info && !(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)); - batch.push_back({path,info?std::optional(*info):std::nullopt, - allocate?allocatedFileBytes(path,info->attributes):std::nullopt}); + const auto allocation=allocate?(info->allocated?info->allocated:allocatedFileBytes(path,info->attributes)): + std::nullopt; + batch.push_back({path,info?std::optional(*info):std::nullopt,allocation}); if(batch.size()>=spaceBatchSize || GetTickCount64()-lastUpdate>=80) publish(); }); publish(); @@ -144,12 +171,14 @@ struct SpaceAnalyzer fs::path folder, root, selected; SpaceVolume volume; std::future pendingVolume; - bool selectedFolder{}, volumeScope{}, mapVisible{}; + bool selectedFolder{}, volumeScope{}; + SpaceDisplay display{SpaceDisplay::tree}; std::shared_ptr run; std::vector nodes; std::map directories; size_t files{}, mapFolder{}, selectedTile{}; std::vector tiles; + std::vector sectors; ULONGLONG lastMapUpdate{}; bool scanning{}, hasResults{}; }; @@ -171,7 +200,7 @@ void layoutSpaceAnalyzer(HWND dialog) top+=textHeight+dialogRowGap(); const auto buttonHeight=textHeight; auto x=inset; - for(const auto id:{spaceScope,spaceMapButton}) + for(const auto id:{spaceScope,spaceMapButton,spaceSunburstButton}) { const auto button=GetDlgItem(dialog,id); const auto width=std::max(12L*cellWidth,farDialogButtonWidth(button)); @@ -180,7 +209,19 @@ void layoutSpaceAnalyzer(HWND dialog) } top+=buttonHeight+dialogRowGap(); place(spaceTree,top,9*textHeight); - place(spaceMap,top,9*textHeight); + const auto state=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(state && state->display==SpaceDisplay::sunburst) + { + const auto graphWidth=width*3/5; + const auto gap=dialogColumnGap(); + SetWindowPos(GetDlgItem(dialog,spaceSunburstLabel),nullptr,inset+graphWidth,top-textHeight-dialogRowGap(), + width-graphWidth,textHeight,SWP_NOZORDER|SWP_NOACTIVATE); + SetWindowPos(GetDlgItem(dialog,spaceMap),nullptr,inset,top,graphWidth-gap,9*textHeight, + SWP_NOZORDER|SWP_NOACTIVATE); + SetWindowPos(GetDlgItem(dialog,spaceSunburstList),nullptr,inset+graphWidth,top,width-graphWidth, + 9*textHeight,SWP_NOZORDER|SWP_NOACTIVATE); + } + else place(spaceMap,top,9*textHeight); top+=9*textHeight+dialogRowGap(); place(spaceStatus,top,textHeight); place(spaceFooter,top+textHeight+dialogRowGap(),1); @@ -302,12 +343,13 @@ void updateSpaceTree(HWND dialog,SpaceAnalyzer &state) { const auto tree=GetDlgItem(dialog,spaceTree); const auto budget=GetTickCount64()+15; - bool finished=false,stopped=false,changed=false; + bool finished=false,stopped=false,changed=false,indexed=false; do { std::vector batch; { std::lock_guard lock(state.run->mutex); + indexed=state.run->indexed; if(!state.run->pending.empty()) { batch=std::move(state.run->pending.front()); @@ -327,8 +369,8 @@ void updateSpaceTree(HWND dialog,SpaceAnalyzer &state) } while(GetTickCount64()=200))) - layoutSpaceMap(GetDlgItem(dialog,spaceMap),state); + if(state.display!=SpaceDisplay::tree && (finished || (changed && GetTickCount64()-state.lastMapUpdate>=200))) + refreshSpaceChart(GetDlgItem(dialog,spaceMap),state); if(changed || finished) InvalidateRect(tree,nullptr,FALSE); const bool stopping=state.run->stop.stop_requested(); @@ -336,15 +378,17 @@ void updateSpaceTree(HWND dialog,SpaceAnalyzer &state) stopping?L"Stopping…":L"Scanning…"; const auto &allocation=state.nodes[0].allocated; auto label=std::wstring(status)+L" · "+std::to_wstring(state.files)+L" files"; + if(indexed) label+=L" · NTFS index"; if(allocation.unavailable || allocation.known.partial) label+=L" · on-disk sizes partial"; - else label+=state.mapVisible?L" · logical size by area":L" · logical shares of parent"; + else label+=state.display==SpaceDisplay::treemap?L" · logical size by area": + state.display==SpaceDisplay::sunburst?L" · logical size by angle":L" · logical shares of parent"; SetDlgItemTextW(dialog,spaceStatus,label.c_str()); if(finished) { EnableWindow(GetDlgItem(dialog,spaceStop),FALSE); EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE); EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() && - !sameLocalFolder(state.volume.root,state.folder)); + !sameVolumeRoot(state.folder,state.volume.root)); KillTimer(dialog,spaceUpdateTimer); } } @@ -360,20 +404,21 @@ void resetSpaceResults(HWND dialog,SpaceAnalyzer &state,bool scanning) state.files=0; state.mapFolder=0; state.tiles.clear(); + state.sectors.clear(); state.selectedTile=0; state.scanning=scanning; state.hasResults=scanning; TreeView_SelectItem(tree,insertSpaceNode(tree,state,0)); - if(state.mapVisible) layoutSpaceMap(GetDlgItem(dialog,spaceMap),state); + if(state.display!=SpaceDisplay::tree) refreshSpaceChart(GetDlgItem(dialog,spaceMap),state); EnableWindow(GetDlgItem(dialog,spaceView),FALSE); - EnableWindow(GetDlgItem(dialog,IDOK),!state.mapVisible); + EnableWindow(GetDlgItem(dialog,IDOK),state.display==SpaceDisplay::tree); } void prepareSpaceScope(HWND dialog,SpaceAnalyzer &state) { state.run.reset(); const auto scope=state.volumeScope?state.volume.root:state.folder; - state.root=scope; + state.root=spaceScanPath(scope); SetDlgItemTextW(dialog,spacePath,scope.c_str()); SetDlgItemTextW(dialog,spaceScope,state.volumeScope?L"&Folder":L"Vo&lume"); SetDlgItemTextW(dialog,spaceRescan,L"St&art"); @@ -399,7 +444,7 @@ void updateSpaceVolume(HWND dialog,SpaceAnalyzer &state) } SetDlgItemTextW(dialog,spaceCapacity,caption.c_str()); EnableWindow(GetDlgItem(dialog,spaceScope), - !state.volume.root.empty() && !sameLocalFolder(state.volume.root,state.folder)); + !state.volume.root.empty() && !sameVolumeRoot(state.folder,state.volume.root)); prepareSpaceScope(dialog,state); } @@ -411,7 +456,8 @@ void rescanSpace(HWND dialog,SpaceAnalyzer &state) EnableWindow(GetDlgItem(dialog,spaceScope),FALSE); try { - state.run=startSpaceRun(state.root,state.volumeScope); + const bool volume=state.volumeScope || sameVolumeRoot(state.root,state.volume.root); + state.run=startSpaceRun(state.root,volume?state.volume.root:fs::path{}); EnableWindow(GetDlgItem(dialog,spaceStop),TRUE); SetTimer(dialog,spaceUpdateTimer,60,nullptr); updateSpaceTree(dialog,state); @@ -422,7 +468,7 @@ void rescanSpace(HWND dialog,SpaceAnalyzer &state) EnableWindow(GetDlgItem(dialog,spaceRescan),TRUE); state.scanning=false; EnableWindow(GetDlgItem(dialog,spaceScope),!state.volume.root.empty() && - !sameLocalFolder(state.volume.root,state.folder)); + !sameVolumeRoot(state.folder,state.volume.root)); SetDlgItemTextW(dialog,spaceStatus,L"Could not start space analysis."); } } @@ -438,6 +484,7 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l SetDlgItemTextW(dialog,spaceCapacity,L"Reading volume capacity…"); const auto tree=GetDlgItem(dialog,spaceTree); SetWindowSubclass(GetDlgItem(dialog,spaceMap),spaceMapInput,1,reinterpret_cast(&state)); + SetWindowSubclass(GetDlgItem(dialog,spaceSunburstList),spaceSunburstListKeys,1,reinterpret_cast(&state)); TreeView_SetBkColor(tree,RGB(255,255,255)); TreeView_SetTextColor(tree,RGB(0,0,0)); layoutSpaceAnalyzer(dialog); @@ -469,7 +516,9 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l const auto tree=GetDlgItem(dialog,spaceTree); if(message==WM_DRAWITEM && wp==spaceMap) { - paintSpaceMap(*reinterpret_cast(lp),*state); + const auto &paint=*reinterpret_cast(lp); + if(state->display==SpaceDisplay::sunburst) paintSunburst(paint,*state); + else paintSpaceMap(paint,*state); return TRUE; } if(message==WM_TIMER && wp==spaceVolumeTimer) @@ -511,8 +560,11 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l if(notification->code==TVN_SELCHANGEDW) { const auto selected=selectedSpaceNode(tree,*state); - EnableWindow(GetDlgItem(dialog,spaceView),!state->mapVisible && selected && !state->nodes[*selected].folder); - EnableWindow(GetDlgItem(dialog,IDOK),!state->mapVisible && selected.has_value()); + if(state->display==SpaceDisplay::tree) + { + EnableWindow(GetDlgItem(dialog,spaceView),selected && !state->nodes[*selected].folder); + EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value()); + } } } } @@ -532,12 +584,21 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l prepareSpaceScope(dialog,*state); return TRUE; } - if(command==spaceMapButton) + if(command==spaceMapButton || command==spaceSunburstButton) { - showSpaceMap(dialog,*state,!state->mapVisible); + const auto chart=command==spaceMapButton?SpaceDisplay::treemap:SpaceDisplay::sunburst; + setSpaceDisplay(dialog,*state,state->display==chart?SpaceDisplay::tree:chart); if(state->run) updateSpaceTree(dialog,*state); return TRUE; } + if(command==spaceSunburstList && state->display==SpaceDisplay::sunburst) + { + updateSunburstSelection(dialog,*state); + if(HIWORD(wp)==LBN_DBLCLK) + if(const auto selected=sunburstSelection(dialog,*state)) + finishSpaceSelection(dialog,*state,*selected,IDOK); + return TRUE; + } if(command==spaceRescan && IsWindowEnabled(GetDlgItem(dialog,spaceRescan))) { rescanSpace(dialog,*state); @@ -545,9 +606,9 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l } if(command==IDOK || command==spaceView) { - if(!state->mapVisible) - if(const auto selected=selectedSpaceNode(tree,*state)) - finishSpaceSelection(dialog,*state,*selected,command); + const auto selected=state->display==SpaceDisplay::sunburst?sunburstSelection(dialog,*state): + state->display==SpaceDisplay::tree?selectedSpaceNode(tree,*state):std::nullopt; + if(selected) finishSpaceSelection(dialog,*state,*selected,command); return TRUE; } } @@ -573,7 +634,7 @@ void openSpaceAnalyzer(HWND owner,Panel &panel) return; } const auto origin=static_cast(&panel-panels); - SpaceAnalyzer state{.folder=panel.directory,.root=panel.directory}; + SpaceAnalyzer state{.folder=spaceScanPath(panel.directory),.root=spaceScanPath(panel.directory)}; const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(118),owner, spaceAnalyzerDialog,reinterpret_cast(&state)); if(answer==spaceView) diff --git a/src/files_space_map.inl b/src/files_space_map.inl index 571670a..2a1d267 100644 --- a/src/files_space_map.inl +++ b/src/files_space_map.inl @@ -72,6 +72,18 @@ void layoutSpaceMap(HWND map,SpaceAnalyzer &state) InvalidateRect(map,nullptr,FALSE); } +constexpr COLORREF spaceChartColors[]{RGB(158,203,218),RGB(167,205,172),RGB(230,198,142), + RGB(197,179,211),RGB(226,178,173),RGB(177,190,225)}; + +void paintEmptySpaceChart(const DRAWITEMSTRUCT &paint) +{ + auto bounds=paint.rcItem; + SelectObject(paint.hDC,mono); + SetBkMode(paint.hDC,TRANSPARENT); + SetTextColor(paint.hDC,RGB(15,27,35)); + DrawTextW(paint.hDC,L"No measured space to display",-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE); +} + void paintSpaceMap(const DRAWITEMSTRUCT &paint,const SpaceAnalyzer &state) { FillRect(paint.hDC,&paint.rcItem,GetSysColorBrush(COLOR_WINDOW)); @@ -80,12 +92,9 @@ void paintSpaceMap(const DRAWITEMSTRUCT &paint,const SpaceAnalyzer &state) SetTextColor(paint.hDC,RGB(15,27,35)); if(state.tiles.empty()) { - auto bounds=paint.rcItem; - DrawTextW(paint.hDC,L"No measured space to display",-1,&bounds,DT_CENTER|DT_VCENTER|DT_SINGLELINE); + paintEmptySpaceChart(paint); return; } - constexpr COLORREF surfaces[]{RGB(158,203,218),RGB(167,205,172),RGB(230,198,142), - RGB(197,179,211),RGB(226,178,173),RGB(177,190,225)}; const auto brush=static_cast(GetStockObject(DC_BRUSH)); const auto focused=GetFocus()==paint.hwndItem; for(size_t index=0;index(payload); + if(message==WM_GETDLGCODE && lp && wp==VK_RETURN) + return DefSubclassProc(list,message,wp,lp)|DLGC_WANTMESSAGE; + if(message==WM_KEYDOWN && wp==VK_RETURN) + { + const auto dialog=GetParent(list); + if(const auto selected=sunburstSelection(dialog,state)) finishSpaceSelection(dialog,state,*selected,IDOK); + return 0; + } + return DefSubclassProc(list,message,wp,lp); +} + LRESULT CALLBACK spaceMapInput(HWND map,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR payload) { auto &state=*reinterpret_cast(payload); - if(message==WM_SIZE && state.mapVisible) layoutSpaceMap(map,state); + if(message==WM_SIZE && state.display!=SpaceDisplay::tree) refreshSpaceChart(map,state); if(message==WM_SETFOCUS || message==WM_KILLFOCUS) InvalidateRect(map,nullptr,FALSE); if(message==WM_LBUTTONDOWN) { @@ -137,6 +168,12 @@ LRESULT CALLBACK spaceMapInput(HWND map,UINT message,WPARAM wp,LPARAM lp,UINT_PT if(message==WM_LBUTTONUP) { const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; + if(state.display==SpaceDisplay::sunburst) + { + if(const auto hit=hitSunburst(map,state,point)) + finishSpaceSelection(GetParent(map),state,state.sectors[*hit].node,IDOK); + return 0; + } for(const auto &tile:state.tiles) if(PtInRect(&tile.box,point)) { @@ -150,7 +187,7 @@ LRESULT CALLBACK spaceMapInput(HWND map,UINT message,WPARAM wp,LPARAM lp,UINT_PT const auto *key=reinterpret_cast(lp); return DLGC_WANTARROWS|(key && key->message==WM_KEYDOWN && wp==VK_RETURN?DLGC_WANTMESSAGE:0); } - if(message==WM_KEYDOWN && !state.tiles.empty()) + if(message==WM_KEYDOWN && state.display==SpaceDisplay::treemap && !state.tiles.empty()) { if(wp==VK_RETURN) { @@ -169,22 +206,31 @@ LRESULT CALLBACK spaceMapInput(HWND map,UINT message,WPARAM wp,LPARAM lp,UINT_PT return DefSubclassProc(map,message,wp,lp); } -void showSpaceMap(HWND dialog,SpaceAnalyzer &state,bool show) +void setSpaceDisplay(HWND dialog,SpaceAnalyzer &state,SpaceDisplay display) { const auto tree=GetDlgItem(dialog,spaceTree), map=GetDlgItem(dialog,spaceMap); - state.mapVisible=show; - if(show) + const auto list=GetDlgItem(dialog,spaceSunburstList); + const bool showTree=display==SpaceDisplay::tree, showSunburst=display==SpaceDisplay::sunburst; + const auto selection=selectedSpaceNode(tree,state); + if(state.display==SpaceDisplay::tree && !showTree) { - const auto index=selectedSpaceNode(tree,state).value_or(0); + const auto index=selection.value_or(0); const auto &node=state.nodes[index]; state.mapFolder=node.folder && !node.link?index:node.parent; - layoutSpaceMap(map,state); } - ShowWindow(tree,show?SW_HIDE:SW_SHOW); - ShowWindow(map,show?SW_SHOW:SW_HIDE); - SetDlgItemTextW(dialog,spaceMapButton,show?L"Tr&ee":L"Tree&map"); - const auto selection=selectedSpaceNode(tree,state); - EnableWindow(GetDlgItem(dialog,spaceView),!show && selection && !state.nodes[*selection].folder); - EnableWindow(GetDlgItem(dialog,IDOK),!show && selection.has_value()); - SetFocus(show?map:tree); + state.display=display; + SetDlgItemTextW(dialog,spaceMapButton,display==SpaceDisplay::treemap?L"Tr&ee":L"Tree&map"); + SetDlgItemTextW(dialog,spaceSunburstButton,showSunburst?L"Tr&ee":L"S&unburst"); + layoutSpaceAnalyzer(dialog); + ShowWindow(tree,showTree?SW_SHOW:SW_HIDE); + ShowWindow(map,showTree?SW_HIDE:SW_SHOW); + ShowWindow(GetDlgItem(dialog,spaceSunburstLabel),showSunburst?SW_SHOW:SW_HIDE); + ShowWindow(list,showSunburst?SW_SHOW:SW_HIDE); + if(!showSunburst) + { + EnableWindow(GetDlgItem(dialog,spaceView),showTree && selection && !state.nodes[*selection].folder); + EnableWindow(GetDlgItem(dialog,IDOK),showTree && selection.has_value()); + } + if(!showTree) refreshSpaceChart(map,state); + SetFocus(showTree?tree:showSunburst?list:map); } diff --git a/src/files_space_sunburst.inl b/src/files_space_sunburst.inl new file mode 100644 index 0000000..73ee201 --- /dev/null +++ b/src/files_space_sunburst.inl @@ -0,0 +1,149 @@ +constexpr double fullCircle=2*std::numbers::pi_v; +constexpr unsigned sunburstRings=3; + +double sunburstRingWidth(const RECT &bounds) +{ + return std::max(0L,std::min(bounds.right-bounds.left,bounds.bottom-bounds.top)-4)/ + (2.0*(sunburstRings+0.5)); +} + +void addSunburstRing(SpaceAnalyzer &state,size_t folder,unsigned ring,double start,double end) +{ + if(ring>=sunburstRings || end-start<0.02) return; + const auto &parent=state.nodes[folder]; + double total=0; + for(auto index:parent.children) total+=static_cast(state.nodes[index].size.bytes); + if(total<=0) return; + const auto span=end-start; + auto cursor=start; + for(auto index:parent.children) + { + const auto &item=state.nodes[index]; + if(!item.size.bytes) continue; + const auto next=std::min(end,cursor+span*static_cast(item.size.bytes)/total); + if(next-cursor>=0.02) + { + state.sectors.push_back({index,ring,cursor,next}); + if(item.folder) addSunburstRing(state,index,ring+1,cursor,next); + } + cursor=next; + } +} + +std::optional sunburstSelectedSector(HWND dialog,const SpaceAnalyzer &state) +{ + const auto row=SendDlgItemMessageW(dialog,spaceSunburstList,LB_GETCURSEL,0,0); + if(row==LB_ERR) return {}; + const auto sector=SendDlgItemMessageW(dialog,spaceSunburstList,LB_GETITEMDATA,row,0); + if(sector==LB_ERR || static_cast(sector)>=state.sectors.size()) return {}; + return static_cast(sector); +} + +std::optional sunburstSelection(HWND dialog,const SpaceAnalyzer &state) +{ + const auto sector=sunburstSelectedSector(dialog,state); + return sector?std::optional(state.sectors[*sector].node):std::nullopt; +} + +void updateSunburstSelection(HWND dialog,SpaceAnalyzer &state) +{ + state.selectedTile=sunburstSelectedSector(dialog,state).value_or(state.sectors.size()); + const auto selected=sunburstSelection(dialog,state); + EnableWindow(GetDlgItem(dialog,spaceView),selected && !state.nodes[*selected].folder); + EnableWindow(GetDlgItem(dialog,IDOK),selected.has_value()); + InvalidateRect(GetDlgItem(dialog,spaceMap),nullptr,FALSE); +} + +void layoutSunburst(HWND map,SpaceAnalyzer &state) +{ + const auto dialog=GetParent(map); + const auto list=GetDlgItem(dialog,spaceSunburstList); + const auto selected=sunburstSelection(dialog,state); + state.lastMapUpdate=GetTickCount64(); + state.sectors.clear(); + state.selectedTile=0; + if(state.mapFolder(line.c_str())); + if(row>=0) + { + SendMessageW(list,LB_SETITEMDATA,row,i); + if(selected==sector.node) selection=row; + longest=std::max(longest,line.size()); + } + } + SendMessageW(list,LB_SETHORIZONTALEXTENT,(longest+1)*cellWidth,0); + if(!state.sectors.empty()) SendMessageW(list,LB_SETCURSEL,selection,0); + SendMessageW(list,WM_SETREDRAW,TRUE,0); + InvalidateRect(list,nullptr,FALSE); + updateSunburstSelection(dialog,state); +} + +std::optional hitSunburst(HWND map,const SpaceAnalyzer &state,POINT point) +{ + RECT bounds{}; + GetClientRect(map,&bounds); + const auto width=sunburstRingWidth(bounds); + if(width<=0) return {}; + const auto x=point.x-(bounds.left+bounds.right)/2.0; + const auto y=point.y-(bounds.top+bounds.bottom)/2.0; + const auto radius=std::hypot(x,y)/width-0.5; + if(radius<0 || radius>=sunburstRings) return {}; + const auto ring=static_cast(radius); + auto angle=std::atan2(x,-y); + if(angle<0) angle+=fullCircle; + for(size_t i=0;i=sector.start && angle((sector.end-sector.start)*26),2,164); + const auto inner=(sector.ring+0.5)*width, outer=inner+width; + std::array points; + for(int segment=0;segment<=segments;++segment) + { + const auto angle=sector.start+(sector.end-sector.start)*segment/segments; + points[segment]=point(angle,outer); + points[2*segments+1-segment]=point(angle,inner); + } + SetDCPenColor(paint.hDC,i==state.selectedTile?RGB(35,48,62):RGB(255,255,255)); + SetDCBrushColor(paint.hDC,spaceChartColors[i%std::size(spaceChartColors)]); + Polygon(paint.hDC,points.data(),2*(segments+1)); + } + SelectObject(paint.hDC,oldPen); + SelectObject(paint.hDC,oldBrush); +} diff --git a/src/files_win32_directory.h b/src/files_win32_directory.h new file mode 100644 index 0000000..80f838a --- /dev/null +++ b/src/files_win32_directory.h @@ -0,0 +1,42 @@ +#pragma once + +#include +#include +#include +#include + +namespace ks::files +{ +template +DWORD visitDirectoryRecords(HANDLE directory,const Visitor &visit) +{ + alignas(FILE_ID_BOTH_DIR_INFO) std::array buffer; + constexpr auto header=offsetof(FILE_ID_BOTH_DIR_INFO,FileName); + while(GetFileInformationByHandleEx(directory,FileIdBothDirectoryInfo,buffer.data(), + static_cast(buffer.size()))) + { + for(size_t offset=0;;) + { + const auto remaining=buffer.size()-offset; + if(remaining(buffer.data()+offset); + const auto size=entry.NextEntryOffset?entry.NextEntryOffset:remaining; + if(size>remaining || size
size-header || + entry.FileNameLength%sizeof(wchar_t)) return ERROR_INVALID_DATA; + const std::wstring_view name(entry.FileName,entry.FileNameLength/sizeof(wchar_t)); + if(name.empty() || name.find_first_of(L"/\\:")!=name.npos || name.find(L'\0')!=name.npos) + return ERROR_INVALID_DATA; + if(name!=L"." && name!=L"..") + { + const auto result=visit(entry,name); + if(result!=ERROR_SUCCESS) return result; + } + if(!entry.NextEntryOffset) break; + if(size%alignof(FILE_ID_BOTH_DIR_INFO)) return ERROR_INVALID_DATA; + offset+=size; + } + } + const auto error=GetLastError(); + return error==ERROR_NO_MORE_FILES?ERROR_SUCCESS:error; +} +} From 4b252bd11100461e75e56dd6ea641a756d91a87c Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 15:02:32 +0200 Subject: [PATCH 13/61] Add lazy panel trees and background folder sizes Refs #97 --- FILES-UI.md | 15 +- src/files_main.cpp | 392 ++++++++++++++++++++++++----------- src/files_ntfs_space.inl | 6 - src/files_panel_order.inl | 4 +- src/files_panel_rows.inl | 116 +++++++++++ src/files_panel_tree.inl | 229 ++++++++++++++++++++ src/files_space_analyzer.inl | 4 +- 7 files changed, 636 insertions(+), 130 deletions(-) create mode 100644 src/files_panel_rows.inl create mode 100644 src/files_panel_tree.inl diff --git a/FILES-UI.md b/FILES-UI.md index 4808cc8..893a769 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -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–F12 зарезервовані для інших режимів панелей. Brief і Wide також доступні в меню Left/Right та Options. +- Ctrl+F1 вмикає Brief, Ctrl+F2 вмикає Wide для активної панелі. Ctrl+F3–F9 керують сортуванням і фільтром активної панелі. Ctrl+F10 перемикає List і Tree. Ctrl+F11 перемикає фоновий підрахунок розмірів папок. Brief і Wide також доступні в меню Left/Right та Options. ## Налаштування Files @@ -455,6 +455,19 @@ Warning і початковий фокус на No. переміщені та видалені файли зникають зі списку. Ctrl+R повторює пошук з тією самою маскою й видимістю прихованих файлів. +- **Left/Right → Tree view** або Ctrl+F10 перемикає вигляд відповідної + панелі незалежно від Brief і Wide. Enter, подвійний клік чи стрілка біля + папки розкриває або згортає гілку. Стрілки вправо й вліво працюють із + гілкою та її батьківською папкою. Вміст гілки читається у фоні під час + розкриття. Позначки згорнутих гілок залишаються доступними для F5, F6 і F8. + Якщо позначено папку та її вміст, команда обробляє їх одним деревом. + Повернення до List відкриває батьківську папку поточного елемента. +- **Background folder sizes** або Ctrl+F11 вмикає вимірювання видимих папок + у фоні для відповідної панелі. Під час оновлення попереднє число лишається + поруч із символом … . Знак + позначає частковий розмір. Error з’являється, + коли вимірювання недоступне. Якщо попереднє число є, позначка ! відрізняє + його від свіжого результату. + - **Commands → Space Analyzer** показує місткість і вільне місце за даними Windows перед скануванням. Volume вибирає корінь тому, Folder повертає поточну локальну папку, Start запускає фоновий аналіз тим самим обходом, diff --git a/src/files_main.cpp b/src/files_main.cpp index 7c909f3..53b418b 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -280,7 +280,7 @@ DWORD readElevatedFolder(const ElevatedHelper &session,const fs::path &directory struct FolderSize { uint64_t bytes{}; - bool partial{}; + bool partial{}, failed{}, previous{}; void add(uint64_t amount) { @@ -321,6 +321,7 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir const FolderMeasurementObserver &observe={}) { FolderSize size; + bool readable=false; std::vector pending{root}; while(!pending.empty() && !stop.stop_requested()) { @@ -332,6 +333,7 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir complete=listDirectory(directory,[&](const fs::path &path,const FileInfo &entry) { if(stop.stop_requested()) return false; + readable=true; if(observe) observe(path,&entry); if(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT) return true; if(entry.attributes&FILE_ATTRIBUTE_DIRECTORY) pending.push_back(path); @@ -340,6 +342,7 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir }); } catch(const std::exception &) {} + readable|=complete; if(!complete) { size.partial=true; @@ -347,6 +350,7 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir } } if(stop.stop_requested()) size.partial=true; + size.failed=size.partial && !readable && !stop.stop_requested(); return size; } @@ -355,6 +359,12 @@ constexpr auto schemeKey = L"Software\\KSwitcher\\Files"; #include "files_ftp.inl" +fs::path folderPathWithoutSeparator(fs::path path) +{ + if(!path.has_filename() && path.has_relative_path()) return path.parent_path(); + return path; +} + fs::path panelParentPath(const fs::path &directory,bool local) { if(!directory.has_relative_path()) return {}; @@ -421,7 +431,7 @@ enum class PanelSort { name, extension, size, modified }; struct PanelView { PanelSort sort{PanelSort::name}; - bool descending{}, foldersFirst{true}, showHidden{true}; + bool descending{}, foldersFirst{true}, showHidden{true}, tree{}, automaticSizes{}; std::wstring mask; fs::path revealedFile; }; @@ -502,6 +512,22 @@ struct Panel fs::path ftpInitialDirectory; std::vector ordered; }; + struct TreeBranch + { + std::vector ordered; + std::map metadata; + std::future> scan; + std::stop_source stop; + bool expanded{}, loaded{}, failed{}, needsScan{}; + }; + struct TreeView + { + fs::path root; + std::map branches; + std::set marks; + std::map depths; + } tree; + std::set listReturnMarks; std::optional scanRequest; std::future> scan; std::stop_source scanStop; @@ -761,13 +787,16 @@ void loadPanelView(int index) view.descending=(settings&4)!=0; view.foldersFirst=(settings&8)==0; view.showHidden=(settings&16)==0; + view.tree=(settings&32)!=0; + view.automaticSizes=(settings&64)!=0; } void savePanelView(int index) { const auto &view=panels[index].view; savePreference(panelViewKeys[index],static_cast(view.sort) | - (view.descending?4:0) | (view.foldersFirst?0:8) | (view.showHidden?0:16)); + (view.descending?4:0) | (view.foldersFirst?0:8) | (view.showHidden?0:16) | + (view.tree?32:0) | (view.automaticSizes?64:0)); } void setMode(int index, bool wide) @@ -1766,6 +1795,8 @@ void copyTerminalText(HWND owner) copyFilesText(owner,value,L"Could not copy terminal text."); } +#include "files_panel_rows.inl" + LRESULT currentPanelRow(const Panel &panel) { const auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0); @@ -1775,8 +1806,18 @@ LRESULT currentPanelRow(const Panel &panel) std::vector selectedPanelPaths(const Panel &panel) { std::vector paths; - for(size_t i=0;i directories; + visitPanelMarks(panel,[&](const fs::path &path,const FolderEntryMetadata &entry) { + paths.push_back(path); + if(treePanelActive(panel) && (entry.attributes&FILE_ATTRIBUTE_DIRECTORY)) directories.insert(path); + }); + if(!directories.empty()) + std::erase_if(paths,[&](const auto &path) { + for(auto parent=path.parent_path();parent!=panel.tree.root && parent!=parent.parent_path(); + parent=parent.parent_path()) + if(directories.contains(parent)) return true; + return false; + }); if(paths.empty()) { const auto row=currentPanelRow(panel); @@ -1853,7 +1894,7 @@ void startFileSearch(Panel &panel,Panel::FindOptions options); void refreshPanel(Panel &panel) { cancelFolderSizes(panel); - panel.folderSizes.clear(); + if(!panel.view.automaticSizes) panel.folderSizes.clear(); updateSelectionSummary(panel); if(panel.findOrigin) startFileSearch(panel,panel.findOrigin->options); else open(panel,panel.directory,false); @@ -2206,33 +2247,28 @@ void updateSelectionSummary(const Panel &panel) size_t marked=0,unmeasured=0; uint64_t total=0; bool partial=false; - if(!ftpProfileList(panel)) + visitPanelMarks(panel,[&](const fs::path &path,const FolderEntryMetadata &entry) { - for(size_t row=0;rowsecond.failed && !measured->second.previous)) { - const auto measured=panel.folderSizes.find(panel.rows[row]); - if(measured==panel.folderSizes.end()) - { - ++unmeasured; - continue; - } - bytes=measured->second.bytes; - partial|=measured->second.partial; + ++unmeasured; + return; } - else bytes=std::stoull(panel.sizes[row]); - if(bytes>UINT64_MAX-total) - { - total=UINT64_MAX; - partial=true; - } - else total+=bytes; + bytes=measured->second.bytes; + partial|=measured->second.partial; } - } + if(bytes>UINT64_MAX-total) + { + total=UINT64_MAX; + partial=true; + } + else total+=bytes; + }); std::wstring summary; if(marked) { @@ -2255,6 +2291,42 @@ std::optional localFileTime(uint64_t ticks) return {}; } +std::wstring folderMeasurementText(const Panel &panel,const fs::path &path,size_t columns=0) +{ + const bool waiting=panel.folderSizeWaiting.contains(path); + const auto measured=panel.folderSizes.find(path); + if(measured==panel.folderSizes.end()) + { + if(path==panel.folderSpinner) + { + constexpr const wchar_t *frames[]{L"|",L"/",L"-",L"\\"}; + return frames[(GetTickCount64()/folderSpinnerInterval)%std::size(frames)]; + } + return waiting?L"Queued":L""; + } + const auto &size=measured->second; + if(!columns) + { + if(size.failed) + { + auto label=std::wstring(L"size unavailable"); + if(size.previous) label+=L" (last known "+formatSize(size.bytes)+L")"; + if(waiting) label+=L" (updating)"; + return label; + } + auto label=formatSize(size.bytes); + if(size.partial) label+=L" (partial)"; + if(waiting) label+=L" (updating)"; + return label; + } + if(size.failed && !size.previous) return waiting?L"Error…":L"Error"; + std::wstring suffix; + if(size.failed) suffix=L"!"; + else if(size.partial) suffix=L"+"; + if(waiting) suffix+=L"…"; + return formatSize(size.bytes,columns>suffix.size()?columns-suffix.size():1)+suffix; +} + void showFileDetails(const Panel &panel) { refreshQuickView(panel); @@ -2299,11 +2371,12 @@ void showFileDetails(const Panel &panel) if(statusFields&2) { const auto &size=panel.sizes[row]; - const auto measured=panel.folderSizes.find(path); - if(size==L"Folder" && measured!=panel.folderSizes.end()) - details+=L" "+formatSize(measured->second.bytes)+(measured->second.partial?L" (partial)":L""); - else - details+=L" "+(size==L"Folder" || size==L"Up"?size:formatSize(std::stoull(size))); + if(size==L"Folder") + { + const auto measure=folderMeasurementText(panel,path); + details+=L" "+(measure.empty()?size:measure); + } + else details+=L" "+(size==L"Up"?size:formatSize(std::stoull(size))); } std::wstring timestamp=date; if((statusFields&4) && timestamp.size()>=12) details+=timestamp.substr(0,12); @@ -2435,6 +2508,12 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque } void startDirectoryScan(Panel &panel); +void queueAutomaticPanelSizes(Panel &panel,bool refresh=false); +void collectTreeBranches(); +void stopTreeBranches(Panel &panel); +void refreshTreeBranches(Panel &panel); +void replaceTreeRoot(Panel &panel,Panel::ScanResult &scan,bool sameDirectory,const std::set &marks); +void appendTreeRows(Panel &panel,PanelRowsUpdate &rows); bool samePanelSource(const Panel &panel,const std::optional &peer,const std::optional &ftp) { @@ -2534,6 +2613,12 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul } panel.findOrigin.reset(); } + if(!finding && !panel.listReturnMarks.empty()) + { + for(const auto &mark:panel.listReturnMarks) + if(mark.parent_path()==folderPathWithoutSeparator(directory)) markedPaths.insert(mark); + panel.listReturnMarks.clear(); + } if(peer || request.ftp) panel.navigation={}; else if(!finding) { @@ -2554,49 +2639,29 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul panel.watch.reset(); std::swap(panel.watch.handle,nextWatch.handle); } - panel.filteredMarks.clear(); - if(!finding) - { - if(!partial) std::erase_if(markedPaths,[&](const auto &path){return !metadata.contains(path);}); - panel.filteredMarks=markedPaths; - } - panel.metadata=std::move(metadata); - panel.rows.clear(); - panel.sizes.clear(); - panel.dimmed.clear(); - panel.marked.clear(); - panel.fileExtensionLength=panel.folderExtensionLength=0; const bool profiles=ftpProfileList(panel); + const bool renderTree=panel.view.tree && !finding && !profiles; + panel.filteredMarks.clear(); + if(renderTree) replaceTreeRoot(panel,scan,sameDirectory,markedPaths); + else + { + if(!finding) + { + stopTreeBranches(panel); + if(!partial) std::erase_if(markedPaths,[&](const auto &path){return !metadata.contains(path);}); + panel.filteredMarks=markedPaths; + } + panel.metadata=std::move(metadata); + } const auto parent=finding?fs::path{}:panelParentPath(directory,!panel.peer && !panel.ftp); const bool hasParent=!parent.empty(); - const auto rowCount=profiles?ftpProfiles.size():finding?files.size():ordered.size()+hasParent; - panel.rows.reserve(rowCount); - panel.sizes.reserve(rowCount); - panel.dimmed.reserve(rowCount); - panel.marked.reserve(rowCount); - const bool visible=IsWindowVisible(panel.list); - if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0); - SendMessageW(panel.list, LB_RESETCONTENT, 0, 0); - SendMessageW(panel.list, LB_INITSTORAGE, rowCount, 0); - auto add = [&](const fs::path &path, const std::wstring &label, bool folder) + const auto rowCount=profiles?ftpProfiles.size():finding?files.size(): + renderTree?panel.tree.branches.at(panel.tree.root).ordered.size()+hasParent:ordered.size()+hasParent; + PanelRowsUpdate rows(panel,rowCount); + const auto add=[&](const fs::path &path,const std::wstring &label,bool folder) { - if (SendMessageW(panel.list, LB_ADDSTRING, 0, reinterpret_cast(label.c_str())) >= 0) - { - panel.rows.push_back(path); - if(label!=L"..") - { - const auto extension=path.extension().native(); - auto &longest=folder?panel.folderExtensionLength:panel.fileExtensionLength; - if(extension.size()>1) longest=std::max(longest,extension.size()-1); - } - const bool marked=label!=L".." && markedPaths.contains(path); - panel.marked.push_back(marked); - if(marked) panel.filteredMarks.erase(path); - const auto entry=label==L".." || profiles ? FolderEntryMetadata{} : panel.metadata.at(path); - panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0); - panel.sizes.push_back(profiles?L"":folder ? (label==L".." ? L"Up" : L"Folder") : - std::to_wstring(entry.size)); - } + const bool marked=markedPaths.contains(path); + if(rows.add(path,label,folder,marked) && marked) panel.filteredMarks.erase(path); }; if(profiles) { @@ -2605,15 +2670,20 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul } else { - if(hasParent) add(parent,L"..",true); - if(finding) + if(hasParent) rows.add(parent,L"..",true,false,true); + if(renderTree) appendTreeRows(panel,rows); + else if(finding) + { for(const auto &file:files) add(file,file.lexically_relative(directory).native(),false); + } else + { for(const auto &entry:ordered) { const auto name=entry.path.filename().native(); add(entry.path,entry.folder?L"["+name+L"]":name,entry.folder); } + } } const auto label=panelCaption(panel); SetWindowTextW(panel.path,label.c_str()); @@ -2643,7 +2713,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul if(sameDirectory) SendMessageW(panel.list,LB_SETTOPINDEX,previousTop,0); SendMessageW(panel.list,LB_SETCURSEL,selected-panel.rows.begin(),0); } - if(visible) SendMessageW(panel.list,WM_SETREDRAW,TRUE,0); + rows.finish(); InvalidateRect(panel.list,nullptr,FALSE); updateSelectionSummary(panel); refreshQuickView(panel); @@ -2653,16 +2723,15 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul else if(!partial && error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND) setStatus(L"Some entries could not be read."); else if(updateDetails && &panel==&panels[active]) showFileDetails(panel); + if(!finding && !profiles) queueAutomaticPanelSizes(panel,true); return true; } -void startDirectoryScan(Panel &panel) +std::future> scanDirectoryInBackground(HWND owner,Panel::ScanRequest request, + PanelView view,std::shared_ptr entries,std::stop_token stop) { - panel.scanStop=std::stop_source{}; - panel.scanEntriesRead=std::make_shared(0); - const auto owner=GetParent(panel.list); std::packaged_task()> task( - [request=*panel.scanRequest,view=panel.view,entries=panel.scanEntriesRead,stop=panel.scanStop.get_token()] + [request=std::move(request),view=std::move(view),entries=std::move(entries),stop] { auto result=scanDirectory(request,*entries,stop); if(result->opened && !request.find) orderDirectoryRows(*result,view); @@ -2674,7 +2743,15 @@ void startDirectoryScan(Panel &panel) task(); PostMessageW(owner,directoryScanReady,0,0); }).detach(); - panel.scan=std::move(future); + return future; +} + +void startDirectoryScan(Panel &panel) +{ + panel.scanStop=std::stop_source{}; + panel.scanEntriesRead=std::make_shared(0); + panel.scan=scanDirectoryInBackground(GetParent(panel.list),*panel.scanRequest,panel.view, + panel.scanEntriesRead,panel.scanStop.get_token()); panel.scanSuperseded=false; if(&panel==&panels[active]) showDirectoryScanProgress(panel); } @@ -2738,6 +2815,8 @@ void open(Panel &panel,const fs::path &directory,bool offerElevation=false) openOn(panel,directory,offerElevation,panel.peer,{},{},panel.ftp); } +#include "files_panel_tree.inl" + bool panelViewAvailable(const Panel &panel) { return !panel.findOrigin && !ftpProfileList(panel) && !panel.directory.empty() && @@ -2779,11 +2858,41 @@ void togglePanelView(Panel &panel,bool foldersFirst) void editPanelFilter(HWND owner,Panel &panel); +void setTreePanelMode(Panel &panel) +{ + if(!panelViewAvailable(panel)) return; + if(!panel.view.tree) + { + panel.view.tree=true; + updatePanelView(panel); + return; + } + panel.view.tree=false; + savePanelView(static_cast(&panel-panels)); + const auto row=currentPanelRow(panel); + const auto selected=row!=LB_ERR && panel.sizes[row]!=L"Up"?panel.rows[row]:fs::path{}; + const auto directory=selected.empty()?panel.directory:selected.parent_path(); + panel.listReturnMarks=std::move(panel.tree.marks); + stopTreeBranches(panel); + openOn(panel,directory,false,panel.peer,selected,{},panel.ftp); +} + +void toggleAutomaticPanelSizes(Panel &panel) +{ + if(!panelViewAvailable(panel)) return; + panel.view.automaticSizes=!panel.view.automaticSizes; + savePanelView(static_cast(&panel-panels)); + if(panel.view.automaticSizes) queueAutomaticPanelSizes(panel,true); + else cancelFolderSizes(panel); +} + void panelViewAction(HWND owner,Panel &panel,int action) { if(action>=0 && action<4) sortPanel(panel,static_cast(action)); else if(action==5) editPanelFilter(owner,panel); else if(action==4 || action==6) togglePanelView(panel,action==4); + else if(action==7) setTreePanelMode(panel); + else if(action==8) toggleAutomaticPanelSizes(panel); } LRESULT CALLBACK panelHeadingInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) @@ -2846,11 +2955,13 @@ void refreshChangedPanels() if(!FindNextChangeNotification(watch)) panel.watch.reset(); // Pass a copy because opening the folder rebuilds the panel. const auto directory=panel.directory; + if(panel.view.automaticSizes) cancelFolderSizes(panel); open(panel,directory); } } void collectFolderSizes(Panel &panel); +bool queueFolderMeasurements(Panel &panel,const std::vector &folders,bool foreground); bool calculateFolderSizes(Panel &panel,LRESULT current) { @@ -2869,6 +2980,12 @@ bool calculateFolderSizes(Panel &panel,LRESULT current) folders.push_back(panel.rows[current]); } + return queueFolderMeasurements(panel,folders,true); +} + +bool queueFolderMeasurements(Panel &panel,const std::vector &folders,bool foreground) +{ + if(folders.empty()) return false; if(const auto running=panel.folderSizeJob) { bool queued=false; @@ -2890,7 +3007,7 @@ bool calculateFolderSizes(Panel &panel,LRESULT current) if(queued) { if(added) InvalidateRect(panel.list,nullptr,FALSE); - setStatus(L"Calculating folder sizes... [Esc]"); + if(foreground) setStatus(L"Calculating folder sizes... [Esc]"); return true; } collectFolderSizes(panel); @@ -2952,8 +3069,8 @@ bool calculateFolderSizes(Panel &panel,LRESULT current) catch(const std::exception &) { std::lock_guard lock(job->mutex); - if(!job->current.empty()) job->completed.try_emplace(job->current,FolderSize{0,true}); - for(const auto &folder:job->pending) job->completed.try_emplace(folder,FolderSize{0,true}); + if(!job->current.empty()) job->completed.try_emplace(job->current,FolderSize{0,true,true}); + for(const auto &folder:job->pending) job->completed.try_emplace(folder,FolderSize{0,true,true}); job->finished=true; } }; @@ -2964,35 +3081,54 @@ bool calculateFolderSizes(Panel &panel,LRESULT current) return true; } panel.folderSizeJob=std::move(job); - panel.folderSizeWaiting.insert(std::next(folders.begin()),folders.end()); - if(!panel.folderSizeWaiting.empty()) InvalidateRect(panel.list,nullptr,FALSE); - setStatus(L"Calculating folder sizes... [Esc]"); + panel.folderSizeWaiting.insert(folders.begin(),folders.end()); + InvalidateRect(panel.list,nullptr,FALSE); + if(foreground) setStatus(L"Calculating folder sizes... [Esc]"); return true; } +void queueAutomaticPanelSizes(Panel &panel,bool refresh) +{ + if(!panel.view.automaticSizes || panel.findOrigin || ftpProfileList(panel)) return; + std::vector folders; + for(size_t i=0;isecond)) folders.push_back(path); + } + queueFolderMeasurements(panel,folders,false); +} + void collectFolderSizes(Panel &panel) { const auto job=panel.folderSizeJob; if(!job) return; FolderSizes completed; - fs::path current, spinner; + fs::path spinner; bool finished; { std::lock_guard lock(job->mutex); completed.swap(job->completed); finished=job->finished; - current=job->current; if(!finished && GetTickCount64()-job->started>=folderSpinnerDelay) - spinner=current; + spinner=job->current; } - if(panel.folderSizeWaiting.erase(current)) invalidateFolderSizeRow(panel,current); if(spinner!=panel.folderSpinner) invalidateFolderSizeRow(panel,panel.folderSpinner); panel.folderSpinner=std::move(spinner); invalidateFolderSizeRow(panel,panel.folderSpinner); for(const auto &[path,size]:completed) { panel.folderSizeWaiting.erase(path); - panel.folderSizes.insert_or_assign(path,size); + auto reported=size; + if(const auto previous=panel.folderSizes.find(path); + size.failed && previous!=panel.folderSizes.end() && (!previous->second.failed || previous->second.previous)) + { + reported.bytes=previous->second.bytes; + reported.previous=true; + } + panel.folderSizes.insert_or_assign(path,reported); invalidateFolderSizeRow(panel,path); } if(finished) cancelFolderSizes(panel); @@ -3791,6 +3927,7 @@ void enter(Panel &panel) revealLocalFile(panel,target); return; } + if(panel.sizes[row]==L"Folder" && toggleTreeRow(panel,static_cast(row))) return; if(panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") open(panel,target,true); else if(panel.ftp) openSelectedText(panel,false,false); else openPanelFile(panel, target, nullptr, L"Cannot open the selected file."); @@ -5817,7 +5954,8 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve results.insert(progress.renamedTarget.empty()?to:progress.renamedTarget); if(!request.externalSources) progress.ui.invoke([&] { const auto row=std::find(source.rows.begin(),source.rows.end(),path); - if(row!=source.rows.end()) source.marked[row-source.rows.begin()]=false; + if(row!=source.rows.end()) markPanelRow(source,row-source.rows.begin(),false); + else if(treePanelActive(source)) source.tree.marks.erase(path); InvalidateRect(source.list,nullptr,FALSE); }); } @@ -5852,6 +5990,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve } if(move) { + if(treePanelActive(source)) pruneTreeMarks(source,removed); if(fromSearch) pruneSearchResults(source,removed); else open(source,source.directory); if(!ftpRename && &source!=&destination) open(destination,destination.directory); @@ -6259,6 +6398,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) progressDialog.close(); for(auto &visible:panels) { + if(treePanelActive(visible) && samePanelSource(panel,visible.peer,visible.ftp)) pruneTreeMarks(visible,removed); if(visible.findOrigin) pruneSearchResults(visible,removed); else if(!visible.directory.empty()) open(visible,visible.directory); } @@ -6776,6 +6916,15 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT activatePanel(index); if(message==WM_LBUTTONDOWN) { + if(rowHit && treePanelActive(panel)) + { + const auto depth=panel.tree.depths.find(panel.rows[row]); + if(depth!=panel.tree.depths.end()) + { + const auto start=2*static_cast(std::min(depth->second,40))*cellWidth; + if(point.x>=start && point.x<=start+2*cellWidth && toggleTreeRow(panel,row)) return 0; + } + } if(rowHit && panel.sizes[row]!=L"Up") panelDragStart=point; SetCapture(window); } @@ -6788,6 +6937,13 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT restoreCommandFocus(); return 0; } + if(message==WM_KEYDOWN && (wp==VK_LEFT || wp==VK_RIGHT) && + !(GetKeyState(VK_SHIFT)&0x8000) && !(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) && + moveTreeCursor(panels[index],wp==VK_RIGHT)) + { + panelClipboardContext=true; + return 0; + } const bool rangeKey=wp==VK_UP || wp==VK_DOWN || wp==VK_LEFT || wp==VK_RIGHT; if(message==WM_KEYDOWN && (wp==VK_INSERT || (rangeKey && (GetKeyState(VK_SHIFT)&0x8000)))) { @@ -6808,8 +6964,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT const bool toBoundary=wp==VK_LEFT || wp==VK_RIGHT; const auto first=toBoundary ? std::min(row,target) : row; const auto end=toBoundary ? std::max(row,target) : row; - for(auto i=first;i<=end;++i) - if(panel.sizes[i]!=L"Up") panel.marked[i]=mark; + for(auto i=first;i<=end;++i) markPanelRow(panel,i,mark); SendMessageW(window,LB_SETCURSEL,target,0); InvalidateRect(window,nullptr,FALSE); updateSelectionSummary(panel); @@ -6962,6 +7117,9 @@ void openMenu(HWND window, int index) rows.push_back(panel.view.foldersFirst?L"✓ Folders first\tCtrl+F7":L" Folders first\tCtrl+F7"); rows.push_back(panel.view.mask.empty()?L" Filter by mask…\tCtrl+F8":L"✓ Filter by mask…\tCtrl+F8"); rows.push_back(panel.view.showHidden?L"✓ Show hidden and system\tCtrl+F9":L" Show hidden and system\tCtrl+F9"); + rows.push_back(panel.view.tree?L" List view\tCtrl+F10":L" Tree view\tCtrl+F10"); + rows.push_back(panel.view.automaticSizes?L"✓ Background folder sizes\tCtrl+F11": + L" Background folder sizes\tCtrl+F11"); } } else if(index==1) rows={L"Copy\tF5",L"Move\tF6",L"Make folder\tF7",L"Exit\tF10"}; @@ -7242,7 +7400,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) performPanelDrop(window); return 0; case directoryScanReady: - if(!FilesModalDialog::activeFor(window)) collectDirectoryScans(); + if(!FilesModalDialog::activeFor(window)) + { + collectDirectoryScans(); + collectTreeBranches(); + } return 0; case WM_TIMER: if(wp==driveQueryTimer) {pollDriveQueries(window);return 0;} @@ -7260,6 +7422,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) if(!FilesModalDialog::activeFor(window)) { collectDirectoryScans(); + collectTreeBranches(); refreshChangedPanels(); showDirectoryScanProgress(panels[active]); } @@ -7673,7 +7836,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) background=Selection; COLORREF rowBackground=colors[background]; HFONT rowFont{}; - const wchar_t *folderIndicator=nullptr; + std::wstring folderIndicator; if(panelRow) { const auto &panel=panels[item.CtlID-102]; @@ -7686,12 +7849,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) if(item.itemID(sizeWidth)); } } auto shortcut=text.find(L'\t'); @@ -7792,13 +7950,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } else if(item.CtlID>=130 && item.CtlID<=134) paintMenuLabel(item.hDC,item.rcItem,text,0,foreground,colors[background]); - else if(folderIndicator && !panels[item.CtlID-102].wide) + else if(!folderIndicator.empty() && !panels[item.CtlID-102].wide) { auto name=item.rcItem, indicator=item.rcItem; - indicator.left=std::max(indicator.left,indicator.right-lstrlenW(folderIndicator)*cellWidth-10); + indicator.left=std::max(indicator.left,indicator.right-static_cast(folderIndicator.size())*cellWidth-10); name.right=indicator.left; paintText(item.hDC,name,text.c_str(),foreground,rowBackground,false,rowFont); - paintText(item.hDC,indicator,folderIndicator,foreground,rowBackground,true); + paintText(item.hDC,indicator,folderIndicator.c_str(),foreground,rowBackground,true); } else paintText(item.hDC,item.rcItem,text.c_str(),foreground,rowBackground,false,rowFont); if(item.CtlID==102 || item.CtlID==103) @@ -7811,7 +7969,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) const auto &extension=columns[extensionColumn]; const auto &date=columns[dateColumn]; const bool folder=panel.sizes[item.itemID]==L"Folder"; - if(folder) text=path.filename().native(); + const bool tree=treePanelActive(panel); + if(folder || (tree && panel.sizes[item.itemID]!=L"Up")) text=path.filename().native(); const bool separateExtension=extension.leftsecond.partial; - visible=formatSize(measured->second.bytes,static_cast(sizeWidth)-(partial?1:0)); - if(partial) visible+=L"+"; - } + if(!folderIndicator.empty()) visible=folderIndicator; else if(amount!=L"Folder" && amount!=L"Up") visible=formatSize(std::stoull(amount),static_cast(sizeWidth)); paintText(item.hDC,columns[sizeColumn],visible.c_str(),foreground,rowBackground,true); @@ -7924,6 +8077,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) for(auto &panel:panels) { panel.scanStop.request_stop(); + stopTreeBranches(panel); panel.watch.reset(); } terminalView.close(); @@ -8162,12 +8316,13 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) continue; } if(mainInput && !terminalVisible && !copyInProgress && - message.message==WM_KEYDOWN && message.wParam>=VK_F1 && message.wParam<=VK_F12 && + (message.message==WM_KEYDOWN || (message.message==WM_SYSKEYDOWN && message.wParam==VK_F10)) && + message.wParam>=VK_F1 && message.wParam<=VK_F12 && (GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) && !(GetKeyState(VK_RWIN)&0x8000)) { - if(!(message.lParam & (1LL<<30)) && message.wParam<=VK_F9) + if(!(message.lParam & (1LL<<30)) && message.wParam<=VK_F11) { hidePicker(); showMenu(false); @@ -8300,7 +8455,8 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) } } if (message.message == WM_SYSKEYDOWN && message.wParam == VK_F10 && - !(GetKeyState(VK_MENU) & 0x8000) && !(GetKeyState(VK_SHIFT) & 0x8000)) + !(GetKeyState(VK_CONTROL) & 0x8000) && !(GetKeyState(VK_MENU) & 0x8000) && + !(GetKeyState(VK_SHIFT) & 0x8000)) { SendMessageW(window, WM_CLOSE, 0, 0); continue; diff --git a/src/files_ntfs_space.inl b/src/files_ntfs_space.inl index b19df99..559937a 100644 --- a/src/files_ntfs_space.inl +++ b/src/files_ntfs_space.inl @@ -13,12 +13,6 @@ bool sameVolumeRoot(const fs::path &directory,const fs::path &root) right.data(),static_cast(right.size()),TRUE)==CSTR_EQUAL; } -fs::path spaceScanPath(fs::path path) -{ - if(!path.has_filename() && path.has_relative_path()) return path.parent_path(); - return path; -} - bool isNtfsVolume(const fs::path &root) { wchar_t filesystem[16]{}; diff --git a/src/files_panel_order.inl b/src/files_panel_order.inl index 4513f4f..b8d6838 100644 --- a/src/files_panel_order.inl +++ b/src/files_panel_order.inl @@ -29,9 +29,7 @@ void orderDirectoryRows(Panel::ScanResult &result,const PanelView &view) const auto &metadata=result.metadata.at(path); const uint64_t value=view.sort==PanelSort::modified?metadata.modified: view.sort==PanelSort::size?metadata.size:0; - const bool visible=(view.showHidden || !(metadata.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))) && - (folder || view.mask.empty() || matchesFileMask(directoryRowName(path),view.mask)); - if(visible || path==view.revealedFile) rows.push_back({std::move(path),value,folder}); + if(visibleToPanelView(view,path,metadata)) rows.push_back({std::move(path),value,folder}); } }; append(result.folders,true); diff --git a/src/files_panel_rows.inl b/src/files_panel_rows.inl new file mode 100644 index 0000000..fcd6a2e --- /dev/null +++ b/src/files_panel_rows.inl @@ -0,0 +1,116 @@ +class PanelRowsUpdate +{ +public: + PanelRowsUpdate(Panel &panel,size_t count) : panel(panel),visible(IsWindowVisible(panel.list)), + profiles(ftpProfileList(panel)) + { + if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0); + panel.rows.clear(); + panel.sizes.clear(); + panel.dimmed.clear(); + panel.marked.clear(); + panel.fileExtensionLength=panel.folderExtensionLength=0; + panel.rows.reserve(count); + panel.sizes.reserve(count); + panel.dimmed.reserve(count); + panel.marked.reserve(count); + SendMessageW(panel.list,LB_RESETCONTENT,0,0); + SendMessageW(panel.list,LB_INITSTORAGE,count,0); + } + + ~PanelRowsUpdate() {finish();} + + bool add(const fs::path &path,const std::wstring &label,bool folder,bool marked,bool up=false) + { + if(SendMessageW(panel.list,LB_ADDSTRING,0,reinterpret_cast(label.c_str()))<0) return false; + panel.rows.push_back(path); + if(!up) + { + const auto extension=path.extension().native(); + auto &longest=folder?panel.folderExtensionLength:panel.fileExtensionLength; + if(extension.size()>1) longest=std::max(longest,extension.size()-1); + } + panel.marked.push_back(!up && marked); + const auto found=panel.metadata.find(path); + const auto entry=up || profiles || found==panel.metadata.end()?FolderEntryMetadata{}:found->second; + panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0); + panel.sizes.push_back(profiles?L"":folder?(up?L"Up":L"Folder"):std::to_wstring(entry.size)); + return true; + } + + void finish() + { + if(visible) + { + SendMessageW(panel.list,WM_SETREDRAW,TRUE,0); + visible=false; + } + } + +private: + Panel &panel; + bool visible,profiles; +}; + +bool treePanelActive(const Panel &panel) +{ + return panel.view.tree && !panel.findOrigin && !panel.tree.root.empty(); +} + +void markPanelRow(Panel &panel,size_t row,bool mark) +{ + if(row>=panel.rows.size() || panel.sizes[row]==L"Up") return; + panel.marked[row]=mark; + if(!treePanelActive(panel)) return; + const auto &path=panel.rows[row]; + if(mark) panel.tree.marks.insert(path); + else panel.tree.marks.erase(path); +} + +const FolderEntryMetadata *treePanelEntry(const Panel &panel,const fs::path &path) +{ + const auto branch=panel.tree.branches.find(path.parent_path()); + if(branch==panel.tree.branches.end()) return nullptr; + const auto item=branch->second.metadata.find(path); + return item==branch->second.metadata.end()?nullptr:&item->second; +} + +bool matchesFileMask(std::wstring_view name,std::wstring_view mask); + +bool visibleToPanelView(const PanelView &view,const fs::path &path,const FolderEntryMetadata &metadata) +{ + if(path==view.revealedFile) return true; + return (view.showHidden || !(metadata.attributes&(FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM))) && + ((metadata.attributes&FILE_ATTRIBUTE_DIRECTORY) || view.mask.empty() || + matchesFileMask(path.filename().native(),view.mask)); +} + +template +void visitPanelMarks(const Panel &panel,const Visitor &visit) +{ + if(treePanelActive(panel)) + { + for(const auto &path:panel.tree.marks) + { + const auto entry=treePanelEntry(panel,path); + if(!entry || !visibleToPanelView(panel.view,path,*entry)) continue; + auto directory=path.parent_path(); + while(directory!=panel.tree.root) + { + const auto parent=treePanelEntry(panel,directory); + const auto ancestor=directory.parent_path(); + if(!parent || ancestor==directory || !visibleToPanelView(panel.view,directory,*parent)) break; + directory=ancestor; + } + if(directory==panel.tree.root) visit(path,*entry); + } + return; + } + if(ftpProfileList(panel)) return; + for(size_t i=0;ifirst,item->second); + } +} diff --git a/src/files_panel_tree.inl b/src/files_panel_tree.inl new file mode 100644 index 0000000..120f0d4 --- /dev/null +++ b/src/files_panel_tree.inl @@ -0,0 +1,229 @@ +void stopTreeBranches(Panel &panel) +{ + for(auto &[path,branch]:panel.tree.branches) branch.stop.request_stop(); + panel.tree={}; +} + +bool canExpandTreeEntry(const FolderEntryMetadata &entry) +{ + return (entry.attributes&FILE_ATTRIBUTE_DIRECTORY) && !(entry.attributes&FILE_ATTRIBUTE_REPARSE_POINT); +} + +void startPendingTreeScans(Panel &panel) +{ + if(!treePanelActive(panel)) return; + auto running=std::count_if(panel.tree.branches.begin(),panel.tree.branches.end(), + [](const auto &item){return item.second.scan.valid();}); + for(auto &[path,branch]:panel.tree.branches) + { + if(running>=2) break; + if(!branch.expanded || !branch.needsScan || branch.scan.valid() || path==panel.tree.root) continue; + branch.needsScan=false; + const auto entry=treePanelEntry(panel,path); + if(!entry || !canExpandTreeEntry(*entry)) continue; + branch.stop=std::stop_source{}; + Panel::ScanRequest request{.directory=path,.peer=panel.peer,.ftp=panel.ftp}; + try + { + branch.scan=scanDirectoryInBackground(GetParent(panel.list),std::move(request),panel.view, + std::make_shared(0),branch.stop.get_token()); + ++running; + } + catch(const std::exception &) {branch.failed=true;} + } +} + +void refreshTreeBranches(Panel &panel) +{ + if(!treePanelActive(panel)) return; + for(auto &[path,branch]:panel.tree.branches) + if(branch.expanded && path!=panel.tree.root) branch.needsScan=true; + startPendingTreeScans(panel); +} + +void replaceTreeRoot(Panel &panel,Panel::ScanResult &scan,bool sameDirectory,const std::set &marks) +{ + auto directory=folderPathWithoutSeparator(panel.directory); + if(!sameDirectory || panel.tree.root!=directory) stopTreeBranches(panel); + panel.tree.root=std::move(directory); + auto &root=panel.tree.branches[panel.tree.root]; + root.expanded=root.loaded=true; + root.ordered=std::move(scan.ordered); + root.metadata=std::move(scan.metadata); + panel.tree.marks.insert(marks.begin(),marks.end()); + if(scan.error!=ERROR_CANCELLED) + std::erase_if(panel.tree.marks,[&](const auto &path) { + return path.parent_path()==panel.tree.root && !root.metadata.contains(path); + }); + refreshTreeBranches(panel); +} + +void pruneTreeMarks(Panel &panel,const std::set &removed) +{ + if(!treePanelActive(panel) || removed.empty()) return; + std::erase_if(panel.tree.marks,[&](auto path) { + for(;path!=panel.tree.root && path!=path.parent_path();path=path.parent_path()) + if(removed.contains(path)) return true; + return false; + }); +} + +std::wstring treeRowPrefix(const Panel &panel,const fs::path &path,bool folder) +{ + const auto depth=panel.tree.depths.find(path); + if(depth==panel.tree.depths.end()) return {}; + std::wstring prefix(2*std::min(depth->second,40),L' '); + if(!folder) return prefix+L" "; + const auto branch=panel.tree.branches.find(path); + if(branch!=panel.tree.branches.end()) + { + if(branch->second.scan.valid() || branch->second.needsScan) return prefix+L"… "; + if(branch->second.expanded) return prefix+(branch->second.failed?L"! ":L"▾ "); + } + if(const auto entry=treePanelEntry(panel,path);entry && canExpandTreeEntry(*entry)) return prefix+L"▸ "; + return prefix+L" "; +} + +void appendTreeRows(Panel &panel,PanelRowsUpdate &rows) +{ + panel.tree.depths.clear(); + panel.metadata.clear(); + struct BranchRows {const Panel::TreeBranch *branch; size_t next;}; + std::vector stack{{&panel.tree.branches.at(panel.tree.root),0}}; + while(!stack.empty()) + { + auto ¤t=stack.back(); + if(current.next==current.branch->ordered.size()) + { + stack.pop_back(); + continue; + } + const auto &entry=current.branch->ordered[current.next++]; + const auto &path=entry.path; + panel.tree.depths.emplace(path,stack.size()-1); + const auto metadata=current.branch->metadata.find(path); + if(metadata==current.branch->metadata.end() || !visibleToPanelView(panel.view,path,metadata->second)) continue; + panel.metadata.emplace(path,metadata->second); + const auto label=treeRowPrefix(panel,path,entry.folder)+path.filename().native(); + rows.add(path,label,entry.folder,panel.tree.marks.contains(path)); + const auto child=panel.tree.branches.find(path); + if(entry.folder && child!=panel.tree.branches.end() && child->second.expanded && child->second.loaded) + stack.push_back({&child->second,0}); + } +} + +void redrawTreeRows(Panel &panel) +{ + if(!treePanelActive(panel)) return; + const auto current=SendMessageW(panel.list,LB_GETCURSEL,0,0); + const auto top=SendMessageW(panel.list,LB_GETTOPINDEX,0,0); + auto selected=current>=0 && static_cast(current)(current,0,panel.rows.size()-1):position-panel.rows.begin(),0); + } + rows.finish(); + InvalidateRect(panel.list,nullptr,FALSE); + InvalidateRect(panel.heading,nullptr,FALSE); + updateSelectionSummary(panel); + refreshQuickView(panel); +} + +void collectTreeBranches() +{ + for(auto &panel:panels) + { + if(!treePanelActive(panel)) continue; + bool updated=false; + for(auto &[path,branch]:panel.tree.branches) + { + if(!branch.scan.valid() || branch.scan.wait_for(std::chrono::seconds(0))!=std::future_status::ready) continue; + updated=true; + try + { + auto scan=branch.scan.get(); + const auto error=scan->error; + branch.failed=!scan->opened || !scan->failure.empty() || + (error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND); + if(scan->opened && scan->failure.empty()) + { + branch.loaded=true; + branch.ordered=std::move(scan->ordered); + branch.metadata=std::move(scan->metadata); + if(!branch.failed) std::erase_if(panel.tree.marks,[&](const auto &marked) { + return marked.parent_path()==path && !branch.metadata.contains(marked); + }); + } + } + catch(const std::exception &) {branch.failed=true;} + if(branch.failed && &panel==&panels[active] && branch.expanded) + setStatus(L"Could not read tree folder: "+path.native()); + } + if(updated) + { + startPendingTreeScans(panel); + redrawTreeRows(panel); + queueAutomaticPanelSizes(panel); + } + } +} + +bool toggleTreeRow(Panel &panel,size_t row,std::optional expanded={}) +{ + if(!treePanelActive(panel) || row>=panel.rows.size() || panel.sizes[row]!=L"Folder") return false; + const auto path=panel.rows[row]; + const auto entry=treePanelEntry(panel,path); + if(!entry || !canExpandTreeEntry(*entry)) return false; + auto &branch=panel.tree.branches[path]; + const auto next=expanded.value_or(!branch.expanded); + if(next==branch.expanded) return false; + branch.expanded=next; + if(next) + { + branch.needsScan=true; + startPendingTreeScans(panel); + } + else branch.needsScan=false; + redrawTreeRows(panel); + if(&panel==&panels[active]) + { + if(next && branch.scan.valid()) setStatus(L"Reading tree folder: "+path.native()); + else showFileDetails(panel); + } + return true; +} + +bool moveTreeCursor(Panel &panel,bool forward) +{ + if(!treePanelActive(panel)) return false; + const auto position=SendMessageW(panel.list,LB_GETCURSEL,0,0); + if(position<0 || static_cast(position)>=panel.rows.size() || panel.sizes[position]==L"Up") return false; + if(toggleTreeRow(panel,static_cast(position),forward)) return true; + const auto &path=panel.rows[position]; + if(forward) + { + if(static_cast(position+1)(&panel-panels); - SpaceAnalyzer state{.folder=spaceScanPath(panel.directory),.root=spaceScanPath(panel.directory)}; + SpaceAnalyzer state{.folder=folderPathWithoutSeparator(panel.directory),.root=folderPathWithoutSeparator(panel.directory)}; const auto answer=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(118),owner, spaceAnalyzerDialog,reinterpret_cast(&state)); if(answer==spaceView) From 3efe10885310138288e046e8381a7c96af8741da Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 15:17:20 +0200 Subject: [PATCH 14/61] Add per-panel modes and customizable columns Refs #98 --- FILES-UI.md | 16 +- resources/files.rc | 24 +- src/files_columns_metadata.inl | 86 +++++++ src/files_main.cpp | 389 ++++++++++++++++++++++------- src/files_options.inl | 39 ++- src/files_panel_columns_dialog.inl | 78 ++++++ src/files_panel_rows.inl | 14 ++ src/files_panel_tree.inl | 7 +- src/files_space_analyzer.inl | 20 -- 9 files changed, 551 insertions(+), 122 deletions(-) create mode 100644 src/files_columns_metadata.inl create mode 100644 src/files_panel_columns_dialog.inl diff --git a/FILES-UI.md b/FILES-UI.md index 893a769..079c4b6 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -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 з командного рядка діють на активну панель. - Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший. diff --git a/resources/files.rc b/resources/files.rc index 3141a9a..56e7296 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -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 diff --git a/src/files_columns_metadata.inl b/src/files_columns_metadata.inl new file mode 100644 index 0000000..a6ad423 --- /dev/null +++ b/src/files_columns_metadata.inl @@ -0,0 +1,86 @@ +constexpr DWORD columnFileShare=FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE; + +std::optional fileStorageInformation(HANDLE file) +{ + FILE_STANDARD_INFO result{}; + if(GetFileInformationByHandleEx(file,FileStandardInfo,&result,sizeof(result))) return result; + return {}; +} + +std::optional allocatedFileBytes(HANDLE file,DWORD attributes, + const std::optional &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(compression.CompressedFileSize.QuadPart); + return {}; + } + if(metadata && !metadata->Directory && metadata->AllocationSize.QuadPart>=0) + return static_cast(metadata->AllocationSize.QuadPart); + return {}; +} + +std::optional 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{}:fileStorageInformation(file.value); + return allocatedFileBytes(file.value,attributes,metadata); +} + +std::wstring localOwnerName(const fs::path &path,std::map &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 security(descriptor,LocalFree); + if(result!=ERROR_SUCCESS || !owner) return {}; + wchar_t *sidText=nullptr; + if(!ConvertSidToStringSidW(owner,&sidText)) return {}; + const std::unique_ptr 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(std::size(name)),domainLength=static_cast(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 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)); + } +} diff --git a/src/files_main.cpp b/src/files_main.cpp index 53b418b..7f56d94 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -5,6 +5,8 @@ #include #include #include +#include +#include #include #include #include @@ -427,6 +429,44 @@ struct LocalNavigation } }; +enum class PanelMode : DWORD { brief, wide, medium, full }; +constexpr const wchar_t *panelModeNames[]{L"Brief",L"Wide",L"Medium",L"Full"}; +enum PanelColumn : size_t { nameColumn, extensionColumn, sizeColumn, dateColumn, allocationColumn, + linkColumn, ownerColumn, panelColumnCount }; +constexpr const wchar_t *panelColumnNames[]{L"Name",L"Ext",L"Size",L"Modified",L"Allocated",L"Links",L"Owner"}; +constexpr DWORD columnMask(PanelColumn column) { return 1u< allocated; + std::optional links; +}; + +using ColumnMetadataMap=std::map; + +DWORD defaultPanelColumns(PanelMode mode) +{ + constexpr DWORD medium=columnMask(sizeColumn); + constexpr DWORD wide=medium|columnMask(extensionColumn)|columnMask(dateColumn); + switch(mode) + { + case PanelMode::brief: return 0; + case PanelMode::medium: return medium; + case PanelMode::wide: return wide; + case PanelMode::full: return wide|extendedColumnMask; + } + return 0; +} + enum class PanelSort { name, extension, size, modified }; struct PanelView { @@ -511,11 +551,13 @@ struct Panel std::wstring failure; fs::path ftpInitialDirectory; std::vector ordered; + ColumnMetadataMap columnMetadata; }; struct TreeBranch { std::vector ordered; std::map metadata; + ColumnMetadataMap columnMetadata; std::future> scan; std::stop_source stop; bool expanded{}, loaded{}, failed{}, needsScan{}; @@ -545,7 +587,10 @@ struct Panel fs::path folderSpinner; std::set transferResults; size_t fileExtensionLength{}, folderExtensionLength{}; - bool wide{}; + PanelMode mode{PanelMode::brief}; + std::array columns; + std::array longestColumn{}; + ColumnMetadataMap columnMetadata; }; bool ftpProfileList(const Panel &panel) { @@ -559,9 +604,18 @@ std::wstring panelLocation(const Panel &panel) return (panel.peer?panel.peer->name+L" · ":std::wstring{})+panel.directory.native(); } -bool hasPanelSizeColumn(const Panel &panel) +bool detailedPanel(const Panel &panel) {return panel.mode!=PanelMode::brief;} +DWORD defaultVisibleColumns(PanelMode mode); + +DWORD effectivePanelColumns(const Panel &panel) { - return panel.wide && !panel.findOrigin && !ftpProfileList(panel); + const auto &columns=panel.columns[static_cast(panel.mode)]; + return detailedPanel(panel)?(columns.customized?columns.visibility:defaultVisibleColumns(panel.mode)):0; +} + +bool hasPanelColumns(const Panel &panel) +{ + return detailedPanel(panel) && !panel.findOrigin && !ftpProfileList(panel); } std::wstring panelCaption(const Panel &panel) @@ -776,7 +830,42 @@ fs::path savedPanelPath(const wchar_t *key) return path; } -constexpr const wchar_t *panelModeKeys[]{L"LeftWide",L"RightWide"}; +constexpr const wchar_t *legacyPanelModeKeys[]{L"LeftWide",L"RightWide"}; +constexpr const wchar_t *panelModeKeys[]{L"LeftPanelMode",L"RightPanelMode"}; +constexpr const wchar_t *panelColumnKeys[2][4]{ + {nullptr,L"LeftWideColumns",L"LeftMediumColumns",L"LeftFullColumns"}, + {nullptr,L"RightWideColumns",L"RightMediumColumns",L"RightFullColumns"}}; + +PanelMode readPanelMode(int index) +{ + const auto legacy=preference(legacyPanelModeKeys[index],defaultWide)!=0; + const auto stored=preference(panelModeKeys[index],legacy?1:0); + return stored< std::size(panelModeNames)?static_cast(stored):PanelMode::brief; +} + +void savePanelMode(int index,PanelMode mode) +{ + savePreference(panelModeKeys[index],static_cast(mode)); + savePreference(legacyPanelModeKeys[index],mode!=PanelMode::brief); +} + +void loadPanelColumns(int index) +{ + auto &panel=panels[index]; + for(size_t mode=1;mode(mode); + const auto &settings=panels[index].columns[slot]; + savePreference(panelColumnKeys[index][slot],settings.visibility | + (settings.automatic?0:0x100) | (settings.customized?0x200:0)); +} constexpr const wchar_t *panelViewKeys[]{L"LeftViewOrder",L"RightViewOrder"}; void loadPanelView(int index) @@ -799,13 +888,19 @@ void savePanelView(int index) (view.tree?32:0) | (view.automaticSizes?64:0)); } -void setMode(int index, bool wide) +void refreshPanelColumnData(Panel &panel); + +void setMode(int index,PanelMode mode) { - panels[index].wide=wide; - savePreference(panelModeKeys[index],wide); - notifyFilesPreferences(GetParent(panels[index].list)); - layout(GetParent(panels[index].list)); - InvalidateRect(panels[index].list,nullptr,TRUE); + auto &panel=panels[index]; + if(panel.mode==mode) return; + const auto previous=effectivePanelColumns(panel); + panel.mode=mode; + savePanelMode(index,mode); + notifyFilesPreferences(GetParent(panel.list)); + layout(GetParent(panel.list)); + InvalidateRect(panel.list,nullptr,TRUE); + if((previous^effectivePanelColumns(panel))&extendedColumnMask) refreshPanelColumnData(panel); showFileDetails(panels[active]); } HFONT mono{}; @@ -813,31 +908,78 @@ LOGFONTW displayFont{}; int fontPoints=110; int textHeight=20, cellWidth=9; -constexpr size_t nameColumn=0, extensionColumn=1, sizeColumn=2, dateColumn=3; +using PanelColumnRects=std::array; -std::array panelColumns(const Panel &panel,RECT bounds) +DWORD defaultVisibleColumns(PanelMode mode) { - auto columns=std::array{bounds,bounds,bounds,bounds}; - const auto nameMinimum=10L*cellWidth; - const auto sizeWidthPx=(sizeWidth+2L)*cellWidth; - const auto dateWidth=12L*cellWidth; - const auto extensionLength=std::max(alignExtensions?panel.fileExtensionLength:0, - alignFolders?panel.folderExtensionLength:0); - const auto extensionWidth=(std::clamp(static_cast(extensionLength),4L,12L)+2)*cellWidth; - const LONG available=bounds.right-bounds.left; - const bool showDate=available>=nameMinimum+sizeWidthPx+dateWidth; - columns[dateColumn].left=showDate?bounds.right-dateWidth:bounds.right; - columns[sizeColumn].right=columns[dateColumn].left; - columns[sizeColumn].left=std::max(bounds.left,columns[sizeColumn].right-sizeWidthPx); - columns[extensionColumn].right=columns[sizeColumn].left; - const bool showExtension=(alignExtensions || alignFolders) && - columns[sizeColumn].left-bounds.left>=nameMinimum+extensionWidth; - columns[extensionColumn].left=columns[sizeColumn].left-(showExtension?extensionWidth:0); - columns[nameColumn].right=columns[extensionColumn].left; + auto columns=defaultPanelColumns(mode); + if(mode==PanelMode::wide && !alignExtensions && !alignFolders) columns&=~columnMask(extensionColumn); return columns; } -void paintPanelColumnLines(HDC dc,const std::array &columns) +PanelColumnRects panelColumns(const Panel &panel,RECT bounds) +{ + PanelColumnRects columns; + columns.fill(bounds); + const auto mask=effectivePanelColumns(panel); + const auto &settings=panel.columns[static_cast(panel.mode)]; + const auto extensionLength=std::max(alignExtensions || settings.customized || panel.mode==PanelMode::full? + panel.fileExtensionLength:0,alignFolders || settings.customized || panel.mode==PanelMode::full? + panel.folderExtensionLength:0); + const std::array minimum{10,4,6,11,10,6,7}; + const std::array fixed{10,6,sizeWidth+2L,12,11,7,13}; + auto desired=fixed; + if(settings.automatic) + { + desired[extensionColumn]=std::clamp(static_cast(extensionLength)+2,4L,14L); + for(const auto column:{sizeColumn,allocationColumn,linkColumn,ownerColumn}) + { + const auto limit=column==ownerColumn?20L:16L; + desired[column]=std::max(fixed[column],std::clamp( + static_cast(std::min(panel.longestColumn[column],limit))+2,minimum[column],limit)); + } + } + constexpr std::array widePriority{sizeColumn,dateColumn,extensionColumn,ownerColumn,allocationColumn,linkColumn}; + constexpr std::array fullPriority{sizeColumn,allocationColumn,linkColumn,ownerColumn,dateColumn,extensionColumn}; + const auto &priority=panel.mode==PanelMode::full?fullPriority:widePriority; + std::array widths{}; + auto available=std::max(0L,bounds.right-bounds.left-minimum[nameColumn]*cellWidth); + for(const auto column:priority) + { + if(!(mask&columnMask(column)) || available1;) + { + --index; + columns[index].right=edge; + edge-=widths[index]; + columns[index].left=edge; + } + columns[nameColumn].right=edge; + return columns; +} + +std::optional firstPanelColumnDivider(const Panel &panel,RECT bounds) +{ + if(!hasPanelColumns(panel)) return {}; + const auto columns=panelColumns(panel,bounds); + const auto &size=columns[sizeColumn]; + if(size.left(GetStockObject(DC_BRUSH)); @@ -1294,7 +1436,8 @@ void swapPanels(HWND window) SetWindowLongPtrW(panel.heading,GWLP_ID,140+i); SetWindowLongPtrW(panel.path,GWLP_ID,142+i); SetWindowLongPtrW(panel.selectionSummary,GWLP_ID,154+i); - savePreference(panelModeKeys[i],panel.wide); + savePanelMode(i,panel.mode); + for(size_t mode=1;mode(mode)); savePanelView(i); } notifyFilesPreferences(window); @@ -1351,13 +1494,13 @@ void layout(HWND window,bool activeOnly) int x = i ? middle + 2 : 0; int end = i ? width : middle - 2; place(panels[i].path, x + 5, 4, std::max(0, end - x - 10), textHeight); - int headingHeight=panels[i].wide?textHeight:0; + int headingHeight=detailedPanel(panels[i])?textHeight:0; const int listWidth=std::max(0,end-x-8-scrollBarWidth(panels[i].list)); const bool panelVisible=!terminalVisible && (!quickViewWindow || i==quickViewSource); ShowWindow(panels[i].path,panelVisible?SW_SHOWNA:SW_HIDE); ShowWindow(panels[i].list,panelVisible?SW_SHOWNA:SW_HIDE); place(panels[i].heading,x+5,textHeight+10,listWidth,headingHeight); - ShowWindow(panels[i].heading,panelVisible && panels[i].wide?SW_SHOWNA:SW_HIDE); + ShowWindow(panels[i].heading,panelVisible && detailedPanel(panels[i])?SW_SHOWNA:SW_HIDE); place(panels[i].list, x + 5, textHeight+10+headingHeight,listWidth, std::max(0, panelBottom-textHeight-10-headingHeight)); place(panels[i].selectionSummary,x+8,panelBottom+4,std::max(0,end-x-16),summaryHeight); @@ -2345,7 +2488,7 @@ void showFileDetails(const Panel &panel) return; } auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0); - if(!panel.wide || !showDetails || row<0 || static_cast(row)>=panel.rows.size()) + if(!detailedPanel(panel) || !showDetails || row<0 || static_cast(row)>=panel.rows.size()) { setStatus(panel.view.mask.empty()?L"":L"Filter: "+panel.view.mask); return; @@ -2397,7 +2540,7 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque { if(request.find) return scanFileMatches(request,entriesRead,stop); auto result=std::make_unique(); - auto &[watch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered]=*result; + auto &[watch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata]=*result; const auto &directory=request.directory; const auto &peer=request.peer; if(stop.stop_requested()) @@ -2527,7 +2670,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul auto &peer=request.peer; const auto previousDirectory=samePanelSource(panel,peer,request.ftp)?panel.directory:fs::path{}; const bool sameDirectory=previousDirectory==directory; - auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered]=scan; + auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata]=scan; const bool partial=error==ERROR_CANCELLED; if(!failure.empty()) { @@ -2652,6 +2795,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul panel.filteredMarks=markedPaths; } panel.metadata=std::move(metadata); + panel.columnMetadata=std::move(columnMetadata); } const auto parent=finding?fs::path{}:panelParentPath(directory,!panel.peer && !panel.ftp); const bool hasParent=!parent.empty(); @@ -2727,14 +2871,20 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul return true; } +#include "files_columns_metadata.inl" + std::future> scanDirectoryInBackground(HWND owner,Panel::ScanRequest request, - PanelView view,std::shared_ptr entries,std::stop_token stop) + PanelView view,DWORD columns,std::shared_ptr entries,std::stop_token stop) { std::packaged_task()> task( - [request=std::move(request),view=std::move(view),entries=std::move(entries),stop] + [request=std::move(request),view=std::move(view),columns,entries=std::move(entries),stop] { auto result=scanDirectory(request,*entries,stop); - if(result->opened && !request.find) orderDirectoryRows(*result,view); + if(result->opened && !request.find) + { + orderDirectoryRows(*result,view); + if(columns && !request.peer && !request.ftp) readLocalColumnMetadata(*result,columns,stop); + } return result; }); auto future=task.get_future(); @@ -2751,7 +2901,7 @@ void startDirectoryScan(Panel &panel) panel.scanStop=std::stop_source{}; panel.scanEntriesRead=std::make_shared(0); panel.scan=scanDirectoryInBackground(GetParent(panel.list),*panel.scanRequest,panel.view, - panel.scanEntriesRead,panel.scanStop.get_token()); + effectivePanelColumns(panel)&extendedColumnMask,panel.scanEntriesRead,panel.scanStop.get_token()); panel.scanSuperseded=false; if(&panel==&panels[active]) showDirectoryScanProgress(panel); } @@ -2836,6 +2986,18 @@ void updatePanelView(Panel &panel) else open(panel,panel.directory); } +void refreshPanelColumnData(Panel &panel) +{ + if(panel.directory.empty() || panel.peer || panel.ftp || panel.findOrigin || + (panel.scanRequest && panel.scanRequest->find)) return; + if(panel.scanRequest) + { + panel.scanSuperseded=true; + panel.scanStop.request_stop(); + } + else open(panel,panel.directory); +} + void sortPanel(Panel &panel,PanelSort sort) { if(!panelViewAvailable(panel)) return; @@ -2857,6 +3019,7 @@ void togglePanelView(Panel &panel,bool foldersFirst) } void editPanelFilter(HWND owner,Panel &panel); +void editPanelColumns(HWND owner,Panel &panel); void setTreePanelMode(Panel &panel) { @@ -2893,6 +3056,7 @@ void panelViewAction(HWND owner,Panel &panel,int action) else if(action==4 || action==6) togglePanelView(panel,action==4); else if(action==7) setTreePanelMode(panel); else if(action==8) toggleAutomaticPanelSizes(panel); + else if(action==9) editPanelColumns(owner,panel); } LRESULT CALLBACK panelHeadingInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) @@ -2905,7 +3069,7 @@ LRESULT CALLBACK panelHeadingInput(HWND window,UINT message,WPARAM wp,LPARAM lp, GetClientRect(window,&bounds); const auto columns=panelColumns(panel,bounds); const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; - for(size_t i=0;i2) panelViewAction(owner,panels[index],static_cast(row)-3); - else if(row==2) chooseDrive(index); - else setMode(index,row==1); + if(row>4) panelViewAction(owner,panels[index],static_cast(row)-5); + else if(row==4) chooseDrive(index); + else setMode(index,static_cast(row)); } else if(menuIndex==2 && row==3) showFolderShortcuts(panels[active],-1); else if(menuIndex==2 && (row==4 || row==5)) openSelectedText(panels[active],row==5,true); @@ -7040,7 +7204,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT invalidatePanelCursorChange(window,previous); } if(message==WM_LBUTTONUP && GetFocus()==window) restoreCommandFocus(); - if(message==WM_PAINT && hasPanelSizeColumn(panels[index])) + if(message==WM_PAINT && hasPanelColumns(panels[index])) { auto dc=GetDC(window); if(dc) @@ -7068,7 +7232,14 @@ bool loadFilesPreferences(HWND window) std::min(preference(dialogRowTextKey,defaultDialogFramePadding.rowText),maxDialogRowTextPadding)}; loadFileStyles(); loadFolderShortcuts(); - for(int i=0;i<2;++i) panels[i].wide=preference(panelModeKeys[i],defaultWide)!=0; + for(int i=0;i<2;++i) + { + auto &panel=panels[i]; + const auto previous=effectivePanelColumns(panel); + panel.mode=readPanelMode(i); + loadPanelColumns(i); + if(panel.list && ((previous^effectivePanelColumns(panel))&extendedColumnMask)) refreshPanelColumnData(panel); + } sizeWidth=static_cast(std::clamp(preference(L"SizeWidth",defaultSizeWidth),6UL,16UL)); alignExtensions=preference(L"AlignExtensions",defaultAlignExtensions)!=0; showDetails=preference(L"ShowDetails",defaultShowDetails)!=0; @@ -7081,6 +7252,7 @@ bool loadFilesPreferences(HWND window) #include "files_find.inl" #include "files_options.inl" +#include "files_panel_columns_dialog.inl" #include "files_space_analyzer.inl" void openMenu(HWND window, int index) @@ -7101,10 +7273,14 @@ void openMenu(HWND window, int index) if(index==0 || index==4) { const auto &panel=panels[index==4]; - const bool wide=panel.wide; - rows={wide?L" Brief\tCtrl+F1":L"✓ Brief\tCtrl+F1", - wide?L"✓ Wide\tCtrl+F2":L" Wide\tCtrl+F2", - index==0?L" Change drive\tAlt+F1":L" Change drive\tAlt+F2"}; + for(size_t i=0;i(panel.mode)==i?L"✓ ":L" "; + auto label=std::wstring(prefix)+panelModeNames[i]; + if(i<2) label+=i==0?L"\tCtrl+F1":L"\tCtrl+F2"; + rows.push_back(std::move(label)); + } + rows.push_back(index==0?L" Change drive\tAlt+F1":L" Change drive\tAlt+F2"); if(panelViewAvailable(panel)) { constexpr const wchar_t *sortLabels[]{L"Sort by name\tCtrl+F3",L"Sort by extension\tCtrl+F4", @@ -7120,6 +7296,7 @@ void openMenu(HWND window, int index) rows.push_back(panel.view.tree?L" List view\tCtrl+F10":L" Tree view\tCtrl+F10"); rows.push_back(panel.view.automaticSizes?L"✓ Background folder sizes\tCtrl+F11": L" Background folder sizes\tCtrl+F11"); + 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"}; @@ -7158,7 +7335,10 @@ void openMenu(HWND window, int index) } return false; }; - if(index==0 || index==4) {reserve(0,L'B');reserve(1,L'W');reserve(2,L'C');} + if(index==0 || index==4) + { + reserve(0,L'B');reserve(1,L'W');reserve(2,L'M');reserve(3,L'F');reserve(4,L'C'); + } if(index==1) {reserve(0,L'C');reserve(2,L'F');reserve(3,L'X');} if(index==2) {reserve(1,L'V');reserve(2,L'E');} for(size_t i=0;i(&box),2); - const LONG columnX=panelColumns(panel,box)[sizeColumn].left; + const auto columnX=firstPanelColumnDivider(panel,box); box.right+=scrollBarWidth(panel.list); InflateRect(&box,2,2); box.left-=2; @@ -7626,9 +7806,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) InflateRect(&box,-3,-3); FrameRect(dc,&box,border); FillRect(dc,÷r,border); - if(hasPanelSizeColumn(panel)) + if(columnX) { - RECT column{columnX,box.top+1,columnX+1,pathBounds.bottom+6}; + RECT column{*columnX,box.top+1,*columnX+1,pathBounds.bottom+6}; FillRect(dc,&column,border); } } @@ -7685,15 +7865,17 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) RECT lower{bounds.left,middle+1,bounds.right,middle+2}; FillRect(item.hDC,&upper,lineBrush); FillRect(item.hDC,&lower,lineBrush); - if(hasPanelSizeColumn(panel)) + if(hasPanelColumns(panel)) { const auto index=item.CtlID-142; RECT list{}; GetWindowRect(panels[index].list,&list); MapWindowPoints(nullptr,item.hwndItem,reinterpret_cast(&list),2); - const auto x=panelColumns(panel,list)[sizeColumn].left; - RECT column{x,middle,x+1,bounds.bottom}; - FillRect(item.hDC,&column,lineBrush); + if(const auto x=firstPanelColumnDivider(panel,list)) + { + RECT column{*x,middle,*x+1,bounds.bottom}; + FillRect(item.hDC,&column,lineBrush); + } } const bool highlighted=static_cast(item.CtlID)-142==active; if(localNavigationAvailable(panel)) @@ -7728,14 +7910,15 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) return TRUE; } const auto columns=panelColumns(panel,item.rcItem); - constexpr const wchar_t *headings[]{L"Name",L"Ext",L"Size",L"Modified"}; + static_assert(std::size(panelColumnNames)==panelColumnCount); for(size_t i=0;i=columns[i].right) continue; - std::wstring label=headings[i]; + std::wstring label=panelColumnNames[i]; if(i==nameColumn && !panel.view.mask.empty()) label+=L" *"; if(static_cast(panel.view.sort)==i) label+=panel.view.descending?L" ↓":L" ↑"; - paintText(item.hDC,columns[i],label.c_str(),RGB(255,255,0),colors[PanelBlue],i==sizeColumn); + paintText(item.hDC,columns[i],label.c_str(),RGB(255,255,0),colors[PanelBlue], + i==sizeColumn || i==allocationColumn || i==linkColumn); } paintPanelColumnLines(item.hDC,columns); return TRUE; @@ -7950,7 +8133,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } else if(item.CtlID>=130 && item.CtlID<=134) paintMenuLabel(item.hDC,item.rcItem,text,0,foreground,colors[background]); - else if(!folderIndicator.empty() && !panels[item.CtlID-102].wide) + else if(!folderIndicator.empty() && !detailedPanel(panels[item.CtlID-102])) { auto name=item.rcItem, indicator=item.rcItem; indicator.left=std::max(indicator.left,indicator.right-static_cast(folderIndicator.size())*cellWidth-10); @@ -7962,43 +8145,81 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) if(item.CtlID==102 || item.CtlID==103) { const auto &panel=panels[item.CtlID-102]; - if(hasPanelSizeColumn(panel) && !ftpProfileList(panel) && item.itemID(panel.mode)]; + const bool useExtension=extension.left1 && panel.sizes[item.itemID]!=L"Up"; - paintText(item.hDC,extension,showSuffix?suffix.c_str()+1:L"",foreground,rowBackground,true,rowFont); - if(showSuffix) text=path.stem().native(); + auto suffix=useExtension?path.extension().native():std::wstring{}; + if(suffix.size()>1) + { + suffix.erase(suffix.begin()); + text=path.stem().native(); + const auto capacity=static_cast(std::max(1L,(extension.right-extension.left-6)/cellWidth)); + if(suffix.size()>capacity) + { + suffix.resize(capacity-1); + if(!suffix.empty() && suffix.back()>=0xd800 && suffix.back()<=0xdbff) suffix.pop_back(); + suffix+=L'…'; + } + } + else suffix.clear(); + paintText(item.hDC,extension,suffix.c_str(),foreground,rowBackground,true,rowFont); } if(tree) text=treeRowPrefix(panel,path,folder)+text; - auto name=columns[nameColumn]; - if(!separateExtension) name.right=extension.right; - paintText(item.hDC,name,text.c_str(),foreground,rowBackground,false,rowFont); + const auto paintValue=[&](PanelColumn column,const std::wstring &value,bool align) + { + const auto &bounds=columns[column]; + if(bounds.left(std::max(1L,(bounds.right-bounds.left)/cellWidth-2)); + }; + paintValue(nameColumn,text,false); if(date.leftsecond.modified)) swprintf_s(modified,L"%04u-%02u-%02u",unsigned(time->wYear),unsigned(time->wMonth),unsigned(time->wDay)); } - paintText(item.hDC,date,modified,foreground,rowBackground,true,rowFont); + paintValue(dateColumn,modified,true); } - const auto &amount=panel.sizes[item.itemID]; - auto visible=amount; - if(!folderIndicator.empty()) visible=folderIndicator; - else if(amount!=L"Folder" && amount!=L"Up") - visible=formatSize(std::stoull(amount),static_cast(sizeWidth)); - paintText(item.hDC,columns[sizeColumn],visible.c_str(),foreground,rowBackground,true); + const auto &size=columns[sizeColumn]; + if(size.leftsecond; + if(columns[allocationColumn].leftallocated? + formatSize(*extra->allocated,columnCells(allocationColumn)):empty,true); + if(columns[linkColumn].leftlinks?std::to_wstring(*extra->links):empty,true); + if(columns[ownerColumn].leftowner.empty()?extra->owner:empty,false); paintPanelColumnLines(item.hDC,columns); } } @@ -8326,7 +8547,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { hidePicker(); showMenu(false); - if(message.wParam<=VK_F2) setMode(active,message.wParam==VK_F2); + if(message.wParam<=VK_F2) setMode(active,message.wParam==VK_F2?PanelMode::wide:PanelMode::brief); else panelViewAction(window,panels[active],static_cast(message.wParam-VK_F3)); } continue; diff --git a/src/files_options.inl b/src/files_options.inl index 73e0f1f..d6dffc0 100644 --- a/src/files_options.inl +++ b/src/files_options.inl @@ -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(selection)(selection):PanelMode::brief; +} + +void showPanelModeOptions(HWND dialog) +{ + for(int index=0;index<2;++index) + SendDlgItemMessageW(dialog,273+index,CB_SETCURSEL,static_cast(panels[index].mode),0); +} + struct OptionsBaseline { LOGFONTW font=displayFont; @@ -92,7 +107,7 @@ struct OptionsBaseline bool remoteUpdate=ks::lan::remoteUpdateAllowed(); DWORD width=static_cast(sizeWidth), fields=statusFields; bool extensions=alignExtensions, folders=alignFolders, details=showDetails; - std::array wide{panels[0].wide,panels[1].wide}; + std::array 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<(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); diff --git a/src/files_panel_columns_dialog.inl b/src/files_panel_columns_dialog.inl new file mode 100644 index 0000000..ae84363 --- /dev/null +++ b/src/files_panel_columns_dialog.inl @@ -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(i)-1,columns&(1u<(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(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(i)-1)==BST_CHECKED) + draft.visibility|=1u<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(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(&prompt))!=IDOK) return; + if(prompt.draft.visibility==draft.visibility && prompt.draft.automatic==draft.automatic) return; + settings=prompt.draft; + savePanelColumns(static_cast(&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); +} diff --git a/src/files_panel_rows.inl b/src/files_panel_rows.inl index fcd6a2e..5ef9c2b 100644 --- a/src/files_panel_rows.inl +++ b/src/files_panel_rows.inl @@ -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; } diff --git a/src/files_panel_tree.inl b/src/files_panel_tree.inl index 120f0d4..88b4dcc 100644 --- a/src/files_panel_tree.inl +++ b/src/files_panel_tree.inl @@ -26,7 +26,7 @@ void startPendingTreeScans(Panel &panel) try { branch.scan=scanDirectoryInBackground(GetParent(panel.list),std::move(request),panel.view, - std::make_shared(0),branch.stop.get_token()); + effectivePanelColumns(panel)&extendedColumnMask,std::make_shared(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 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); }); diff --git a/src/files_space_analyzer.inl b/src/files_space_analyzer.inl index 26c8217..5b91d4c 100644 --- a/src/files_space_analyzer.inl +++ b/src/files_space_analyzer.inl @@ -33,26 +33,6 @@ std::future readSpaceVolume(const fs::path &folder) return result; } -std::optional 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(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(metadata.AllocationSize.QuadPart); - return {}; -} - struct SpaceAllocation { FolderSize known; From cde7dacffcd9bf65c3ccaec0834eb06f0e142633 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 15:43:10 +0200 Subject: [PATCH 15/61] Browse local ZIP and 7z archives in Files Refs #99 --- CMakeLists.txt | 18 +- FILES-UI.md | 6 + build.ps1 | 4 + cmake/FilesArchiveLibraries.cmake | 103 +++++++++++ package.ps1 | 3 +- resources/files-archive-license.txt | 110 +++++++++++ src/files_archive.cpp | 217 ++++++++++++++++++++++ src/files_archive.h | 33 ++++ src/files_compare.inl | 2 +- src/files_drag_drop.inl | 2 +- src/files_find.inl | 2 +- src/files_folder_shortcuts.inl | 4 +- src/files_main.cpp | 275 ++++++++++++++++++++++------ src/files_path_navigation.inl | 12 +- src/files_space_analyzer.inl | 2 +- src/files_win32_directory.h | 25 +++ tests/files_archive.cpp | 150 +++++++++++++++ 17 files changed, 899 insertions(+), 69 deletions(-) create mode 100644 cmake/FilesArchiveLibraries.cmake create mode 100644 resources/files-archive-license.txt create mode 100644 src/files_archive.cpp create mode 100644 src/files_archive.h create mode 100644 tests/files_archive.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 1b47474..10f82df 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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$<$: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 "$") 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" "$/dictionaries") install(DIRECTORY dictionaries DESTINATION .) diff --git a/FILES-UI.md b/FILES-UI.md index 079c4b6..79d1e5c 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -627,6 +627,12 @@ Warning і початковий фокус на No. панелі, результати пошуку й віртуальні елементи Explorer без локального шляху не підтримують перетягування. Files повідомляє причину в рядку стану. +## Архіви ZIP і 7z + +- Enter на локальному архіві відкриває його в поточній панелі. Заголовок панелі починається з Read-only і містить ім’я архіву та шлях усередині нього. Enter відкриває папки всередині архіву, а рядок `..`, Alt+Up і Escape піднімають на один рівень. Вихід із кореня повертає курсор на архів. +- F3 відкриває текстовий файл у спільному переглядачі. F5 копіює позначені записи або поточний запис у локальну папку через спільні діалоги Copy, конфлікту та прогресу. F4, F6, F7 і F8 не змінюють вміст архіву. +- Небезпечні шляхи й посилання блокують читання архіву. Для зашифрованих записів та архівів із зашифрованими заголовками Files показує підказку про пароль. + ## Діалог Copy - Вирівнюй підпис Existing files по вертикальному центру списку. Ширше поле списку починається ближче до підпису, а його правий край збігається з правим краєм поля імені. diff --git a/build.ps1 b/build.ps1 index 4c63f65..dee2ca7 100644 --- a/build.ps1 +++ b/build.ps1 @@ -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 diff --git a/cmake/FilesArchiveLibraries.cmake b/cmake/FilesArchiveLibraries.cmake new file mode 100644 index 0000000..fa5e490 --- /dev/null +++ b/cmake/FilesArchiveLibraries.cmake @@ -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 --config "${config}" + INSTALL_COMMAND "${CMAKE_COMMAND}" --install --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 "$") + 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) diff --git a/package.ps1 b/package.ps1 index 16d986e..2ddbd39 100644 --- a/package.ps1 +++ b/package.ps1 @@ -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()} diff --git a/resources/files-archive-license.txt b/resources/files-archive-license.txt new file mode 100644 index 0000000..a0950a2 --- /dev/null +++ b/resources/files-archive-license.txt @@ -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 +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 + jloup@gzip.org madler@alumni.caltech.edu + +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. diff --git a/src/files_archive.cpp b/src/files_archive.cpp new file mode 100644 index 0000000..a6c562e --- /dev/null +++ b/src/files_archive.cpp @@ -0,0 +1,217 @@ +#include "files_archive.h" +#include "files_win32_directory.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +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; +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(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 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;start255 || !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((seconds+epochOffset)*ticksPerSecond+archive_entry_mtime_nsec(entry)/100):0; + return {relative,{static_cast(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 +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 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(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) || + written!=static_cast(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(entry.modified),static_cast(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 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 &selection, + const fs::path &staging,const ArchiveProgress &progress) +{ + const std::set 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."); +} +} diff --git a/src/files_archive.h b/src/files_archive.h new file mode 100644 index 0000000..832f3aa --- /dev/null +++ b/src/files_archive.h @@ -0,0 +1,33 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +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; +using ArchiveProgress=std::function; + +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 &selection,const std::filesystem::path &staging, + const ArchiveProgress &progress); +} diff --git a/src/files_compare.inl b/src/files_compare.inl index f6b34e8..0518253 100644 --- a/src/files_compare.inl +++ b/src/files_compare.inl @@ -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(); diff --git a/src/files_drag_drop.inl b/src/files_drag_drop.inl index 065f760..b8ff59d 100644 --- a/src/files_drag_drop.inl +++ b/src/files_drag_drop.inl @@ -13,7 +13,7 @@ std::optional 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) diff --git a/src/files_find.inl b/src/files_find.inl index d561864..a7a7e47 100644 --- a/src/files_find.inl +++ b/src/files_find.inl @@ -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; diff --git a/src/files_folder_shortcuts.inl b/src/files_folder_shortcuts.inl index 9369691..c67ca9b 100644 --- a/src/files_folder_shortcuts.inl +++ b/src/files_folder_shortcuts.inl @@ -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(group.size())-1); SetFocus(GetDlgItem(dialog,shortcutList)); return TRUE; diff --git a/src/files_main.cpp b/src/files_main.cpp index 7f56d94..291e149 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -27,6 +27,7 @@ #include #include #include "files_terminal.h" +#include "files_archive.h" #include "files_win32_directory.h" #include "files_command_completion.h" #include "files_text_window.h" @@ -53,6 +54,7 @@ using ks::lan::Json; using ks::lan::fileRequest; using ks::lan::filePath; using ks::lan::checkFileReply; +using ks::files::validFileName; struct FileInfo { @@ -483,6 +485,12 @@ struct DirectoryRow bool folder{}; }; +struct ArchiveLocation +{ + fs::path file; + std::shared_ptr entries; +}; + struct Panel { HWND path{}, list{}, heading{}; @@ -490,6 +498,7 @@ struct Panel LocalNavigation navigation; std::optional peer; std::optional ftp; + std::optional archive; struct DirectoryWatch { HANDLE handle=INVALID_HANDLE_VALUE; @@ -540,6 +549,7 @@ struct Panel std::optional ftp; std::optional find; std::optional navigationPosition; + std::optional archive; }; struct ScanResult { @@ -552,6 +562,7 @@ struct Panel fs::path ftpInitialDirectory; std::vector ordered; ColumnMetadataMap columnMetadata; + std::shared_ptr archiveEntries; }; struct TreeBranch { @@ -620,6 +631,11 @@ bool hasPanelColumns(const Panel &panel) std::wstring panelCaption(const Panel &panel) { + if(panel.archive) + { + const auto display=panel.directory.lexically_relative(panel.archive->file.parent_path()); + return L"Read-only · "+display.native(); + } return panel.findOrigin?L"Search results":panelLocation(panel); } @@ -1989,7 +2005,7 @@ void copyPanelNames(HWND owner) void copyPanelFiles(HWND owner,const Panel &panel) { - if(panel.peer || panel.ftp) + if(panel.peer || panel.ftp || panel.archive) { setStatus(L"File clipboard copy requires local files."); return; @@ -2033,13 +2049,15 @@ void copyCommandLineOrPanelNames(HWND owner) } void startFileSearch(Panel &panel,Panel::FindOptions options); +void refreshArchive(Panel &panel); void refreshPanel(Panel &panel) { cancelFolderSizes(panel); if(!panel.view.automaticSizes) panel.folderSizes.clear(); updateSelectionSummary(panel); - if(panel.findOrigin) startFileSearch(panel,panel.findOrigin->options); + if(panel.archive) refreshArchive(panel); + else if(panel.findOrigin) startFileSearch(panel,panel.findOrigin->options); else open(panel,panel.directory,false); } @@ -2058,7 +2076,7 @@ std::wstring powerShellPath(const fs::path &path) void insertCurrentPanelPath(bool nameOnly = false) { const auto &panel=panels[active]; - if(panel.ftp) return; + if(panel.ftp || panel.archive) return; const auto row=currentPanelRow(panel); if(row==LB_ERR) return; const bool up=panel.sizes[row]==L"Up"; @@ -2182,6 +2200,7 @@ bool startTerminal(HWND owner,const fs::path &directory) bool showCommandOutput(HWND owner,const Panel &panel) { + if(panel.archive) return startTerminal(owner,panel.archive->file.parent_path()); return panel.peer || panel.ftp?ensureTerminalView(owner):startTerminal(owner,panel.directory); } @@ -2214,6 +2233,11 @@ void appendTerminalOutput(std::string_view output) bool submitTerminalCommand(const Panel &panel,const std::wstring &value) { const auto owner=GetParent(panel.list); + if(panel.archive) + { + setStatus(L"Shell commands require a local or LAN folder."); + return false; + } if(panel.ftp) { setStatus(L"Shell commands are unavailable in FTP panels."); @@ -2540,7 +2564,7 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque { if(request.find) return scanFileMatches(request,entriesRead,stop); auto result=std::make_unique(); - auto &[watch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata]=*result; + auto &[watch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=*result; const auto &directory=request.directory; const auto &peer=request.peer; if(stop.stop_requested()) @@ -2548,6 +2572,40 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque error=ERROR_CANCELLED; return result; } + if(request.archive) + { + try + { + const auto &source=*request.archive; + archiveEntries=source.entries?source.entries: + std::make_shared(ks::files::readArchive(source.file,stop)); + const auto inner=directory.lexically_relative(source.file); + const auto relative=inner==L"."?fs::path{}:inner; + if(!relative.empty()) + { + const auto member=archiveEntries->find(relative); + if(member==archiveEntries->end() || !member->second.directory) + throw std::runtime_error("This folder is no longer present in the archive."); + } + for(const auto &[path,entry]:*archiveEntries) + { + if(stop.stop_requested()) {error=ERROR_CANCELLED; return result;} + if(path.parent_path()!=relative) continue; + const auto child=source.file/path; + const DWORD attributes=entry.directory?FILE_ATTRIBUTE_DIRECTORY:FILE_ATTRIBUTE_NORMAL; + metadata.emplace(child,FolderEntryMetadata{attributes,entry.size,entry.modified}); + (entry.directory?folders:files).push_back(child); + } + opened=true; + } + catch(const std::system_error &e) + { + if(e.code().value()==ERROR_CANCELLED) error=ERROR_CANCELLED; + else failure=fileError(e); + } + catch(const std::exception &e) {failure=ks::wide(e.what());} + return result; + } if(request.ftp) { if(!request.ftp->name.empty()) @@ -2670,7 +2728,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul auto &peer=request.peer; const auto previousDirectory=samePanelSource(panel,peer,request.ftp)?panel.directory:fs::path{}; const bool sameDirectory=previousDirectory==directory; - auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata]=scan; + auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=scan; const bool partial=error==ERROR_CANCELLED; if(!failure.empty()) { @@ -2763,7 +2821,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul panel.listReturnMarks.clear(); } if(peer || request.ftp) panel.navigation={}; - else if(!finding) + else if(!finding && !request.archive) { panel.navigation.opened(directory,request.navigationPosition); if(!sameDirectory && !panel.directory.empty() && !partial) updateRecentFolders(directory,true); @@ -2771,19 +2829,21 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul panel.directory = directory; panel.peer=std::move(peer); panel.ftp=std::move(request.ftp); + panel.archive=std::move(request.archive); + if(panel.archive) panel.archive->entries=std::move(archiveEntries); if(!sameDirectory) { cancelFolderSizes(panel); panel.folderSizes.clear(); } - if(partial || finding) panel.watch.reset(); + if(partial || finding || panel.archive) panel.watch.reset(); else if(!sameDirectory || panel.watch.handle==INVALID_HANDLE_VALUE) { panel.watch.reset(); std::swap(panel.watch.handle,nextWatch.handle); } const bool profiles=ftpProfileList(panel); - const bool renderTree=panel.view.tree && !finding && !profiles; + const bool renderTree=panel.view.tree && !finding && !profiles && !panel.archive; panel.filteredMarks.clear(); if(renderTree) replaceTreeRoot(panel,scan,sameDirectory,markedPaths); else @@ -2797,7 +2857,8 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul panel.metadata=std::move(metadata); panel.columnMetadata=std::move(columnMetadata); } - const auto parent=finding?fs::path{}:panelParentPath(directory,!panel.peer && !panel.ftp); + const auto parent=finding?fs::path{}:panel.archive?directory.parent_path(): + panelParentPath(directory,!panel.peer && !panel.ftp); const bool hasParent=!parent.empty(); const auto rowCount=profiles?ftpProfiles.size():finding?files.size(): renderTree?panel.tree.branches.at(panel.tree.root).ordered.size()+hasParent:ordered.size()+hasParent; @@ -2867,7 +2928,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul else if(!partial && error!=ERROR_SUCCESS && error!=ERROR_NO_MORE_FILES && error!=ERROR_FILE_NOT_FOUND) setStatus(L"Some entries could not be read."); else if(updateDetails && &panel==&panels[active]) showFileDetails(panel); - if(!finding && !profiles) queueAutomaticPanelSizes(panel,true); + if(!finding && !profiles && !panel.archive) queueAutomaticPanelSizes(panel,true); return true; } @@ -2883,7 +2944,7 @@ std::future> scanDirectoryInBackground(HWND o if(result->opened && !request.find) { orderDirectoryRows(*result,view); - if(columns && !request.peer && !request.ftp) readLocalColumnMetadata(*result,columns,stop); + if(columns && !request.peer && !request.ftp && !request.archive) readLocalColumnMetadata(*result,columns,stop); } return result; }); @@ -2908,7 +2969,7 @@ void startDirectoryScan(Panel &panel) void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional peer, fs::path selection={},fs::path fallback={},std::optional ftp={}, - std::optional navigationPosition={}) + std::optional navigationPosition={},std::optional archive={}) { if(directory.empty() && !ftp) return; if(!panel.view.revealedFile.empty() && @@ -2916,7 +2977,7 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti if(directory!=panel.directory || !samePanelSource(panel,peer,ftp)) cancelFolderSizes(panel); panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback), - std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition}; + std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition,std::move(archive)}; if(panel.scan.valid()) { panel.scanSuperseded=true; @@ -2962,7 +3023,19 @@ void collectDirectoryScans() void open(Panel &panel,const fs::path &directory,bool offerElevation=false) { - openOn(panel,directory,offerElevation,panel.peer,{},{},panel.ftp); + openOn(panel,directory,offerElevation,panel.peer,{},{},panel.ftp,{},panel.archive); +} + +void refreshArchive(Panel &panel) +{ + openOn(panel,panel.directory,false,{},{},{},{},{},ArchiveLocation{panel.archive->file,{}}); +} + +void parentArchive(Panel &panel) +{ + if(panel.directory==panel.archive->file) + openOn(panel,panel.directory.parent_path(),false,{},panel.archive->file); + else open(panel,panel.directory.parent_path()); } #include "files_panel_tree.inl" @@ -2988,7 +3061,7 @@ void updatePanelView(Panel &panel) void refreshPanelColumnData(Panel &panel) { - if(panel.directory.empty() || panel.peer || panel.ftp || panel.findOrigin || + if(panel.directory.empty() || panel.peer || panel.ftp || panel.findOrigin || panel.archive || (panel.scanRequest && panel.scanRequest->find)) return; if(panel.scanRequest) { @@ -3023,7 +3096,7 @@ void editPanelColumns(HWND owner,Panel &panel); void setTreePanelMode(Panel &panel) { - if(!panelViewAvailable(panel)) return; + if(panel.archive || !panelViewAvailable(panel)) return; if(!panel.view.tree) { panel.view.tree=true; @@ -3042,7 +3115,7 @@ void setTreePanelMode(Panel &panel) void toggleAutomaticPanelSizes(Panel &panel) { - if(!panelViewAvailable(panel)) return; + if(panel.archive || !panelViewAvailable(panel)) return; panel.view.automaticSizes=!panel.view.automaticSizes; savePanelView(static_cast(&panel-panels)); if(panel.view.automaticSizes) queueAutomaticPanelSizes(panel,true); @@ -3149,7 +3222,7 @@ bool calculateFolderSizes(Panel &panel,LRESULT current) bool queueFolderMeasurements(Panel &panel,const std::vector &folders,bool foreground) { - if(folders.empty()) return false; + if(folders.empty() || panel.archive) return false; if(const auto running=panel.folderSizeJob) { bool queued=false; @@ -3976,7 +4049,7 @@ void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb void openSelectedWithSystem(const Panel &panel) { - if(panel.ftp) return; + if(panel.ftp || panel.archive) return; const auto row=currentPanelRow(panel); if(row==LB_ERR) return; if(panel.peer) @@ -4006,7 +4079,7 @@ void refreshQuickView(const Panel &panel) { if(!quickViewWindow || &panel!=&panels[quickViewSource]) return; const auto row=currentPanelRow(panel); - const bool file=!panel.peer && !panel.ftp && row!=LB_ERR && + const bool file=!panel.peer && !panel.ftp && !panel.archive && row!=LB_ERR && panel.sizes[row]!=L"Folder" && panel.sizes[row]!=L"Up"; ks::files::previewQuickViewFile(quickViewWindow,file?panel.rows[row]:fs::path{}); } @@ -4021,7 +4094,7 @@ void toggleQuickView(HWND owner) return; } const auto &panel=panels[active]; - if(panel.peer || panel.ftp || terminalVisible) + if(panel.peer || panel.ftp || panel.archive || terminalVisible) { setStatus(L"Quick View requires a visible local file pane."); return; @@ -4051,11 +4124,39 @@ bool handleQuickViewKey(HWND window,const MSG &message) ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile); +void openArchiveText(const Panel &panel,const fs::path &path) +{ + const auto file=panel.archive->file; + const auto member=path.lexically_relative(file); + const auto found=panel.archive->entries->find(member); + if(found==panel.archive->entries->end() || found->second.directory) return; + if(found->second.encrypted) + { + setStatus(L"This archive entry requires a password. Password-protected entries cannot be opened in Files."); + return; + } + const ks::files::RemoteTextSource archive{ + "archive:"+ks::utf8(file.native()),file.filename().native(), + [file](const fs::path &original,const fs::path &cache,bool,const ks::files::ArchiveProgress &progress,uint64_t limit) + { + const auto relative=original.lexically_relative(file); + const auto entry=ks::files::readArchiveMember(file,relative,cache,limit,progress); + return ks::files::RemoteTextRevision{entry.size,entry.modified,false}; + },{}}; + ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive); +} + void openSelectedText(const Panel &panel, bool edit, bool external) { if(ftpProfileList(panel)) return; const auto row=currentPanelRow(panel); if(row==LB_ERR || panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") return; + if(panel.archive) + { + if(edit || external) setStatus(L"Archive entries are read-only. Use F5 to extract them."); + else openArchiveText(panel,panel.rows[row]); + return; + } if((panel.peer || panel.ftp) && external) { setStatus(L"Copy the remote file to a local panel before opening it."); @@ -4086,6 +4187,13 @@ void enter(Panel &panel) return; } auto target = panel.rows[row]; + if(panel.archive) + { + if(panel.sizes[row]==L"Up") parentArchive(panel); + else if(panel.sizes[row]==L"Folder") open(panel,target); + else openArchiveText(panel,target); + return; + } if(panel.findOrigin) { revealLocalFile(panel,target); @@ -4094,6 +4202,8 @@ void enter(Panel &panel) if(panel.sizes[row]==L"Folder" && toggleTreeRow(panel,static_cast(row))) return; if(panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") open(panel,target,true); else if(panel.ftp) openSelectedText(panel,false,false); + else if(!panel.peer && ks::files::isArchivePath(target)) + openOn(panel,target,false,{},{},{},{},{},ArchiveLocation{target,{}}); else openPanelFile(panel, target, nullptr, L"Cannot open the selected file."); } } @@ -4119,7 +4229,7 @@ struct CopyRequest std::future validation; std::wstring ftpDestination; bool upload{}; - bool ftpRename{}, externalSources{}; + bool ftpRename{}, externalSources{}, archiveSource{}; }; bool directoryExists(const FilesPeer *peer,const fs::path &path) @@ -4645,32 +4755,13 @@ void installFarCheckbox(HWND field,FarCheckboxSurface surface) SetWindowSubclass(field,paintFarCheckbox,1,static_cast(surface)); } -bool validFileName(std::wstring_view name) -{ - return !name.empty() && name.back()!=L'.' && name.back()!=L' ' && - name.find_first_of(L"<>:\"/\\|?*")==name.npos && - std::none_of(name.begin(),name.end(),[](wchar_t ch){return ch<32;}); -} - bool validFtpCopyName(std::wstring_view name,bool upload) { if(upload) return !name.empty() && name!=L"." && name!=L".." && name.find_first_of(L"/\\:\r\n") == name.npos && std::none_of(name.begin(),name.end(),[](wchar_t ch){return ch<32;}); - if(!validFileName(name)) return false; - auto stem=name.substr(0,name.find(L'.')); - stem=stem.substr(0,stem.find_last_not_of(L' ')+1); - const auto equals=[&](std::wstring_view device) - { - return CompareStringOrdinal(stem.data(),static_cast(stem.size()), - device.data(),static_cast(device.size()),TRUE)==CSTR_EQUAL; - }; - for(const auto device:{L"CON",L"PRN",L"AUX",L"NUL",L"CONIN$",L"CONOUT$"}) - if(equals(device)) return false; - return stem.size()!=4 || std::wstring_view(L"123456789¹²³").find(stem.back())==name.npos || - (CompareStringOrdinal(stem.data(),3,L"COM",3,TRUE)!=CSTR_EQUAL && - CompareStringOrdinal(stem.data(),3,L"LPT",3,TRUE)!=CSTR_EQUAL); + return ks::files::validWindowsFileName(name); } void drawFarComboRow(const DRAWITEMSTRUCT &item) @@ -4734,14 +4825,14 @@ CopyDestination validateCopyDestination(CopyRequest request,const std::wstring & else if(request.sources.size()==1) { const auto &name=value; - if(!validFileName(name)) + if(request.archiveSource?!ks::files::validWindowsFileName(name):!validFileName(name)) throw std::runtime_error(ks::utf8(L"Enter a valid name for the copy.")); if(CompareStringOrdinal(name.c_str(),-1,request.sources.front().filename().c_str(),-1,TRUE)!=CSTR_EQUAL) request.newName=name; else request.newName.clear(); } const auto sourceDirectory=request.sources.front().parent_path(); - const bool renameInSource=!request.externalSources && !request.move && !request.newName.empty(); + const bool renameInSource=!request.externalSources && !request.archiveSource && !request.move && !request.newName.empty(); const auto destination=renameInSource?sourceDirectory:request.destination; std::error_code error; const auto peer=renameInSource?request.sourcePeer:request.destinationPeer; @@ -4903,6 +4994,7 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) snapshot.ftpDestination=request.ftpDestination; snapshot.upload=request.upload; snapshot.externalSources=request.externalSources; + snapshot.archiveSource=request.archiveSource; std::packaged_task validation( [snapshot=std::move(snapshot),value=std::move(value), source=peer(request.sourcePeer),other=peer(request.otherPeer)]() mutable { @@ -5964,11 +6056,47 @@ void pruneSearchResults(Panel &panel,const std::set &removed) updateSelectionSummary(panel); } +struct ArchiveStaging +{ + fs::path directory; + + void create() + { + GUID id{}; + wchar_t name[40]{}; + if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40)) + throw std::runtime_error("Could not create temporary storage for archive entries."); + const auto path=fs::temp_directory_path()/(L"ks-files-archive-"+std::wstring(name)); + if(!fs::create_directory(path)) throw std::runtime_error("Could not create temporary storage for archive entries."); + directory=path; + } + + ~ArchiveStaging() + { + if(directory.empty()) return; + std::error_code error; + fs::remove_all(directory,error); + } +}; + void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::vector external={}, fs::path targetFolder={}) { const auto sourceFtp=source.ftp; const bool ftpRename=move && sourceFtp && !ftpProfileList(source); + const auto archive=source.archive?source.archive->file:fs::path{}; + auto archiveDirectory=archive.empty()?fs::path{}:source.directory.lexically_relative(archive); + if(archiveDirectory==L".") archiveDirectory.clear(); + if(destination.archive || (!archive.empty() && move)) + { + setStatus(L"Archive entries are read-only. Use F5 to extract them to a local folder."); + return; + } + if(!archive.empty() && (destination.peer || destination.ftp)) + { + setStatus(L"Open a local destination folder to extract archive entries."); + return; + } if(quickViewWindow && &destination!=&panels[quickViewSource] && !ftpRename) { setStatus(L"Close Quick View to use the destination pane."); @@ -6003,6 +6131,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve request.move=move; request.ftpRename=ftpRename; request.externalSources=!external.empty(); + request.archiveSource=!archive.empty(); if(ftp) { request.ftpDestination=panelLocation(destination); @@ -6024,7 +6153,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve if(result!=IDOK) return; const bool renamed=!request.newName.empty(); - const bool renameInSource=renamed && !move && !ftp && !request.externalSources; + const bool renameInSource=renamed && !move && !ftp && !request.externalSources && archive.empty(); const auto targetDirectory=renameInSource?request.sources.front().parent_path():request.destination; const auto *targetPeer=renameInSource?request.sourcePeer:request.destinationPeer; const auto peerId=[](const FilesPeer *peer){return peer?peer->id:std::string{};}; @@ -6056,7 +6185,26 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve { progress.ui.run(progress.window,progress.canceled,[&] { FileOperationElevation elevation(progress.window,progress.canceled,&progress.ui); - auto *admin=!ftp && !request.sourcePeer && !targetPeer?&elevation:nullptr; + auto *admin=archive.empty() && !ftp && !request.sourcePeer && !targetPeer?&elevation:nullptr; + ArchiveStaging staging; + auto sources=request.sources; + if(!archive.empty()) + { + staging.create(); + std::vector selection; + for(auto &path:sources) + { + selection.push_back(path.lexically_relative(archive)); + path=staging.directory/path.filename(); + } + progress.from=archive; + progress.to=targetDirectory; + ks::files::extractArchiveSelection(archive,archiveDirectory,selection,staging.directory,[&](uint64_t done,uint64_t total) + { + reportCopyProgress(progress,done,total); + return !progress.canceled; + }); + } CopyHost sourceHost(request.sourcePeer,sourceFtp,admin); if(ftpRename) { @@ -6082,12 +6230,13 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve const CopyEndpoints hosts{sourceHost,otherHost?*otherHost:sourceHost,sameHost, request.sourcePeer?request.sourcePeer->id:"local",!request.sourcePeer && !sourceFtp, !targetPeer && !destinationFtp}; - for(const auto &path:request.sources) + for(const auto &path:sources) if(!countCopy(sourceHost,path,progress)) { failed=true; break; } reportCopyProgress(progress,0,0,true); - for(const auto &path:request.sources) + for(size_t i=0;ifile.parent_path():panels[i].directory).native(); if(!panels[i].peer && !panels[i].ftp && !path.empty()) RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelPathKeys[i],REG_SZ,path.c_str(), static_cast((path.size()+1)*sizeof(wchar_t))); const auto row=SendMessageW(panels[i].list,LB_GETCURSEL,0,0); - const auto cursor=row>=0 && static_cast(row)file.native(): + row>=0 && static_cast(row)((cursor.size()+1)*sizeof(wchar_t))); } @@ -8420,11 +8576,16 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) (message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list)) { auto &panel=panels[active]; - if(panel.scanRequest && panel.scanRequest->find) + if(panel.scanRequest && (panel.scanRequest->find || panel.scanRequest->archive)) { if(!panel.scanSuperseded) stopDirectoryScan(); continue; } + if(panel.archive && !panel.scanRequest) + { + parentArchive(panel); + continue; + } if(panel.findOrigin && !panel.scanRequest) { openOn(panel,panel.directory,false,{}); diff --git a/src/files_path_navigation.inl b/src/files_path_navigation.inl index 3415f20..97273bb 100644 --- a/src/files_path_navigation.inl +++ b/src/files_path_navigation.inl @@ -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)) { diff --git a/src/files_space_analyzer.inl b/src/files_space_analyzer.inl index 5b91d4c..cf55aaa 100644 --- a/src/files_space_analyzer.inl +++ b/src/files_space_analyzer.inl @@ -608,7 +608,7 @@ INT_PTR CALLBACK spaceAnalyzerDialog(HWND dialog,UINT message,WPARAM wp,LPARAM l void openSpaceAnalyzer(HWND owner,Panel &panel) { - if(panel.peer || panel.ftp || panel.directory.empty()) + if(panel.peer || panel.ftp || panel.archive || panel.directory.empty()) { setStatus(L"Space Analyzer requires an open local folder."); return; diff --git a/src/files_win32_directory.h b/src/files_win32_directory.h index 80f838a..da55ed8 100644 --- a/src/files_win32_directory.h +++ b/src/files_win32_directory.h @@ -1,12 +1,37 @@ #pragma once #include +#include #include #include #include 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(stem.size()), + device.data(),static_cast(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 DWORD visitDirectoryRecords(HANDLE directory,const Visitor &visit) { diff --git a/tests/files_archive.cpp b/tests/files_archive.cpp new file mode 100644 index 0000000..c83e060 --- /dev/null +++ b/tests/files_archive.cpp @@ -0,0 +1,150 @@ +#include "files_archive.h" +#include +#include +#include +#include +#include +#include +#include + +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 &members,bool sevenZip=false,bool encrypted=false) +{ + std::unique_ptr 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 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(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(in),std::istreambuf_iterator()}; +} + +template +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< Date: Wed, 25 Nov 2026 15:56:01 +0200 Subject: [PATCH 16/61] 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)< Date: Wed, 25 Nov 2026 16:12:12 +0200 Subject: [PATCH 17/61] Preview images in Files Viewer and Quick View Refs #101 --- CMakeLists.txt | 18 +- FILES-UI.md | 10 +- build.ps1 | 4 + cmake/FilesImageLibraries.cmake | 25 ++ package.ps1 | 3 +- resources/files-image-license.txt | 56 ++++ src/files_image_decode.cpp | 157 ++++++++++ src/files_image_decode.h | 19 ++ src/files_image_view.cpp | 459 ++++++++++++++++++++++++++++++ src/files_image_view.h | 21 ++ src/files_main.cpp | 54 +++- src/files_text_window.cpp | 60 +++- src/files_text_window.h | 4 + tests/files_image.cpp | 172 +++++++++++ 14 files changed, 1046 insertions(+), 16 deletions(-) create mode 100644 cmake/FilesImageLibraries.cmake create mode 100644 resources/files-image-license.txt create mode 100644 src/files_image_decode.cpp create mode 100644 src/files_image_decode.h create mode 100644 src/files_image_view.cpp create mode 100644 src/files_image_view.h create mode 100644 tests/files_image.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 10f82df..ddf59cf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,6 +14,7 @@ set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-compare.ico") include(cmake/FilesTextLibraries.cmake) include(cmake/FilesArchiveLibraries.cmake) +include(cmake/FilesImageLibraries.cmake) set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files") target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00) find_program(KSWITCHER_POWERSHELL NAMES pwsh powershell REQUIRED) @@ -33,7 +34,7 @@ add_custom_target(check-files-quick-view DEPENDS KSwitcherFiles VERBATIM) target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include") -target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet) +target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet KSwitcherFilesImage) if(MSVC) target_compile_options(KSwitcherFiles PRIVATE /utf-8) else() @@ -165,6 +166,17 @@ elseif(MINGW) target_link_options(KSwitcherFilesArchiveTests PRIVATE -static) endif() add_test(NAME files-archive COMMAND KSwitcherFilesArchiveTests) +add_executable(KSwitcherFilesImageTests tests/files_image.cpp) +target_include_directories(KSwitcherFilesImageTests PRIVATE src) +target_compile_definitions(KSwitcherFilesImageTests PRIVATE NOMINMAX) +target_link_libraries(KSwitcherFilesImageTests PRIVATE KSwitcherFilesImage webp) +if(MSVC) + set_property(TARGET KSwitcherFilesImageTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + target_compile_options(KSwitcherFilesImageTests PRIVATE /utf-8) +elseif(MINGW) + target_link_options(KSwitcherFilesImageTests PRIVATE -static) +endif() +add_test(NAME files-image COMMAND KSwitcherFilesImageTests) add_executable(KSwitcherFilesModalTests tests/files_modal_dialog.cpp) target_include_directories(KSwitcherFilesModalTests PRIVATE src) target_link_libraries(KSwitcherFilesModalTests PRIVATE user32 comctl32) @@ -227,7 +239,7 @@ if(KSWITCHER_NODE) src/files_text_window.cpp src/files_text_document.cpp src/files_text_language.cpp resources/files.rc) target_include_directories(KSwitcherFilesMarkdownLanFixture PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include") - target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText) + target_link_libraries(KSwitcherFilesMarkdownLanFixture PRIVATE kscore KSwitcherFilesText KSwitcherFilesImage) add_dependencies(KSwitcherFilesMarkdownLanFixture KSwitcherTerminalAssets) if(MSVC) set_property(TARGET KSwitcherFilesMarkdownLanFixture PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") @@ -331,7 +343,7 @@ add_test(NAME screenshot-save-regressions COMMAND KSwitcherScreenshotUITests --s add_test(NAME updater-regressions COMMAND powershell.exe -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/update.ps1" -Executable "$") 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 resources/files-archive-license.txt DESTINATION .) +install(FILES LICENSE vendor/json-LICENSE.txt resources/files-archive-license.txt resources/files-image-license.txt DESTINATION .) add_custom_command(TARGET KSwitcher POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/dictionaries" "$/dictionaries") install(DIRECTORY dictionaries DESTINATION .) diff --git a/FILES-UI.md b/FILES-UI.md index 061527e..a4570bb 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -557,10 +557,18 @@ Warning і початковий фокус на No. - Клік у панелі нижче списку ставить курсор на останній рядок, а клік вище списку — на перший. - **Commands → Quick View** або **Ctrl+Q** вмикає перегляд локального - тексту й Markdown у сусідній панелі. Перегляд слідує за курсором активної + тексту, Markdown і зображень у сусідній панелі. Перегляд слідує за курсором активної панелі. Повторна команда повертає сусідній каталог, курсор і позначки. Під час перегляду файлові операції з призначенням у сусідній панелі пропонують спершу закрити Quick View. +- **F3** відкриває PNG, JPEG, GIF, WebP і BMP у Viewer. Стрілки вліво й + вправо, Page Up і Page Down та кнопки Previous і Next гортають видимі + зображення в порядку вихідної панелі на момент відкриття Viewer. +- У Viewer і Quick View коліщатко та кнопки − і + змінюють масштаб, + перетягування мишею панорамує збільшене зображення, Fit підганяє його + під область перегляду, а 100% повертає вихідний масштаб. Клавіші 0 і 1 + виконують Fit і 100% у сфокусованому перегляді. GIF та анімований WebP + показують перший кадр. Пошкоджені та надто великі файли показують повідомлення. - **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує останні відвідані локальні папки. Повторний візит підіймає один запис diff --git a/build.ps1 b/build.ps1 index dee2ca7..12f68ac 100644 --- a/build.ps1 +++ b/build.ps1 @@ -71,6 +71,10 @@ try { if ($LASTEXITCODE) { throw 'Files archive test build failed' } & (Join-Path $filesBuild 'KSwitcherFilesArchiveTests.exe') if ($LASTEXITCODE) { throw 'Files archive tests failed' } + & cmake --build $filesBuild --target KSwitcherFilesImageTests + if ($LASTEXITCODE) { throw 'Files image test build failed' } + & (Join-Path $filesBuild 'KSwitcherFilesImageTests.exe') + if ($LASTEXITCODE) { throw 'Files image tests failed' } & $compiler @common -Werror tests/settings_merge.cpp build/sync.o @driveObjects build/storage.o build/core.o build/platform.o build/ocr.o @libs -static -s -o build/KSwitcherSettingsMergeTests.exe if ($LASTEXITCODE) { throw 'Settings merge test build failed' } & .\build\KSwitcherSettingsMergeTests.exe diff --git a/cmake/FilesImageLibraries.cmake b/cmake/FilesImageLibraries.cmake new file mode 100644 index 0000000..6ce820d --- /dev/null +++ b/cmake/FilesImageLibraries.cmake @@ -0,0 +1,25 @@ +include(FetchContent) +FetchContent_Declare(files_webp + URL https://storage.googleapis.com/downloads.webmproject.org/releases/webp/libwebp-1.6.0.tar.gz + URL_HASH SHA256=e4ab7009bf0629fd11982d4c2aa83964cf244cffba7347ecd39019a9e38c4564 + DOWNLOAD_EXTRACT_TIMESTAMP FALSE + SOURCE_SUBDIR kswitcher-download-only) +FetchContent_MakeAvailable(files_webp) + +function(build_files_webp) + set(BUILD_SHARED_LIBS OFF) + set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + foreach(component IN ITEMS ANIM_UTILS CWEBP DWEBP GIF2WEBP IMG2WEBP VWEBP WEBPINFO LIBWEBPMUX WEBPMUX EXTRAS) + set(WEBP_BUILD_${component} OFF) + endforeach() + add_subdirectory("${files_webp_SOURCE_DIR}" "${files_webp_BINARY_DIR}" EXCLUDE_FROM_ALL) +endfunction() +build_files_webp() + +add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_view.cpp) +target_compile_definitions(KSwitcherFilesImage PRIVATE NOMINMAX UNICODE _UNICODE _WIN32_WINNT=0x0A00) +target_link_libraries(KSwitcherFilesImage PRIVATE webpdemux windowscodecs msimg32 ole32) +if(MSVC) + set_property(TARGET KSwitcherFilesImage PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") + target_compile_options(KSwitcherFilesImage PRIVATE /utf-8) +endif() diff --git a/package.ps1 b/package.ps1 index 2ddbd39..4dc019a 100644 --- a/package.ps1 +++ b/package.ps1 @@ -13,6 +13,7 @@ Copy-Item -LiteralPath (Join-Path $root 'LICENSE') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'vendor\json-LICENSE.txt') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'resources\files-text-license.txt') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'resources\files-archive-license.txt') -Destination $destination +Copy-Item -LiteralPath (Join-Path $root 'resources\files-image-license.txt') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'README.md') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'LAN-PREVIEW.md') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'dictionaries') -Destination $destination -Recurse -Force @@ -21,7 +22,7 @@ Copy-Item -LiteralPath (Join-Path $root 'resources\portable-tools-README.txt') - Copy-Item -LiteralPath (Join-Path $root 'build\release\tools\StayHere.exe') -Destination (Join-Path $destination 'tools\StayHere.exe') -Force Copy-Item -LiteralPath (Join-Path $root 'utilities\StayHere\README.md') -Destination (Join-Path $destination 'tools\StayHere-README.md') -Force # Enumerate the distributable files explicitly; do not include a user's data directory. -$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','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 $_ } +$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','files-archive-license.txt','files-image-license.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ } $entries = foreach ($path in $files) { foreach ($file in @(Get-ChildItem -LiteralPath $path -File -Recurse)) { @{path=$file.FullName.Substring($destination.Length+1).Replace('\','/'); size=$file.Length; sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant()} diff --git a/resources/files-image-license.txt b/resources/files-image-license.txt new file mode 100644 index 0000000..0829693 --- /dev/null +++ b/resources/files-image-license.txt @@ -0,0 +1,56 @@ +libwebp 1.6.0 +https://developers.google.com/speed/webp + +Copyright (c) 2010, Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of Google nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Additional IP Rights Grant (Patents) +------------------------------------ + +"These implementations" means the copyrightable works that implement the WebM +codecs distributed by Google as part of the WebM Project. + +Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge, +royalty-free, irrevocable (except as stated in this section) patent license to +make, have made, use, offer to sell, sell, import, transfer, and otherwise +run, modify and propagate the contents of these implementations of WebM, where +such license applies only to those patent claims, both currently owned by +Google and acquired in the future, licensable by Google that are necessarily +infringed by these implementations of WebM. This grant does not include claims +that would be infringed only as a consequence of further modification of these +implementations. If you or your agent or exclusive licensee institute or order +or agree to the institution of patent litigation or any other patent +enforcement activity against any entity (including a cross-claim or +counterclaim in a lawsuit) alleging that any of these implementations of WebM +or any code incorporated within any of these implementations of WebM +constitute direct or contributory patent infringement, or inducement of +patent infringement, then any patent rights granted to you under this License +for these implementations of WebM shall terminate as of the date such +litigation is filed. diff --git a/src/files_image_decode.cpp b/src/files_image_decode.cpp new file mode 100644 index 0000000..53cc38f --- /dev/null +++ b/src/files_image_decode.cpp @@ -0,0 +1,157 @@ +#include "files_image_decode.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ks::files +{ +namespace +{ +namespace fs=std::filesystem; +constexpr char invalidImage[]="Could not decode the image. The file may be damaged."; +constexpr char largeImage[]="This image is too large to preview."; + +enum class ImageFormat { unknown, png, jpeg, gif, webp, bmp }; + +ImageFormat imageFormat(const fs::path &path) +{ + const auto extension=path.extension(); + const auto matches=[&](const wchar_t *suffix) + { + return CompareStringOrdinal(extension.c_str(),-1,suffix,-1,TRUE)==CSTR_EQUAL; + }; + if(matches(L".png")) return ImageFormat::png; + if(matches(L".jpg") || matches(L".jpeg") || matches(L".jpe")) return ImageFormat::jpeg; + if(matches(L".gif")) return ImageFormat::gif; + if(matches(L".webp")) return ImageFormat::webp; + if(matches(L".bmp")) return ImageFormat::bmp; + return ImageFormat::unknown; +} + +void checkImage(HRESULT result) +{ + if(FAILED(result)) throw std::runtime_error(invalidImage); +} + +void checkImageDimensions(unsigned width,unsigned height) +{ + if(!width || !height) throw std::runtime_error(invalidImage); + if(width>16384 || height>16384 || uint64_t(width)*height>32ULL*1024*1024) + throw std::runtime_error(largeImage); +} + +void checkImageStop(std::stop_token stop) +{ + if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category()); +} + +template +struct ImagingObject +{ + T *value{}; + ~ImagingObject() {if(value) value->Release();} + T *operator->() const {return value;} +}; + +ImageRaster decodeNativeImage(const fs::path &file,ImageFormat format,std::stop_token stop) +{ + struct Apartment + { + const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED); + ~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();} + }; + const Apartment apartment; + if(apartment.initialized!=RPC_E_CHANGED_MODE) checkImage(apartment.initialized); + ImagingObject factory; + checkImage(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value))); + ImagingObject stream; + checkImage(factory->CreateStream(&stream.value)); + checkImage(stream->InitializeFromFilename(file.c_str(),GENERIC_READ)); + const auto &container=format==ImageFormat::png?GUID_ContainerFormatPng: + format==ImageFormat::jpeg?GUID_ContainerFormatJpeg:format==ImageFormat::gif?GUID_ContainerFormatGif: + GUID_ContainerFormatBmp; + ImagingObject decoder; + checkImage(factory->CreateDecoder(container,nullptr,&decoder.value)); + checkImage(decoder->Initialize(stream.value,WICDecodeMetadataCacheOnDemand)); + ImagingObject frame; + checkImage(decoder->GetFrame(0,&frame.value)); + ImageRaster raster; + checkImage(frame->GetSize(&raster.width,&raster.height)); + checkImageDimensions(raster.width,raster.height); + checkImageStop(stop); + ImagingObject formatConverter; + checkImage(factory->CreateFormatConverter(&formatConverter.value)); + checkImage(formatConverter->Initialize(frame.value,GUID_WICPixelFormat32bppPBGRA,WICBitmapDitherTypeNone, + nullptr,0,WICBitmapPaletteTypeCustom)); + raster.pixels.resize(size_t(raster.width)*raster.height); + checkImage(formatConverter->CopyPixels(nullptr,raster.width*sizeof(uint32_t), + static_cast(raster.pixels.size()*sizeof(uint32_t)),reinterpret_cast(raster.pixels.data()))); + return raster; +} + +ImageRaster decodeWebp(const fs::path &file,size_t size,std::stop_token stop) +{ + std::vector bytes(size); + std::ifstream stream(file,std::ios::binary); + if(!stream.read(reinterpret_cast(bytes.data()),size)) throw std::runtime_error(invalidImage); + WebPBitstreamFeatures info{}; + if(WebPGetFeatures(bytes.data(),bytes.size(),&info)!=VP8_STATUS_OK) throw std::runtime_error(invalidImage); + ImageRaster raster{static_cast(info.width),static_cast(info.height)}; + checkImageDimensions(raster.width,raster.height); + checkImageStop(stop); + raster.pixels.resize(size_t(raster.width)*raster.height); + auto *output=reinterpret_cast(raster.pixels.data()); + const auto outputSize=raster.pixels.size()*sizeof(uint32_t); + if(info.has_animation) + { + WebPAnimDecoderOptions options{}; + if(!WebPAnimDecoderOptionsInit(&options)) throw std::runtime_error(invalidImage); + options.color_mode=MODE_bgrA; + const WebPData data{bytes.data(),bytes.size()}; + const std::unique_ptr decoder( + WebPAnimDecoderNew(&data,&options),WebPAnimDecoderDelete); + uint8_t *frame=nullptr; + int timestamp{}; + if(!decoder || !WebPAnimDecoderGetNext(decoder.get(),&frame,×tamp)) + throw std::runtime_error(invalidImage); + std::memcpy(output,frame,outputSize); + } + else + { + WebPDecoderConfig config{}; + if(!WebPInitDecoderConfig(&config)) throw std::runtime_error(invalidImage); + config.output.colorspace=MODE_bgrA; + config.output.is_external_memory=1; + config.output.u.RGBA={output,static_cast(raster.width*sizeof(uint32_t)),outputSize}; + const auto status=WebPDecode(bytes.data(),bytes.size(),&config); + WebPFreeDecBuffer(&config.output); + if(status!=VP8_STATUS_OK) throw std::runtime_error(invalidImage); + } + return raster; +} +} + +bool isImagePath(const std::filesystem::path &path) +{ + return imageFormat(path)!=ImageFormat::unknown; +} + +ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop) +{ + const auto format=imageFormat(name); + if(format==ImageFormat::unknown) throw std::runtime_error("This image format is not supported."); + checkImageStop(stop); + const auto size=std::filesystem::file_size(contents); + if(size==0) throw std::runtime_error(invalidImage); + if(size>imageSourceLimit) throw std::runtime_error(largeImage); + auto image=format==ImageFormat::webp?decodeWebp(contents,static_cast(size),stop): + decodeNativeImage(contents,format,stop); + checkImageStop(stop); + return image; +} +} diff --git a/src/files_image_decode.h b/src/files_image_decode.h new file mode 100644 index 0000000..dd3edb7 --- /dev/null +++ b/src/files_image_decode.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include +#include +#include + +namespace ks::files +{ +struct ImageRaster +{ + unsigned width{}, height{}; + std::vector pixels; +}; + +inline constexpr uint64_t imageSourceLimit=96ULL*1024*1024; +bool isImagePath(const std::filesystem::path &path); +ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop={}); +} diff --git a/src/files_image_view.cpp b/src/files_image_view.cpp new file mode 100644 index 0000000..32f2bda --- /dev/null +++ b/src/files_image_view.cpp @@ -0,0 +1,459 @@ +#include "files_image_view.h" +#include "platform.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ks::files +{ +namespace +{ +namespace fs=std::filesystem; +constexpr wchar_t imageWindowClass[]=L"KSwitcherFilesImageViewer"; +constexpr UINT_PTR imageTimer=1; +enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize }; + +void fillImageView(HDC dc,const RECT &rect,COLORREF color) +{ + SetDCBrushColor(dc,color); + FillRect(dc,&rect,static_cast(GetStockObject(DC_BRUSH))); +} + +struct ImageView +{ + HWND window{}; + bool embedded{}; + ImageViewStyle style; + std::vector images; + size_t position{}; + ImageLoad load; + std::function onClose; + std::array buttons{}; + HFONT font{}; + UINT fontDpi{}; + HBITMAP bitmap{}; + unsigned width{},height{}; + fs::path requested; + std::wstring error; + std::future reading; + std::stop_source stop; + uint64_t revision{}, started{}; + double zoom=1, x{}, y{}; + bool fit=true, dragging{}; + POINT lastMouse{}; + + ~ImageView() + { + stop.request_stop(); + if(bitmap) DeleteObject(bitmap); + if(font) DeleteObject(font); + } + + int scale(int pixels) const {return MulDiv(pixels,GetDpiForWindow(window),96);} + + RECT viewport() const + { + RECT area{}; + GetClientRect(window,&area); + area.top=std::min(area.bottom,static_cast(scale(35))); + area.bottom=std::max(area.top,area.bottom-scale(27)); + return area; + } + + void layout() + { + const auto dpi=GetDpiForWindow(window); + if(fontDpi!=dpi) + { + LOGFONTW definition=style.font; + definition.lfHeight=-MulDiv(style.tenthsOfPoint,dpi,720); + if(const auto next=CreateFontIndirectW(&definition)) + { + if(font) DeleteObject(font); + font=next; + fontDpi=dpi; + } + } + RECT bounds{}; + GetClientRect(window,&bounds); + const int left=scale(4), gap=scale(3), height=scale(27); + const int count=embedded?4:6; + const int available=std::max(0,static_cast(bounds.right)-left*2-gap*(count-1)); + const int unit=std::min(scale(80),available/count); + int x=left; + for(auto button:buttons) + { + if(!button) continue; + SetWindowPos(button,nullptr,x,scale(4),unit,height,SWP_NOZORDER|SWP_NOACTIVATE); + x+=unit+gap; + } + clampOffset(); + InvalidateRect(window,nullptr,FALSE); + } + + void updateButtons() const + { + if(!embedded) + { + EnableWindow(buttons[previous-1],position>0); + EnableWindow(buttons[following-1],position+1(image.width); + info.bmiHeader.biHeight=-static_cast(image.height); + info.bmiHeader.biPlanes=1; + info.bmiHeader.biBitCount=32; + info.bmiHeader.biCompression=BI_RGB; + void *bits=nullptr; + bitmap=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0); + if(!bitmap || !bits) throw std::runtime_error("Could not display this image."); + std::memcpy(bits,image.pixels.data(),image.pixels.size()*sizeof(uint32_t)); + width=image.width; + height=image.height; + updateButtons(); + } + + void poll() + { + if(reading.valid()) + { + if(reading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return; + try + { + auto image=reading.get(); + if(revision==started) show(std::move(image)); + } + catch(const std::exception &e) + { + if(revision==started) error=wide(e.what()); + } + if(revision==started) + { + KillTimer(window,imageTimer); + InvalidateRect(window,nullptr,FALSE); + return; + } + } + if(requested.empty()) + { + KillTimer(window,imageTimer); + return; + } + stop=std::stop_source{}; + started=revision; + std::packaged_task task([path=requested,decoder=load,token=stop.get_token()] + { + return decoder?decoder(path,token):decodeImage(path,path,token); + }); + reading=task.get_future(); + try {std::thread(std::move(task)).detach();} + catch(const std::exception &e) + { + reading={}; + error=wide(e.what()); + KillTimer(window,imageTimer); + InvalidateRect(window,nullptr,FALSE); + } + } + + double factor() const + { + if(!fit || !width || !height) return zoom; + const auto area=viewport(); + return std::min({1.0,static_cast(std::max(1L,area.right-area.left))/width, + static_cast(std::max(1L,area.bottom-area.top))/height}); + } + + void clampOffset() + { + const auto area=viewport(); + const auto value=factor(); + const auto limitX=std::max(0.0,(width*value-(area.right-area.left))/2); + const auto limitY=std::max(0.0,(height*value-(area.bottom-area.top))/2); + x=std::clamp(x,-limitX,limitX); + y=std::clamp(y,-limitY,limitY); + } + + void changeZoom(double multiplier,const POINT *anchor=nullptr) + { + if(!bitmap) return; + const auto before=factor(); + fit=false; + zoom=std::clamp(before*multiplier,std::min(0.025,before),16.0); + if(anchor) + { + const auto area=viewport(); + const double dx=anchor->x-(area.left+area.right)/2.0; + const double dy=anchor->y-(area.top+area.bottom)/2.0; + x=dx+(x-dx)*zoom/before; + y=dy+(y-dy)*zoom/before; + } + clampOffset(); + InvalidateRect(window,nullptr,FALSE); + } + + void action(UINT id) + { + if(id==previous && position>0) request(images[--position]); + else if(id==following && position+1(GetStockObject(DC_BRUSH))); + if(font) SelectObject(item.hDC,font); + SetBkMode(item.hDC,TRANSPARENT); + SetTextColor(item.hDC,foreground); + wchar_t label[24]{}; + GetWindowTextW(item.hwndItem,label,static_cast(std::size(label))); + auto labelArea=item.rcItem; + InflateRect(&labelArea,-scale(2),0); + DrawTextW(item.hDC,label,-1,&labelArea,DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX); + } + + void paint() + { + PAINTSTRUCT repaint{}; + const auto dc=BeginPaint(window,&repaint); + RECT all{}; + GetClientRect(window,&all); + const auto area=viewport(); + fillImageView(dc,all,style.toolbar); + fillImageView(dc,area,style.background); + if(font) SelectObject(dc,font); + SetBkMode(dc,TRANSPARENT); + SetTextColor(dc,style.text); + if(bitmap) + { + if(const auto source=CreateCompatibleDC(dc)) + { + const auto old=SelectObject(source,bitmap); + const auto saved=SaveDC(dc); + IntersectClipRect(dc,area.left,area.top,area.right,area.bottom); + const auto displayWidth=std::max(1L,std::lround(width*factor())); + const auto displayHeight=std::max(1L,std::lround(height*factor())); + const auto left=std::lround((area.left+area.right-displayWidth)/2.0+x); + const auto top=std::lround((area.top+area.bottom-displayHeight)/2.0+y); + const double horizontal=double(displayWidth)/width, vertical=double(displayHeight)/height; + const auto clippedSource=[](LONG edge,LONG start,double ratio,unsigned size,bool end) + { + const auto pixel=(edge-start)/ratio; + return static_cast(std::clamp(end?std::ceil(pixel):std::floor(pixel),0.0,double(size))); + }; + const int startX=clippedSource(area.left,left,horizontal,width,false); + const int endX=clippedSource(area.right,left,horizontal,width,true); + const int startY=clippedSource(area.top,top,vertical,height,false); + const int endY=clippedSource(area.bottom,top,vertical,height,true); + const auto destX=left+std::lround(startX*horizontal), destY=top+std::lround(startY*vertical); + AlphaBlend(dc,destX,destY,left+std::lround(endX*horizontal)-destX,top+std::lround(endY*vertical)-destY, + source,startX,startY,endX-startX,endY-startY,{AC_SRC_OVER,0,255,AC_SRC_ALPHA}); + if(saved) RestoreDC(dc,saved); + SelectObject(source,old); + DeleteDC(source); + } + } + else if(!requested.empty()) + { + auto message=area; + InflateRect(&message,-scale(8),0); + DrawTextW(dc,error.empty()?L"Loading image…":error.c_str(),-1,&message, + DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX); + } + SetTextColor(dc,style.toolbarText); + auto status=requested.filename().wstring(); + if(bitmap) status+=L" · "+std::to_wstring(width)+L" × "+std::to_wstring(height)+L" · "+ + std::to_wstring(std::lround(factor()*100))+L"%"; + RECT footer{scale(8),area.bottom,all.right-scale(8),all.bottom}; + DrawTextW(dc,status.c_str(),-1,&footer,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX); + EndPaint(window,&repaint); + } +}; + +std::map> imageViews; + +LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_NCCREATE) + { + const auto *created=reinterpret_cast(lp); + const auto state=*static_cast *>(created->lpCreateParams); + state->window=window; + imageViews.emplace(window,state); + } + const auto found=imageViews.find(window); + if(found==imageViews.end()) return DefWindowProcW(window,message,wp,lp); + const auto state=found->second; + auto &view=*state; + switch(message) + { + case WM_CREATE: + { + constexpr const wchar_t *labels[]{L"Previous",L"Next",L"−",L"+",L"Fit",L"100%"}; + for(unsigned id=view.embedded?zoomOut:previous;id<=actualSize;++id) + view.buttons[id-1]=CreateWindowW(L"BUTTON",labels[id-1],WS_CHILD|WS_VISIBLE|BS_OWNERDRAW, + 0,0,0,0,window,reinterpret_cast(static_cast(id)),GetModuleHandleW(nullptr),nullptr); + view.layout(); + view.updateButtons(); + return 0; + } + case WM_SIZE: view.layout(); return 0; + case WM_DPICHANGED: + if(!view.embedded) + { + const auto &bounds=*reinterpret_cast(lp); + SetWindowPos(window,nullptr,bounds.left,bounds.top,bounds.right-bounds.left,bounds.bottom-bounds.top, + SWP_NOACTIVATE|SWP_NOZORDER); + } + view.layout(); + return 0; + case WM_DPICHANGED_AFTERPARENT: view.layout(); return 0; + case WM_ERASEBKGND: return 1; + case WM_PAINT: view.paint(); return 0; + case WM_DRAWITEM: view.paintButton(*reinterpret_cast(lp)); return TRUE; + case WM_TIMER: if(wp==imageTimer) view.poll(); return 0; + case WM_COMMAND: + if(HIWORD(wp)==BN_CLICKED) {view.action(LOWORD(wp)); SetFocus(window);} + return 0; + case WM_LBUTTONDOWN: + { + const auto area=view.viewport(); + const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; + if(view.bitmap && PtInRect(&area,point)) + { + SetFocus(window); + view.dragging=true; + view.lastMouse=point; + SetCapture(window); + } + return 0; + } + case WM_MOUSEMOVE: + if(view.dragging) + { + const POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; + view.x+=point.x-view.lastMouse.x; + view.y+=point.y-view.lastMouse.y; + view.lastMouse=point; + view.clampOffset(); + InvalidateRect(window,nullptr,FALSE); + } + return 0; + case WM_LBUTTONUP: + if(view.dragging) ReleaseCapture(); + return 0; + case WM_CAPTURECHANGED: view.dragging=false; return 0; + case WM_MOUSEWHEEL: + { + POINT point{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; + ScreenToClient(window,&point); + view.changeZoom(std::pow(1.25,static_cast(GET_WHEEL_DELTA_WPARAM(wp))/WHEEL_DELTA),&point); + return 0; + } + case WM_KEYDOWN: + if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn); + else if(wp==VK_SUBTRACT || wp==VK_OEM_MINUS) view.action(zoomOut); + else if(wp=='0') view.action(fitImage); + else if(wp=='1') view.action(actualSize); + else if(!view.embedded && (wp==VK_LEFT || wp==VK_PRIOR)) view.action(previous); + else if(!view.embedded && (wp==VK_RIGHT || wp==VK_NEXT)) view.action(following); + else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) DestroyWindow(window); + else break; + return 0; + case WM_NCDESTROY: + imageViews.erase(found); + if(view.onClose) view.onClose(window); + break; + } + return DefWindowProcW(window,message,wp,lp); +} +} + +HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector images, + const std::filesystem::path &initial,ImageLoad load,std::function onClose) +{ + const auto instance=GetModuleHandleW(nullptr); + static const bool registered=[instance] + { + WNDCLASSW type{}; + type.hInstance=instance; + type.hCursor=LoadCursorW(nullptr,IDC_ARROW); + type.lpfnWndProc=imageProcedure; + type.lpszClassName=imageWindowClass; + return RegisterClassW(&type)!=0; + }(); + if(!registered) return nullptr; + auto state=std::make_shared(); + state->embedded=embedded; + state->style=style; + state->images=std::move(images); + state->load=std::move(load); + state->onClose=std::move(onClose); + const auto position=std::find(state->images.begin(),state->images.end(),initial); + if(position!=state->images.end()) state->position=static_cast(position-state->images.begin()); + RECT bounds{}; + if(!embedded) GetWindowRect(owner,&bounds); + const auto window=CreateWindowExW(embedded?0:WS_EX_APPWINDOW,imageWindowClass,embedded?L"Quick View":L"Viewer", + embedded?(WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS):(WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN), + bounds.left,bounds.top,bounds.right-bounds.left,bounds.bottom-bounds.top, + embedded?owner:nullptr,nullptr,instance,&state); + if(window) state->request(initial); + return window; +} + +void showImageViewFile(HWND window,const std::filesystem::path &path) +{ + if(const auto found=imageViews.find(window);found!=imageViews.end()) found->second->request(path); +} +} diff --git a/src/files_image_view.h b/src/files_image_view.h new file mode 100644 index 0000000..c127347 --- /dev/null +++ b/src/files_image_view.h @@ -0,0 +1,21 @@ +#pragma once + +#include "files_image_decode.h" +#include +#include + +namespace ks::files +{ +using ImageLoad=std::function; + +struct ImageViewStyle +{ + LOGFONTW font{}; + int tenthsOfPoint{}; + COLORREF background{}, text{}, toolbar{}, toolbarText{}, selection{}; +}; + +HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector images, + const std::filesystem::path &initial,ImageLoad load={},std::function onClose={}); +void showImageViewFile(HWND window,const std::filesystem::path &path); +} diff --git a/src/files_main.cpp b/src/files_main.cpp index bcfcb4f..c130a04 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -28,6 +28,7 @@ #include #include "files_terminal.h" #include "files_archive.h" +#include "files_image_decode.h" #include "files_win32_directory.h" #include "files_command_completion.h" #include "files_text_window.h" @@ -641,6 +642,8 @@ std::wstring panelCaption(const Panel &panel) Panel panels[2]; HWND quickViewWindow{}; +HWND quickImageWindow{}; +bool quickViewDisplaysImage{}; int quickViewSource{}; bool panelClipboardContext=true; void refreshQuickView(const Panel &panel); @@ -1576,9 +1579,14 @@ void layout(HWND window,bool activeOnly) { const int left=quickViewSource==0?middle+2:0; const int right=quickViewSource==0?width:middle-2; - SetWindowPos(quickViewWindow,nullptr,left+5,4,std::max(0,right-left-10), - std::max(0,panelBottom+summaryHeight+textHeight),SWP_NOZORDER|SWP_NOACTIVATE); - ShowWindow(quickViewWindow,terminalVisible?SW_HIDE:SW_SHOWNA); + for(const auto preview:{quickViewWindow,quickImageWindow}) + { + if(!preview) continue; + SetWindowPos(preview,nullptr,left+5,4,std::max(0,right-left-10), + std::max(0,panelBottom+summaryHeight+textHeight),SWP_NOZORDER|SWP_NOACTIVATE); + const bool current=quickViewDisplaysImage==(preview==quickImageWindow); + ShowWindow(preview,!terminalVisible && current?SW_SHOWNA:SW_HIDE); + } } if(IsWindowVisible(panelSearchPopup)) placePanelSearch(window); RedrawWindow(window,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN); @@ -4084,14 +4092,30 @@ void refreshQuickView(const Panel &panel) const auto row=currentPanelRow(panel); const bool file=!panel.peer && !panel.ftp && !panel.archive && row!=LB_ERR && panel.sizes[row]!=L"Folder" && panel.sizes[row]!=L"Up"; - ks::files::previewQuickViewFile(quickViewWindow,file?panel.rows[row]:fs::path{}); + const auto path=file?panel.rows[row]:fs::path{}; + if(file && ks::files::isImagePath(path) && !quickImageWindow) + { + try {quickImageWindow=ks::files::createImageQuickView(GetParent(panel.list),textWindowDialogs());} + catch(const std::exception &) {} + } + const bool image=quickImageWindow && file && ks::files::isImagePath(path); + ks::files::previewQuickViewFile(quickViewWindow,image?fs::path{}:path); + if(quickImageWindow) ks::files::previewImageQuickViewFile(quickImageWindow,image?path:fs::path{}); + if(std::exchange(quickViewDisplaysImage,image)!=image) layout(GetParent(panel.list)); +} + +void closeQuickViews() +{ + if(quickImageWindow) DestroyWindow(std::exchange(quickImageWindow,nullptr)); + if(quickViewWindow) DestroyWindow(std::exchange(quickViewWindow,nullptr)); + quickViewDisplaysImage=false; } void toggleQuickView(HWND owner) { if(quickViewWindow) { - DestroyWindow(std::exchange(quickViewWindow,nullptr)); + closeQuickViews(); layout(owner); restoreCommandFocus(); return; @@ -4127,6 +4151,16 @@ bool handleQuickViewKey(HWND window,const MSG &message) ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile); +void openPanelImage(const Panel &panel,const fs::path &path,const ks::files::RemoteTextSource *source=nullptr) +{ + std::vector images; + for(size_t row=0;rowfile; @@ -4146,7 +4180,8 @@ void openArchiveText(const Panel &panel,const fs::path &path) const auto entry=ks::files::readArchiveMember(file,relative,cache,limit,progress); return ks::files::RemoteTextRevision{entry.size,entry.modified,false}; },{}}; - ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive); + if(ks::files::isImagePath(path)) openPanelImage(panel,path,&archive); + else ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive); } void openSelectedText(const Panel &panel, bool edit, bool external) @@ -4168,12 +4203,15 @@ void openSelectedText(const Panel &panel, bool edit, bool external) const auto &path=panel.rows[row]; if(panel.ftp) { - ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftpTextSource(*panel.ftp)); + const auto ftp=ftpTextSource(*panel.ftp); + if(!edit && ks::files::isImagePath(path)) openPanelImage(panel,path,&ftp); + else ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftp); return; } if(external) openPanelFile(panel,path,edit?L"edit":L"open", edit?L"No editor is registered for this file.":L"Cannot open the selected file."); + else if(!edit && ks::files::isImagePath(path)) openPanelImage(panel,path); else ks::files::openTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(), panel.peer?&*panel.peer:nullptr); } @@ -8474,7 +8512,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) remoteCommandThread.request_stop(); remoteCommandThread.join(); } - if(quickViewWindow) DestroyWindow(std::exchange(quickViewWindow,nullptr)); + closeQuickViews(); ks::files::textWindowOwnerClosed(); return 0; } diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index 7e5d4c5..56de86d 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -1,4 +1,5 @@ #include "files_text_window.h" +#include "files_image_view.h" #include "files_text_preferences.h" #include "files_menu_paint.h" #include "files_menu_navigation.h" @@ -2677,7 +2678,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, self->window=nullptr; textWindows.erase(window); std::erase(textWindowOrder,window); - if(textOwnerClosed && textWindows.empty()) PostQuitMessage(0); + if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0); break; } } @@ -2795,12 +2796,12 @@ void textWindowOwnerClosed() { filesOwner=nullptr; textOwnerClosed=true; - if(textWindows.empty()) PostQuitMessage(0); + if(textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0); } bool cycleTextWindows(HWND current,bool reverse) { - if(!current || (current!=filesOwner && !textWindows.contains(current))) return false; + if(!current) return false; std::vector windows; if(filesOwner && IsWindowVisible(filesOwner)) windows.push_back(filesOwner); for(const auto window:textWindowOrder) @@ -2874,9 +2875,62 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path) preview->second->previewFile(path); } +ImageViewStyle imageViewStyle(TextDialogs dialogs) +{ + const auto font=dialogs.readFont(); + const auto colors=loadTextPreferences().profiles[0].colors; + return {font.font,font.tenthsOfPoint,colors[0],colors[1],colors[2],colors[3],colors[4]}; +} + +HWND createImageQuickView(HWND owner,TextDialogs dialogs) +{ + return createImageView(owner,true,imageViewStyle(dialogs),{},{}); +} + +void previewImageQuickViewFile(HWND window,const std::filesystem::path &path) +{ + showImageViewFile(window,path); +} + +void openImageWindow(HWND owner,std::vector images,const std::filesystem::path &path, + TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source) +{ + try + { + const auto backend=source?std::optional(*source):peer?std::optional(lanTextSource(*peer)):std::nullopt; + ImageLoad load; + if(backend) + load=[backend=*backend](const std::filesystem::path &original,std::stop_token stop) { + RemoteTextFile file(backend,original); + file.download(false,[&](uint64_t,uint64_t){return !stop.stop_requested();},imageSourceLimit); + return decodeImage(file.cache,original,stop); + }; + if(!textWindows.contains(owner)) filesOwner=owner; + const auto window=createImageView(owner,false,imageViewStyle(dialogs),std::move(images),path,std::move(load), + [](HWND closed) { + std::erase(textWindowOrder,closed); + if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0); + }); + if(!window) throw std::runtime_error("Could not open the image viewer."); + textWindowOrder.push_back(window); + const auto instance=GetModuleHandleW(nullptr); + const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(IDI_FILES_VIEWER),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE); + if(icon) SendMessageW(window,WM_SETICON,ICON_BIG,reinterpret_cast(icon)); + setFileWindowTaskbar(window,IDI_FILES_VIEWER,L"HrynCo.KSwitcher.Files.Viewer"); + ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW); + SetFocus(window); + } + catch(const std::exception &error) {dialogs.message(owner,wide(error.what()).c_str());} +} + static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options) { + if(!edit && !options.draft && isImagePath(path)) + { + openImageWindow(owner,{path},path,dialogs,nullptr,backend); + return; + } try { if(!textWindows.contains(owner)) filesOwner=owner; diff --git a/src/files_text_window.h b/src/files_text_window.h index 3816952..db7fe19 100644 --- a/src/files_text_window.h +++ b/src/files_text_window.h @@ -83,6 +83,10 @@ struct RemoteTextSource inline constexpr UINT quickViewToggleMessage=WM_APP+31; HWND createQuickView(HWND owner,TextDialogs dialogs); void previewQuickViewFile(HWND window,const std::filesystem::path &path); +HWND createImageQuickView(HWND owner,TextDialogs dialogs); +void previewImageQuickViewFile(HWND window,const std::filesystem::path &path); +void openImageWindow(HWND owner,std::vector images,const std::filesystem::path &path, + TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr); void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false, diff --git a/tests/files_image.cpp b/tests/files_image.cpp new file mode 100644 index 0000000..b0c692b --- /dev/null +++ b/tests/files_image.cpp @@ -0,0 +1,172 @@ +#include "files_image_decode.h" +#include +#include +#include +#include +#include +#include +#include + +namespace +{ +namespace fs=std::filesystem; +using namespace ks::files; + +void expect(bool condition,const char *message) +{ + if(!condition) throw std::runtime_error(message); +} + +template +struct Com +{ + T *value{}; + ~Com(){if(value) value->Release();} + T *operator->() const{return value;} +}; + +void checked(HRESULT result) +{ + expect(SUCCEEDED(result),"WIC fixture encoding failed."); +} + +void encodeNative(const fs::path &path,REFGUID container) +{ + Com factory; + checked(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value))); + Com stream; + checked(factory->CreateStream(&stream.value)); + checked(stream->InitializeFromFilename(path.c_str(),GENERIC_WRITE)); + Com encoder; + checked(factory->CreateEncoder(container,nullptr,&encoder.value)); + checked(encoder->Initialize(stream.value,WICBitmapEncoderNoCache)); + Com frame; + checked(encoder->CreateNewFrame(&frame.value,nullptr)); + checked(frame->Initialize(nullptr)); + checked(frame->SetSize(8,6)); + auto pixelFormat=GUID_WICPixelFormat24bppBGR; + checked(frame->SetPixelFormat(&pixelFormat)); + expect(pixelFormat==GUID_WICPixelFormat24bppBGR,"fixture pixel format"); + std::array pixels{}; + for(size_t i=0;iWritePixels(6,8*3,pixels.size(),pixels.data())); + checked(frame->Commit()); + checked(encoder->Commit()); +} + +struct Temp +{ + fs::path path; + Temp() + { + GUID id{}; + wchar_t name[40]{}; + expect(SUCCEEDED(CoCreateGuid(&id)) && StringFromGUID2(id,name,40),"temporary file prefix"); + path=fs::temp_directory_path()/(L"ks-test-image-"+std::wstring(name)); + expect(fs::create_directory(path),"temporary image directory"); + } + ~Temp(){std::error_code error; fs::remove_all(path,error);} +}; + +void expectDecodeFailure(const fs::path &file,std::string_view text) +{ + try {decodeImage(file,file);} + catch(const std::runtime_error &e) + { + expect(std::string_view(e.what()).find(text)!=std::string_view::npos,e.what()); + return; + } + throw std::runtime_error("invalid image was decoded"); +} + +std::vector animatedWebp(const uint8_t *encoded,size_t size) +{ + expect(size>12,"WebP fixture RIFF body"); + std::vector bytes{'R','I','F','F',0,0,0,0,'W','E','B','P', + 'V','P','8','X',10,0,0,0,0x12,0,0,0,0,0,0,0,0,0, + 'A','N','I','M',6,0,0,0,0,0,0,0,0,0, + 'A','N','M','F',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,100,0,0,2}; + bytes.insert(bytes.end(),encoded+12,encoded+size); + const auto storeSize=[&](size_t offset,size_t value) { + for(unsigned i=0;i<4;++i) bytes[offset+i]=static_cast(value>>(8*i)); + }; + storeSize(4,bytes.size()-8); + storeSize(48,16+size-12); + return bytes; +} +} + +int main() +{ + const auto apartment=CoInitializeEx(nullptr,COINIT_MULTITHREADED); + int result=0; + try + { + expect(SUCCEEDED(apartment),"initialize COM"); + Temp temp; + for(const auto &[name,container]:std::array{ + std::pair{L"знімок.PNG",&GUID_ContainerFormatPng}, + std::pair{L"picture.jpeg",&GUID_ContainerFormatJpeg}, + std::pair{L"picture.bmp",&GUID_ContainerFormatBmp}}) + { + const auto path=temp.path/name; + expect(isImagePath(path),"supported native extension"); + encodeNative(path,*container); + const auto decoded=decodeImage(path,path); + expect(decoded.width==8 && decoded.height==6 && decoded.pixels.size()==48,"native image dimensions"); + const auto first=decoded.pixels.front(); + expect((first>>24)==255 && ((first>>16)&255)>150,"native image color and opacity"); + } + const auto gif=temp.path/L"picture.gif"; + constexpr unsigned char gifData[]{0x47,0x49,0x46,0x38,0x39,0x61,1,0,1,0,0x80,0,0, + 0,0,0,255,255,255,0x2c,0,0,0,0,1,0,1,0,0,2,2,0x44,1,0,0x3b}; + std::ofstream(gif,std::ios::binary).write(reinterpret_cast(gifData),sizeof(gifData)); + const auto gifImage=decodeImage(gif,gif); + expect(gifImage.width==1 && gifImage.height==1 && gifImage.pixels.size()==1,"GIF first frame"); + const auto webp=temp.path/L"picture.webp"; + const uint8_t pixel[]{12,84,200,128}; + uint8_t *encoded=nullptr; + const auto length=WebPEncodeLosslessBGRA(pixel,1,1,4,&encoded); + expect(length>0,"WebP fixture"); + std::ofstream(webp,std::ios::binary).write(reinterpret_cast(encoded),length); + auto animation=animatedWebp(encoded,length); + WebPFree(encoded); + const auto webpImage=decodeImage(webp,webp); + expect(webpImage.width==1 && webpImage.height==1 && webpImage.pixels.size()==1,"WebP dimensions"); + const auto color=webpImage.pixels.front(); + expect((color>>24)==128 && ((color>>16)&255)>=99 && ((color>>16)&255)<=101,"WebP premultiplied alpha"); + const auto animated=temp.path/L"animated.webp"; + std::ofstream(animated,std::ios::binary).write(reinterpret_cast(animation.data()),animation.size()); + const auto firstFrame=decodeImage(animated,animated); + expect(firstFrame.width==1 && firstFrame.height==1 && firstFrame.pixels.front()==color,"animated WebP first frame"); + const auto hugeCanvas=temp.path/L"oversized-canvas.webp"; + animation[24]=0x1f; + animation[25]=0x4e; // 20000 pixels, encoded as width minus one. + std::ofstream(hugeCanvas,std::ios::binary).write(reinterpret_cast(animation.data()),animation.size()); + expectDecodeFailure(hugeCanvas,"too large"); + const auto corrupt=temp.path/L"corrupt.png"; + std::ofstream(corrupt,std::ios::binary)<<"not an image"; + expectDecodeFailure(corrupt,"damaged"); + const auto large=temp.path/L"huge.bmp"; + { + std::ofstream output(large,std::ios::binary); + output.seekp(imageSourceLimit); + output.put('\0'); + } + expectDecodeFailure(large,"too large"); + std::stop_source canceled; + canceled.request_stop(); + bool stopped=false; + try{decodeImage(webp,webp,canceled.get_token());} + catch(const std::system_error &error){stopped=error.code().value()==ERROR_CANCELLED;} + expect(stopped,"canceled image load"); + } + catch(const std::exception &error){std::cerr< Date: Wed, 25 Nov 2026 16:20:52 +0200 Subject: [PATCH 18/61] Show original file bytes in Hex Viewer Refs #102 --- FILES-UI.md | 7 ++ src/files_main.cpp | 31 +++--- src/files_text_document.cpp | 52 +++++++++ src/files_text_document.h | 5 + src/files_text_window.cpp | 192 ++++++++++++++++++++++++---------- src/files_text_window.h | 3 +- tests/files_text_document.cpp | 21 ++++ 7 files changed, 241 insertions(+), 70 deletions(-) diff --git a/FILES-UI.md b/FILES-UI.md index a4570bb..3c95cb0 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -313,6 +313,13 @@ Warning і початковий фокус на No. - У цьому вікні F6 перемикає перегляд і редагування для поточного файла. За наявності змін перехід у перегляд пропонує Save, Discard або Cancel. Помилка збереження залишає відкритим редактор зі змінами. +- **Shift+F3** або **Commands → View as hex** відкриває файл у Hex Viewer. + **F4** у Viewer перемикає текстовий або форматований перегляд і Hex. + Hex показує 64-бітну адресу, 16 вихідних байтів у рядку й ASCII. + Нульові й недруковані байти видно в hex, а в ASCII їх позначає крапка. + Блоки по 64 КіБ перемикаються через Ctrl+Page Up, Ctrl+Page Down або F5. + Esc повертає до попереднього режиму Viewer або, якщо файл відкрито + напряму в Hex, до файлової панелі. - Ctrl+Tab циклічно перемикає фокус між Files, редакторами й переглядачами у порядку їх відкриття. Ctrl+Shift+Tab обходить ті самі вікна у зворотному порядку. Коли відкрито лише Files, активна панель не змінюється. diff --git a/src/files_main.cpp b/src/files_main.cpp index c130a04..dc7f9c9 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -3381,7 +3381,7 @@ void collectFolderSizes(Panel &panel) if((finished || !completed.empty()) && &panel==&panels[active]) showFileDetails(panel); } -void openSelectedText(const Panel &panel, bool edit, bool external); +void openSelectedText(const Panel &panel, bool edit, bool external,bool hex=false); void findLocalFiles(HWND owner,Panel &panel); void compareSelectedFiles(HWND owner); void createArchive(HWND owner,Panel &panel); @@ -3537,6 +3537,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==2 && row==13) openSelectedText(panels[active],false,false,true); else if(menuIndex==1 && row==4) createArchive(owner,panels[active]); else { @@ -4161,7 +4162,7 @@ void openPanelImage(const Panel &panel,const fs::path &path,const ks::files::Rem panel.peer?&*panel.peer:nullptr,source); } -void openArchiveText(const Panel &panel,const fs::path &path) +void openArchiveText(const Panel &panel,const fs::path &path,bool hex=false) { const auto file=panel.archive->file; const auto member=path.lexically_relative(file); @@ -4180,11 +4181,12 @@ void openArchiveText(const Panel &panel,const fs::path &path) const auto entry=ks::files::readArchiveMember(file,relative,cache,limit,progress); return ks::files::RemoteTextRevision{entry.size,entry.modified,false}; },{}}; - if(ks::files::isImagePath(path)) openPanelImage(panel,path,&archive); - else ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive); + if(!hex && ks::files::isImagePath(path)) openPanelImage(panel,path,&archive); + else ks::files::openRemoteTextWindow(GetParent(panel.list),path,false,textWindowDialogs(),archive,{}, + false,{.hex=hex}); } -void openSelectedText(const Panel &panel, bool edit, bool external) +void openSelectedText(const Panel &panel, bool edit, bool external,bool hex) { if(ftpProfileList(panel)) return; const auto row=currentPanelRow(panel); @@ -4192,7 +4194,7 @@ void openSelectedText(const Panel &panel, bool edit, bool external) if(panel.archive) { if(edit || external) setStatus(L"Archive entries are read-only. Use F5 to extract them."); - else openArchiveText(panel,panel.rows[row]); + else openArchiveText(panel,panel.rows[row],hex); return; } if((panel.peer || panel.ftp) && external) @@ -4204,16 +4206,16 @@ void openSelectedText(const Panel &panel, bool edit, bool external) if(panel.ftp) { const auto ftp=ftpTextSource(*panel.ftp); - if(!edit && ks::files::isImagePath(path)) openPanelImage(panel,path,&ftp); - else ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftp); + if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path,&ftp); + else ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftp,{},false,{.hex=hex}); return; } if(external) openPanelFile(panel,path,edit?L"edit":L"open", edit?L"No editor is registered for this file.":L"Cannot open the selected file."); - else if(!edit && ks::files::isImagePath(path)) openPanelImage(panel,path); + else if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path); else ks::files::openTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(), - panel.peer?&*panel.peer:nullptr); + panel.peer?&*panel.peer:nullptr,{},false,{.hex=hex}); } void enter(Panel &panel) @@ -7510,12 +7512,12 @@ void openMenu(HWND window, int index) L"View externally\tAlt+F3",L"Edit externally\tAlt+F4", L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(), L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q", - L"Copy full path\tCtrl+Shift+C",L"Space Analyzer"}; + L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3"}; } commandActions.clear(); if(index==2) { - commandActions={0,3,11,-1,1,2,4,5,8}; + commandActions={0,3,11,-1,1,13,2,4,5,8}; if(!panels[active].peer && !panels[active].ftp) { commandActions.insert(commandActions.begin()+1,9); @@ -8795,6 +8797,11 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) } continue; } + if(shift && !ctrl && message.wParam==VK_F3 && !terminalVisible && commandLineAvailable(window)) + { + if(!(message.lParam&(1LL<<30))) openSelectedText(panels[active],false,false,true); + continue; + } if(ctrl && !shift && (message.wParam=='F' || message.wParam=='C' || message.wParam=='R' || (message.wParam=='U' && !terminalVisible) || diff --git a/src/files_text_document.cpp b/src/files_text_document.cpp index 7875f9d..553d423 100644 --- a/src/files_text_document.cpp +++ b/src/files_text_document.cpp @@ -306,6 +306,58 @@ std::string TextDocument::readPage(uint64_t page) const return readOriginal(page); } +std::string TextDocument::readBytes(uint64_t offset,size_t count) const +{ + if(path_.empty() || offset>=size_ || !count) return {}; + const auto length=static_cast(std::min({count,hexPageBytes,size_-offset})); + File temporary{source_==INVALID_HANDLE_VALUE?openSource(path_,false):INVALID_HANDLE_VALUE}; + return read(source_==INVALID_HANDLE_VALUE?temporary.handle:source_,offset,length); +} + +std::string formatHexAddress(uint64_t offset) +{ + constexpr char digits[]="0123456789ABCDEF"; + std::string address(16,'0'); + for(size_t i=address.size();i;offset>>=4) address[--i]=digits[offset&15]; + return address; +} + +std::string formatHexPage(std::string_view bytes,uint64_t offset) +{ + constexpr char digits[]="0123456789ABCDEF"; + constexpr size_t rowBytes=16; + std::string formatted; + formatted.reserve(((bytes.size()+rowBytes-1)/rowBytes)*88); + for(size_t row=0;row(bytes[row+column]); + formatted+=digits[value>>4]; + formatted+=digits[value&15]; + } + else formatted+=" "; + formatted+=' '; + } + formatted+=" |"; + for(size_t column=0;column(bytes[row+column]); + formatted+=value>=0x20 && value<=0x7e?static_cast(value):'.'; + } + formatted.append(rowBytes-length,' '); + formatted+="|\r\n"; + } + if(!formatted.empty()) formatted.resize(formatted.size()-2); + return formatted; +} + std::string TextDocument::readOriginal(uint64_t page) const { if(path_.empty()) return {}; diff --git a/src/files_text_document.h b/src/files_text_document.h index a793bca..00bfa8a 100644 --- a/src/files_text_document.h +++ b/src/files_text_document.h @@ -12,6 +12,10 @@ namespace ks::files enum class TextEncoding { automatic, utf8, utf16le, utf16be, windows1252 }; enum class TextLineEnding { preserve, crlf, lf, cr }; +inline constexpr uint64_t hexPageBytes=64*1024; +std::string formatHexAddress(uint64_t offset); +std::string formatHexPage(std::string_view bytes,uint64_t offset); + struct TextSaveFormat { TextEncoding encoding=TextEncoding::utf8; @@ -35,6 +39,7 @@ public: uint64_t size() const { return size_; } uint64_t boundary(uint64_t page) const; std::string readPage(uint64_t page) const; + std::string readBytes(uint64_t offset,size_t count) const; void releaseReadHandle(); void stage(uint64_t page, std::string_view utf8); bool modified() const { return !changes_.empty(); } diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index 56de86d..5c89af0 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -200,7 +200,7 @@ enum Command : UINT { save = 1, close, findText, findNext, previousPage, nextPage, firstPage, lastPage, goToPage, undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options, switchMode, - historyBack, historyForward, findPrevious, previewEscape, + historyBack, historyForward, findPrevious, previewEscape, switchHex, lexerStart = 1000, }; @@ -743,11 +743,13 @@ public: TextWindow(std::filesystem::path path, bool editable, TextDialogs dialogs,const RemoteTextSource *backend, std::string_view fragment,TextOpenOptions options,bool quickView=false) : original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()), - edit(editable), draft(options.draft), embedded(quickView), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), + edit(editable), draft(options.draft), embedded(quickView), hex(options.hex && !editable), + prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), search{dialogs}, previewFragment(fragment) { if (backend) remote=std::make_unique(*backend,original); - else if(!embedded) document=std::make_unique(draft?std::filesystem::path{}:original,edit,options.encoding); + else if(!embedded) document=std::make_unique(draft?std::filesystem::path{}:original,edit, + hex?TextEncoding::utf8:options.encoding); if(options.encoding!=TextEncoding::automatic) { newFormat.encoding=options.encoding; @@ -783,6 +785,13 @@ private: std::wstring filename; bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{}; bool draft{}, embedded{}; + bool hex{}; + struct ViewerPosition + { + uint64_t page{}; + LRESULT anchor{}, caret{}, firstLine{}, horizontal{}; + }; + std::optional beforeHex; TextSaveFormat newFormat; std::filesystem::path pendingSavePath; HICON smallIcon{},largeIcon{}; @@ -923,6 +932,7 @@ private: void applyLineEnding(); void installLexer(); void loadPage(uint64_t index,std::optional cached={}); + void toggleHex(); void stagePage(); void go(uint64_t index); void saveFile(bool closeWhenDone); @@ -978,7 +988,8 @@ void TextWindow::createMenu() const auto menu = CreateMenu(); const auto file = addGroup(menu, L"&File"); if (edit) addItem(file, save, L"&Save\tF2"); - addItem(file, switchMode, edit ? L"&View\tF6" : L"&Edit\tF6"); + if(!hex) addItem(file, switchMode, edit ? L"&View\tF6" : L"&Edit\tF6"); + if(!edit) addItem(file,switchHex,hex?L"&Text view\tF4":L"View as &hex\tF4"); addItem(file, close, L"&Close\tF10"); const auto actions = addGroup(menu, edit ? L"&Edit" : L"&Selection"); if (edit) @@ -992,52 +1003,58 @@ void TextWindow::createMenu() addItem(actions, copy, L"&Copy\tCtrl+C"); addItem(actions, selectAll, L"Select &page\tCtrl+A"); const auto navigation = addGroup(menu, L"&Navigate"); - if (!edit) + if (!edit && !hex) { addItem(navigation, historyBack, L"&Back\tAlt+Left"); addItem(navigation, historyForward, L"F&orward\tAlt+Right"); AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr); } - addItem(navigation, findText, L"&Find on page…\tCtrl+F"); - addItem(navigation, findNext, L"Find &next\tF3"); - AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr); + if(!hex) + { + addItem(navigation, findText, L"&Find on page…\tCtrl+F"); + addItem(navigation, findNext, L"Find &next\tF3"); + AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr); + } addItem(navigation, previousPage, L"&Previous page\tCtrl+PgUp"); addItem(navigation, nextPage, L"N&ext page\tCtrl+PgDn"); addItem(navigation, firstPage, L"F&irst page\tCtrl+Shift+Home"); addItem(navigation, lastPage, L"&Last page\tCtrl+Shift+End"); addItem(navigation, goToPage, L"&Go to page…\tF5"); - const auto syntax = addGroup(menu, L"S&yntax"); - addItem(syntax, lexerAuto, L"&Automatic"); - addItem(syntax, lexerPlain, L"&Plain text"); - constexpr std::wstring_view groups[] = {L"A–&F", L"G–&L", L"M–&R", L"S–&Z"}; - const wchar_t lastLetters[] = {L'f', L'l', L'r', L'z'}; - HMENU group{}; - size_t groupIndex{}; - std::wstring assignedKeys; - for (size_t i = 0; i < lexers.size(); ++i) + const auto syntax = hex?nullptr:addGroup(menu, L"S&yntax"); + if(syntax) { - auto name = wide(lexers[i]); - const auto letter = std::towlower(name.front()); - while (groupIndex + 1 < std::size(groups) && letter > lastLetters[groupIndex]) + addItem(syntax, lexerAuto, L"&Automatic"); + addItem(syntax, lexerPlain, L"&Plain text"); + constexpr std::wstring_view groups[] = {L"A–&F", L"G–&L", L"M–&R", L"S–&Z"}; + const wchar_t lastLetters[] = {L'f', L'l', L'r', L'z'}; + HMENU group{}; + size_t groupIndex{}; + std::wstring assignedKeys; + for (size_t i = 0; i < lexers.size(); ++i) { - ++groupIndex; - group = nullptr; - assignedKeys.clear(); - } - if (!group) group = addGroup(syntax, groups[groupIndex].data()); - for (size_t position = 0; position < name.size(); ++position) - { - const auto key = static_cast(std::towlower(name[position])); - if (((key >= L'a' && key <= L'z') || (key >= L'0' && key <= L'9')) && - assignedKeys.find(key) == assignedKeys.npos) + auto name = wide(lexers[i]); + const auto letter = std::towlower(name.front()); + while (groupIndex + 1 < std::size(groups) && letter > lastLetters[groupIndex]) { - assignedKeys += key; - name.insert(position, 1, L'&'); - break; + ++groupIndex; + group = nullptr; + assignedKeys.clear(); } + if (!group) group = addGroup(syntax, groups[groupIndex].data()); + for (size_t position = 0; position < name.size(); ++position) + { + const auto key = static_cast(std::towlower(name[position])); + if (((key >= L'a' && key <= L'z') || (key >= L'0' && key <= L'9')) && + assignedKeys.find(key) == assignedKeys.npos) + { + assignedKeys += key; + name.insert(position, 1, L'&'); + break; + } + } + addItem(group, static_cast(lexerStart + i), name.c_str()); } - addItem(group, static_cast(lexerStart + i), name.c_str()); } addItem(menu, options, L"&Options…"); menuRoot = menu; @@ -1191,7 +1208,7 @@ void TextWindow::updateMenus() void TextWindow::installLexer() { - lexer = createTextLexer(language); + lexer = hex?nullptr:createTextLexer(language); send(SCI_SETILEXER, 0, reinterpret_cast(lexer)); applyPreferences(); send(SCI_COLOURISE, 0, -1); @@ -1279,9 +1296,9 @@ void TextWindow::applyPreferences() send(SCI_SETUSETABS, !prefs.tabsAsSpaces); send(SCI_SETTABINDENTS, TRUE); send(SCI_SETBACKSPACEUNINDENTS, TRUE); - send(SCI_SETWRAPMODE, prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE); - send(SCI_SETVIEWWS, prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE); - send(SCI_SETVIEWEOL, prefs.whitespace); + send(SCI_SETWRAPMODE, !hex && prefs.wrap ? SC_WRAP_WORD : SC_WRAP_NONE); + send(SCI_SETVIEWWS, !hex && prefs.whitespace ? SCWS_VISIBLEALWAYS : SCWS_INVISIBLE); + send(SCI_SETVIEWEOL, !hex && prefs.whitespace); applyLineEnding(); updateLineNumberMargin(); layout(); @@ -1291,7 +1308,7 @@ void TextWindow::applyPreferences() void TextWindow::updateLineNumberMargin() { LRESULT width{}; - if (prefs.numbers) + if (prefs.numbers && !hex) { const auto digits = std::to_string(send(SCI_GETLINECOUNT)).size(); const std::string sample(digits, '9'); @@ -1312,12 +1329,13 @@ void TextWindow::applyLineEnding() void TextWindow::loadPage(uint64_t index,std::optional cached) { - auto data=cached?std::move(*cached):document->readPage(index); - const auto offset = document->boundary(index); + const auto offset=hex?index*hexPageBytes:document->boundary(index); + auto data=cached?std::move(*cached):hex?formatHexPage(document->readBytes(offset,hexPageBytes),offset): + document->readPage(index); page = index; pageOffset = offset; - pageTotal = document->pages(); fileSize = document->size(); + pageTotal = hex?1+(fileSize?fileSize-1:0)/hexPageBytes:document->pages(); stagedDirty = document->modified(); const auto eol = data.find_first_of("\r\n"); pageEol = eol == data.npos ? SC_EOL_CRLF : data[eol] == '\n' ? SC_EOL_LF : @@ -1343,6 +1361,49 @@ void TextWindow::loadPage(uint64_t index,std::optional cached) invalidate(); } +void TextWindow::toggleHex() +{ + if(edit || embedded || !document) return; + if(hex) + { + const auto restored=beforeHex.value_or(ViewerPosition{}); + const auto index=std::min(restored.page,document->pages()-1); + auto normal=beforeHex?nullptr:std::make_unique(remote?remote->cache:original,false); + auto text=(normal?normal.get():document.get())->readPage(index); + if(normal) + { + document=std::move(normal); + language=automatic=detectLanguage(original,text); + if(navigationHistory.empty()) navigationHistory.push_back({original,previewFragment}); + } + hex=false; + beforeHex.reset(); + installLexer(); + loadPage(index,std::move(text)); + send(SCI_SETSEL,restored.anchor,restored.caret); + send(SCI_SETFIRSTVISIBLELINE,restored.firstLine); + send(SCI_SETXOFFSET,restored.horizontal); + updatePreview(); + } + else + { + const auto index=pageOffset/hexPageBytes; + const auto offset=index*hexPageBytes; + auto bytes=formatHexPage(document->readBytes(offset,hexPageBytes),offset); + beforeHex=ViewerPosition{page,send(SCI_GETANCHOR),send(SCI_GETCURRENTPOS), + send(SCI_GETFIRSTVISIBLELINE),send(SCI_GETXOFFSET)}; + hex=true; + stopPreview(false,true); + installLexer(); + loadPage(index,std::move(bytes)); + focusContent(); + } + releaseMenu(); + createMenu(); + updateTitle(); + invalidate(); +} + void TextWindow::stagePage() { if (!currentChanged()) return; @@ -1362,6 +1423,15 @@ void TextWindow::go(uint64_t index) void TextWindow::initializeDocument(std::optional firstPage) { + if(hex) + { + releaseMenu(); + createMenu(); + installLexer(); + loadPage(0); + updateTitle(); + return; + } if(!firstPage) firstPage=document->readPage(0); automatic=detectLanguage(original,*firstPage); language=automatic; @@ -1461,7 +1531,7 @@ void TextWindow::finishOpen() { opening.get(); if(cancelOpen) { DestroyWindow(window); return; } - document=std::make_unique(remote->cache,edit); + document=std::make_unique(remote->cache,edit,hex?TextEncoding::utf8:TextEncoding::automatic); initializeDocument(); invalidate(); } @@ -1631,7 +1701,7 @@ void TextWindow::changeMode() void TextWindow::updateTitle() { - const auto title = std::wstring(edit ? L"Editor — " : L"Viewer — ") + + const auto title = std::wstring(edit ? L"Editor — " : hex ? L"Hex Viewer — " : L"Viewer — ") + (remote ? remote->source.name + L" · " : std::wstring{}) + original.wstring(); SetWindowTextW(window,title.c_str()); } @@ -1669,7 +1739,7 @@ void TextWindow::updateTaskbarGroup(bool closing) bool TextWindow::canPreview() const { - return !edit && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit; + return !edit && !hex && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit; } void TextWindow::updatePreview() @@ -1720,8 +1790,8 @@ bool TextWindow::startPreviewBrowser() PostMessageW(window,WM_COMMAND,key==VK_LEFT || key==VK_BROWSER_BACK?historyBack:historyForward,0); return true; } - if(key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false; - PostMessageW(window,WM_COMMAND,key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0); + if(key!=VK_F4 && key!=VK_F6 && key!=VK_ESCAPE && key!=VK_F10 && !(ctrl && key=='W')) return false; + PostMessageW(window,WM_COMMAND,key==VK_F4?switchHex:key==VK_F6?switchMode:key==VK_ESCAPE?previewEscape:close,0); return true; }); } @@ -2284,7 +2354,8 @@ void TextWindow::paint() const auto position=send(SCI_GETCURRENTPOS); const auto line=send(SCI_LINEFROMPOSITION,position)+1; const auto column=send(SCI_GETCOLUMN,position)+1; - auto status=filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+ + auto status=hex?filename+L" (Hex) │ 0x"+wide(formatHexAddress(pageOffset+(line-1)*16)): + filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+ L" │ "+(document?document->encodingName():L"Loading…")+L" │ "+textLanguageLabel(language)+ L" │ Ln "+std::to_wstring(line)+L":"+std::to_wstring(column); if(pageTotal>1) @@ -2293,11 +2364,12 @@ void TextWindow::paint() status+=L" │ "+std::to_wstring(fileSize)+L" B"; drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status); } - const auto hints = busy() ? L"Saving…" : insertRejected ? L"Page edit limit: 8 MiB" : + const auto hints = busy() ? L"Saving…" : hex?L"F4 Text F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close": + insertRejected ? L"Page edit limit: 8 MiB" : edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" : - previewVisible ? L"F6 Edit Ctrl+W Close" : + previewVisible ? L"F4 Hex F6 Edit Ctrl+W Close" : previewWanted ? L"Rendering Markdown… Ctrl+W Close" : - L"F3 Find next F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close"; + L"F3 Find next F4 Hex F5 Go to page F6 Edit Ctrl+PgUp/PgDn Pages F10 Close"; constexpr UINT format = DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX; DrawTextW(dc, hints, -1, &bottom, format); SelectObject(dc, previous); @@ -2348,11 +2420,14 @@ void TextWindow::command(UINT id) { if(!document && id!=close) return; if (busy()) return; + if(hex && (id==switchMode || id==historyBack || id==historyForward || id==findText || id==findNext || + id==findPrevious || id==lexerAuto || id==lexerPlain || id>=lexerStart)) return; switch (id) { case save: saveFile(false); return; case close: requestClose(); return; case switchMode: toggleMode(); return; + case switchHex: toggleHex(); return; case historyBack: case historyForward: if(previewVisible) @@ -2487,10 +2562,12 @@ bool TextWindow::handleKey(const MSG &message) UINT id{}; if (key == VK_F2 || (ctrl && key == 'S')) id = save; if (key == VK_F3) id = findNext; + if (key == VK_F4 && !ctrl && !shift && !edit) id = switchHex; if (key == VK_F5 || (ctrl && key == 'G')) id = goToPage; if (key == VK_F6) id = switchMode; if (key == VK_F9) id = 600; - if (key == VK_ESCAPE || key == VK_F10 || (!edit && ctrl && key=='W')) id = close; + if (key == VK_ESCAPE) id = hex && beforeHex?switchHex:close; + if (key == VK_F10 || (!edit && ctrl && key=='W')) id = close; if (!edit && key==VK_BROWSER_BACK) id=historyBack; if (!edit && key==VK_BROWSER_FORWARD) id=historyForward; if (ctrl && key == 'F') id = findText; @@ -2598,6 +2675,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, case WM_KEYDOWN: if(!self->embedded && self->previewWanted && !self->previewVisible) { + if(wparam==VK_F4) self->command(switchHex); if(wparam==VK_F6) self->toggleMode(); if(wparam==VK_ESCAPE || wparam==VK_F10 || (wparam=='W' && (GetKeyState(VK_CONTROL)&0x8000))) self->requestClose(); @@ -2926,7 +3004,7 @@ void openImageWindow(HWND owner,std::vector images,const static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options) { - if(!edit && !options.draft && isImagePath(path)) + if(!edit && !options.draft && !options.hex && isImagePath(path)) { openImageWindow(owner,{path},path,dialogs,nullptr,backend); return; @@ -2937,7 +3015,7 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool std::error_code error; const auto identity=backend?path.lexically_normal():std::filesystem::weakly_canonical(path,error); const auto &original=error?path:identity; - if(const auto existing=newWindow?nullptr:findOpenDocument(original,backend?backend->id:"")) + if(const auto existing=newWindow || options.hex?nullptr:findOpenDocument(original,backend?backend->id:"")) { if(dialogs.confirmExisting(owner) && IsWindow(existing)) { @@ -2952,7 +3030,7 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool const auto instance=GetModuleHandleW(nullptr); if(!registerTextWindowClass(instance)) throw std::runtime_error("Cannot register the text window."); auto state=std::make_shared(original,edit,dialogs,backend,fragment,options); - const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+ + const auto title=std::wstring(edit?L"Editor — ":options.hex?L"Hex Viewer — ":L"Viewer — ")+ (backend?backend->name+L" · ":std::wstring{})+path.wstring(); RECT bounds{}; GetWindowRect(owner,&bounds); @@ -2974,8 +3052,8 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD } void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, - const RemoteTextSource &source,std::string_view fragment,bool newWindow) + const RemoteTextSource &source,std::string_view fragment,bool newWindow,TextOpenOptions options) { - openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,{}); + openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,options); } } diff --git a/src/files_text_window.h b/src/files_text_window.h index db7fe19..98c084a 100644 --- a/src/files_text_window.h +++ b/src/files_text_window.h @@ -61,6 +61,7 @@ struct TextOpenOptions { TextEncoding encoding=TextEncoding::automatic; bool draft{}; + bool hex{}; }; struct RemoteTextRevision @@ -92,7 +93,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false, TextOpenOptions options={}); void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, - const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false); + const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false,TextOpenOptions options={}); void textWindowOwnerClosed(); bool cycleTextWindows(HWND current,bool reverse); } diff --git a/tests/files_text_document.cpp b/tests/files_text_document.cpp index 5c7321b..4ff152e 100644 --- a/tests/files_text_document.cpp +++ b/tests/files_text_document.cpp @@ -140,8 +140,28 @@ void sparseFile(const fs::path &file) const auto index = document.pages() - 1; check(document.size() == offset + 4 && document.boundary(index) == offset, "Use 64-bit offsets"); check(document.readPage(index) == "last", "Read past 4 GiB"); + const auto raw=document.readBytes(offset-2,8); + check(raw==std::string("\0\0last",6),"Read original bytes across a sparse section beyond 4 GiB"); + check(ks::files::formatHexPage(raw,offset-2).starts_with("000000013FFFFFFE 00 00 6C 61 73 74"), + "Format a 64-bit hex offset and embedded NULs"); document.stage(index, "edited"); check(document.readPage(index) == "edited", "Stage an edit past 4 GiB"); + check(document.readBytes(offset,4)=="last","Hex reads original bytes instead of staged edits"); +} + +void hexBytes(const fs::path &file) +{ + const std::string bytes("\xef\xbb\xbf\0A\xff\x7f\r\n",9); + writeFile(file,bytes); + TextDocument document(file,false); + check(document.boundary(0)==3 && document.readBytes(0,64)==bytes,"Hex includes the original BOM"); + check(document.readBytes(9,40).empty(),"Reading at EOF returns an empty block"); + const auto text=ks::files::formatHexPage(bytes,0); + check(text.starts_with("0000000000000000 EF BB BF 00 41 FF 7F 0D 0A") && + text.ends_with("|....A.... |"),"Hex and ASCII columns retain unprintable bytes and alignment"); + const std::string twoRows(17,'a'); + check(ks::files::formatHexPage(twoRows,0).find("\r\n0000000000000010 61")!=std::string::npos, + "Hex offsets advance by the row width"); } void saveDraft(const fs::path &file) @@ -191,6 +211,7 @@ int main() unicodeBoundaries(fixture.directory / L"unicode.txt"); rejectExternalReplacement(fixture.directory / L"external.txt"); saveDraft(fixture.directory / L"created.txt"); + hexBytes(fixture.directory / L"raw.bin"); sparseFile(fixture.directory / L"5gib.log"); std::cout << "Files text document regressions passed.\n"; } From 50010c99bae16b02ffce72deb2a575f709995d96 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 16:32:23 +0200 Subject: [PATCH 19/61] Persist Viewer bookmarks and reopen files at saved lines Refs #103 --- FILES-UI.md | 9 ++ resources/files.rc | 24 ++++ src/files_main.cpp | 6 +- src/files_text_document.cpp | 56 ++++++++ src/files_text_document.h | 10 ++ src/files_text_window.cpp | 152 +++++++++++++++++++- src/files_text_window.h | 2 + src/files_viewer_bookmarks.inl | 251 +++++++++++++++++++++++++++++++++ tests/files_text_document.cpp | 26 ++++ 9 files changed, 530 insertions(+), 6 deletions(-) create mode 100644 src/files_viewer_bookmarks.inl diff --git a/FILES-UI.md b/FILES-UI.md index 3c95cb0..a6936a9 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -397,6 +397,15 @@ Warning і початковий фокус на No. Ctrl+Shift+Home/End відкривають першу й останню. Ctrl+F шукає в поточній сторінці, F3 повторює пошук. Ctrl+A виділяє поточну сторінку. Історія Undo/Redo діє в межах відкритої сторінки. +- **Ctrl+D** або **Navigate → Add bookmark** у Viewer додає закладку + на рядок локального файла. Номер рахується від початку файла, а назва + необов’язкова. У Markdown номер можна вказати за вихідним текстом. + **Navigate → Bookmarks in this file** і **All bookmarks** відкривають + відповідні списки. **Commands → Viewer bookmarks** у панелях працює, + навіть коли Viewer закрито. Списки зберігаються після перезапуску. + Open переходить до рядка, для Markdown у вихідному тексті. Rename + змінює назву, Remove видаляє закладку. Якщо файл або рядок недоступний, + Files показує повідомлення. - Початкова сторінка займає близько 1 МіБ файла. Для вставок і редагування сторінка може вирости до 8 МіБ у UTF-8. Зміни інших сторінок тимчасово зберігаються на диску. F2 або Ctrl+S потоково записують нову копію в diff --git a/resources/files.rc b/resources/files.rc index 2fff9c9..91d1978 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -100,6 +100,30 @@ BEGIN CONTROL "&Processes…", 103, "Button", BS_OWNERDRAW | WS_TABSTOP | NOT WS_VISIBLE, 14, 38, 75, 15 END +613 DIALOGEX 0, 0, 255, 100 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN +FONT 10, "Consolas" +BEGIN + LTEXT "&Line:", 534, 14, 17, 60, 12 + FAR_EDIT(536, ES_NUMBER | WS_BORDER, 75, 16, 166, 14) + LTEXT "&Name (optional):", 537, 14, 37, 227, 12 + FAR_EDIT(535, WS_BORDER, 14, 50, 227, 14) + CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 76, 60, 16 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 132, 76, 60, 16 +END + +614 DIALOGEX 0, 0, 418, 166 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN +FONT 10, "Consolas" +BEGIN + LTEXT "", 541, 14, 16, 390, 12, SS_PATHELLIPSIS | SS_NOPREFIX + LISTBOX 538, 14, 33, 390, 100, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP + CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 83, 140, 58, 16 + CONTROL "Re&name", 539, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 140, 58, 16 + CONTROL "&Remove", 540, "Button", BS_OWNERDRAW | WS_TABSTOP, 211, 140, 58, 16 + CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 275, 140, 58, 16 +END + 609 DIALOGEX 0, 0, 350, 135 STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN FONT 10, "Consolas" diff --git a/src/files_main.cpp b/src/files_main.cpp index dc7f9c9..12a1621 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -3382,6 +3382,7 @@ void collectFolderSizes(Panel &panel) } void openSelectedText(const Panel &panel, bool edit, bool external,bool hex=false); +ks::files::TextDialogs textWindowDialogs(); void findLocalFiles(HWND owner,Panel &panel); void compareSelectedFiles(HWND owner); void createArchive(HWND owner,Panel &panel); @@ -3538,6 +3539,7 @@ void selectDrive() else if(menuIndex==2 && row==11) copyFullPanelPath(owner,panels[active]); else if(menuIndex==2 && row==12) openSpaceAnalyzer(owner,panels[active]); else if(menuIndex==2 && row==13) openSelectedText(panels[active],false,false,true); + else if(menuIndex==2 && row==14) ks::files::showAllViewerBookmarks(owner,textWindowDialogs()); else if(menuIndex==1 && row==4) createArchive(owner,panels[active]); else { @@ -7512,12 +7514,12 @@ void openMenu(HWND window, int index) L"View externally\tAlt+F3",L"Edit externally\tAlt+F4", L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(), L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q", - L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3"}; + L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…"}; } commandActions.clear(); if(index==2) { - commandActions={0,3,11,-1,1,13,2,4,5,8}; + commandActions={0,3,11,-1,1,13,14,2,4,5,8}; if(!panels[active].peer && !panels[active].ftp) { commandActions.insert(commandActions.begin()+1,9); diff --git a/src/files_text_document.cpp b/src/files_text_document.cpp index 553d423..189c51f 100644 --- a/src/files_text_document.cpp +++ b/src/files_text_document.cpp @@ -314,6 +314,62 @@ std::string TextDocument::readBytes(uint64_t offset,size_t count) const return read(source_==INVALID_HANDLE_VALUE?temporary.handle:source_,offset,length); } +namespace +{ +struct TextLineCounter +{ + uint64_t line=1; + bool afterCr{}; + + void consume(char value) + { + if(value=='\r' || (value=='\n' && !afterCr)) ++line; + afterCr=value=='\r'; + } +}; + +void checkLineScan(std::stop_token stop) +{ + if(stop.stop_requested()) throw std::system_error(ERROR_CANCELLED,std::system_category()); +} +} + +uint64_t TextDocument::lineAt(uint64_t page,size_t offset,std::stop_token stop) const +{ + TextLineCounter counter; + page=std::min(page,pages()-1); + for(uint64_t index=0;index<=page;++index) + { + checkLineScan(stop); + const auto contents=readPage(index); + const auto prefix=index==page?std::string_view(contents).substr(0,offset):std::string_view(contents); + for(const char value:prefix) counter.consume(value); + } + return counter.line; +} + +std::optional TextDocument::locateLine(uint64_t line,std::stop_token stop) const +{ + if(!line) return {}; + TextLineCounter counter; + const auto count=pages(); + size_t end=0; + for(uint64_t index=0;index #include #include +#include +#include #include #include @@ -23,6 +25,12 @@ struct TextSaveFormat TextLineEnding lineEnding=TextLineEnding::preserve; }; +struct TextLineLocation +{ + uint64_t page{}; + size_t offset{}; +}; + class TextDocument { public: @@ -40,6 +48,8 @@ public: uint64_t boundary(uint64_t page) const; std::string readPage(uint64_t page) const; std::string readBytes(uint64_t offset,size_t count) const; + uint64_t lineAt(uint64_t page,size_t offset,std::stop_token stop={}) const; + std::optional locateLine(uint64_t line,std::stop_token stop={}) const; void releaseReadHandle(); void stage(uint64_t page, std::string_view utf8); bool modified() const { return !changes_.empty(); } diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index 5c89af0..9555caa 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -25,6 +25,7 @@ #include "../vendor/json.hpp" #include #include +#include #include #include #include @@ -200,7 +201,7 @@ enum Command : UINT { save = 1, close, findText, findNext, previousPage, nextPage, firstPage, lastPage, goToPage, undo, redo, cut, copy, paste, selectAll, lexerAuto, lexerPlain, options, switchMode, - historyBack, historyForward, findPrevious, previewEscape, switchHex, + historyBack, historyForward, findPrevious, previewEscape, switchHex, addBookmark, currentBookmarks, allBookmarks, lexerStart = 1000, }; @@ -218,6 +219,8 @@ void initializePrompt(TextDialogs style, HWND dialog) SendDlgItemMessageW(dialog, 100, EM_SETSEL, 0, -1); } +#include "files_viewer_bookmarks.inl" + INT_PTR CALLBACK pageDialog(HWND dialog, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_INITDIALOG) @@ -744,6 +747,7 @@ public: std::string_view fragment,TextOpenOptions options,bool quickView=false) : original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()), edit(editable), draft(options.draft), embedded(quickView), hex(options.hex && !editable), + initialBookmark(options.line), prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), search{dialogs}, previewFragment(fragment) { @@ -776,6 +780,7 @@ public: bool handleKey(const MSG &message); void goToFragment(std::string_view fragment); void previewFile(const std::filesystem::path &path); + bool openBookmark(const ViewerBookmark &bookmark); std::filesystem::path original; const std::string peerId; @@ -786,6 +791,8 @@ private: bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{}; bool draft{}, embedded{}; bool hex{}; + uint64_t initialBookmark{}; + bool showBookmarkSource{}; struct ViewerPosition { uint64_t page{}; @@ -874,6 +881,17 @@ private: static constexpr UINT_PTR previewTimer = 3; static constexpr UINT_PTR navigationTimer = 4; static constexpr UINT_PTR quickViewTimer = 5; + static constexpr UINT_PTR bookmarkTimer = 6; + struct BookmarkLocation + { + std::filesystem::path path; + uint64_t line{}; + bool adding{}; + std::optional position; + std::unique_ptr source; + }; + std::future bookmarkTask; + std::stop_source bookmarkStop; struct QuickDocument { std::unique_ptr document; @@ -933,6 +951,9 @@ private: void installLexer(); void loadPage(uint64_t index,std::optional cached={}); void toggleHex(); + void locateBookmark(uint64_t line); + void finishBookmark(); + void pickBookmark(bool currentFile); void stagePage(); void go(uint64_t index); void saveFile(bool closeWhenDone); @@ -1015,6 +1036,13 @@ void TextWindow::createMenu() addItem(navigation, findNext, L"Find &next\tF3"); AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr); } + if(!edit && !hex) + { + addItem(navigation,addBookmark,L"Add &bookmark…\tCtrl+D"); + addItem(navigation,currentBookmarks,L"Bookmarks in &this file…"); + addItem(navigation,allBookmarks,L"&All bookmarks…"); + AppendMenuW(navigation, MF_SEPARATOR, 0, nullptr); + } addItem(navigation, previousPage, L"&Previous page\tCtrl+PgUp"); addItem(navigation, nextPage, L"N&ext page\tCtrl+PgDn"); addItem(navigation, firstPage, L"F&irst page\tCtrl+Shift+Home"); @@ -1404,6 +1432,97 @@ void TextWindow::toggleHex() invalidate(); } +bool TextWindow::openBookmark(const ViewerBookmark &bookmark) +{ + if(edit || hex || embedded || remote || !document || compareBookmarkPaths(original,bookmark.path)!=0) return false; + if(IsIconic(window)) ShowWindow(window,SW_RESTORE); + SetForegroundWindow(window); + locateBookmark(bookmark.line); + return true; +} + +void TextWindow::locateBookmark(uint64_t line) +{ + if(!document || edit || hex || embedded || remote) + { + search.style.message(window,L"Line bookmarks are available for local files in the text Viewer."); + return; + } + if(bookmarkTask.valid()) bookmarkStop.request_stop(); + bookmarkStop=std::stop_source{}; + const auto token=bookmarkStop.get_token(); + const auto currentPage=page; + const auto caret=static_cast(std::max(0,send(SCI_GETCURRENTPOS))); + const auto encoding=document->encoding(); + std::packaged_task task([path=original,currentPage,caret,encoding,line,token] { + auto source=std::make_unique(path,false,encoding); + if(!line) return BookmarkLocation{path,source->lineAt(currentPage,caret,token),true,{},{}}; + const auto position=source->locateLine(line,token); + return BookmarkLocation{path,line,false,position,std::move(source)}; + }); + if(!SetTimer(window,bookmarkTimer,40,nullptr)) throw std::runtime_error("Cannot start locating the bookmarked line."); + bookmarkTask=task.get_future(); + try {std::thread(std::move(task)).detach();} + catch(...) + { + bookmarkTask={}; + KillTimer(window,bookmarkTimer); + throw; + } + invalidateStatus(); +} + +void TextWindow::finishBookmark() +{ + if(!bookmarkTask.valid() || bookmarkTask.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return; + KillTimer(window,bookmarkTimer); + auto result=bookmarkTask.get(); + invalidateStatus(); + if(edit || hex || !document || compareBookmarkPaths(result.path,original)!=0) return; + if(result.adding) + { + BookmarkPrompt prompt{search.style,{result.path,result.line,{}}}; + const auto bookmarks=readViewerBookmarks(viewerBookmarksFile()); + const auto same=std::find_if(bookmarks.begin(),bookmarks.end(),[&](const auto &entry){ + return sameViewerBookmark(entry,prompt.bookmark); + }); + if(same!=bookmarks.end()) prompt.bookmark.name=same->name; + if(search.style.run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(613),window,bookmarkNameDialog, + reinterpret_cast(&prompt))==IDOK) focusContent(); + return; + } + if(!result.position) + { + search.style.message(window,L"The bookmarked line is no longer in the file."); + return; + } + showBookmarkSource=true; + if(previewWanted || previewVisible) stopPreview(true,true); + document=std::move(result.source); + loadPage(result.position->page); + send(SCI_GOTOPOS,result.position->offset); + send(SCI_SCROLLCARET); + focusContent(); +} + +void openChosenBookmark(HWND owner,TextDialogs style,const ViewerBookmark &bookmark) +{ + for(const auto &entry:textWindows) + if(entry.second->openBookmark(bookmark)) return; + openTextWindow(owner,bookmark.path,false,style,nullptr,{},true,{.line=bookmark.line}); +} + +void TextWindow::pickBookmark(bool currentFile) +{ + if(currentFile && remote) + { + search.style.message(window,L"Line bookmarks are available for local files in the text Viewer."); + return; + } + const auto selected=selectViewerBookmark(window,search.style,currentFile?original:std::filesystem::path{}); + if(selected) openChosenBookmark(window,search.style,*selected); +} + void TextWindow::stagePage() { if (!currentChanged()) return; @@ -1445,6 +1564,7 @@ void TextWindow::initializeDocument(std::optional firstPage) installLexer(); loadPage(0,std::move(firstPage)); updatePreview(); + if(initialBookmark) locateBookmark(std::exchange(initialBookmark,0)); } std::string readMarkdownDocument(TextDocument &document) @@ -1739,7 +1859,8 @@ void TextWindow::updateTaskbarGroup(bool closing) bool TextWindow::canPreview() const { - return !edit && !hex && automatic.lexer=="markdown" && document && document->size()<=TextDocument::editLimit; + return !edit && !hex && !showBookmarkSource && automatic.lexer=="markdown" && document && + document->size()<=TextDocument::editLimit; } void TextWindow::updatePreview() @@ -1780,6 +1901,11 @@ bool TextWindow::startPreviewBrowser() PostMessageW(window,WM_COMMAND,key=='F'?findText:shift?findPrevious:findNext,0); return true; } + if(ctrl && !alt && key=='D') + { + PostMessageW(window,WM_COMMAND,addBookmark,0); + return true; + } if(ctrl && !alt && key==VK_TAB) { PostMessageW(window,cycleWindow,(GetKeyState(VK_SHIFT)&0x8000)!=0,0); @@ -2362,6 +2488,7 @@ void TextWindow::paint() status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+ L" @ "+std::to_wstring(pageOffset); status+=L" │ "+std::to_wstring(fileSize)+L" B"; + if(bookmarkTask.valid()) status+=L" │ Locating line…"; drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status); } const auto hints = busy() ? L"Saving…" : hex?L"F4 Text F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close": @@ -2428,6 +2555,9 @@ void TextWindow::command(UINT id) case close: requestClose(); return; case switchMode: toggleMode(); return; case switchHex: toggleHex(); return; + case addBookmark: if(!edit && !hex) locateBookmark(0); return; + case currentBookmarks: if(!edit && !hex) pickBookmark(true); return; + case allBookmarks: if(!edit && !hex) pickBookmark(false); return; case historyBack: case historyForward: if(previewVisible) @@ -2571,6 +2701,7 @@ bool TextWindow::handleKey(const MSG &message) if (!edit && key==VK_BROWSER_BACK) id=historyBack; if (!edit && key==VK_BROWSER_FORWARD) id=historyForward; if (ctrl && key == 'F') id = findText; + if (ctrl && key == 'D' && !edit && !hex) id = addBookmark; if (ctrl && key == VK_PRIOR) id = previousPage; if (ctrl && key == VK_NEXT) id = nextPage; if (ctrl && shift && key == VK_HOME) id = firstPage; @@ -2736,6 +2867,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, if (wparam == previewTimer) self->pollImages(); if (wparam == navigationTimer) self->finishNavigation(); if (wparam == quickViewTimer) self->pollQuickView(); + if (wparam == bookmarkTimer) self->finishBookmark(); return 0; case trimUndo: if (self->undoBytes >= 32 * TextDocument::pageBytes) @@ -2747,6 +2879,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, } return 0; case WM_DESTROY: + self->bookmarkStop.request_stop(); if(self->cancelNavigation) *self->cancelNavigation=true; if(!self->embedded) self->updateTaskbarGroup(true); self->stopPreview(false); @@ -3004,7 +3137,7 @@ void openImageWindow(HWND owner,std::vector images,const static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options) { - if(!edit && !options.draft && !options.hex && isImagePath(path)) + if(!edit && !options.draft && !options.hex && !options.line && isImagePath(path)) { openImageWindow(owner,{path},path,dialogs,nullptr,backend); return; @@ -3015,7 +3148,8 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool std::error_code error; const auto identity=backend?path.lexically_normal():std::filesystem::weakly_canonical(path,error); const auto &original=error?path:identity; - if(const auto existing=newWindow || options.hex?nullptr:findOpenDocument(original,backend?backend->id:"")) + if(const auto existing=newWindow || options.hex || options.line?nullptr: + findOpenDocument(original,backend?backend->id:"")) { if(dialogs.confirmExisting(owner) && IsWindow(existing)) { @@ -3056,4 +3190,14 @@ void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit { openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,options); } + +void showAllViewerBookmarks(HWND owner,TextDialogs dialogs) +{ + try + { + const auto selected=selectViewerBookmark(owner,dialogs); + if(selected) openChosenBookmark(owner,dialogs,*selected); + } + catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());} +} } diff --git a/src/files_text_window.h b/src/files_text_window.h index 98c084a..a7c0764 100644 --- a/src/files_text_window.h +++ b/src/files_text_window.h @@ -62,6 +62,7 @@ struct TextOpenOptions TextEncoding encoding=TextEncoding::automatic; bool draft{}; bool hex{}; + uint64_t line{}; }; struct RemoteTextRevision @@ -88,6 +89,7 @@ HWND createImageQuickView(HWND owner,TextDialogs dialogs); void previewImageQuickViewFile(HWND window,const std::filesystem::path &path); void openImageWindow(HWND owner,std::vector images,const std::filesystem::path &path, TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr); +void showAllViewerBookmarks(HWND owner,TextDialogs dialogs); void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, const lan::FilesPeer *peer=nullptr,std::string_view fragment={},bool newWindow=false, diff --git a/src/files_viewer_bookmarks.inl b/src/files_viewer_bookmarks.inl new file mode 100644 index 0000000..9d6acfe --- /dev/null +++ b/src/files_viewer_bookmarks.inl @@ -0,0 +1,251 @@ +struct ViewerBookmark +{ + std::filesystem::path path; + uint64_t line{}; + std::wstring name; +}; + +int compareBookmarkPaths(const std::filesystem::path &left,const std::filesystem::path &right) +{ + return CompareStringOrdinal(left.c_str(),-1,right.c_str(),-1,TRUE)-CSTR_EQUAL; +} + +bool sameViewerBookmark(const ViewerBookmark &left,const ViewerBookmark &right) +{ + return left.line==right.line && compareBookmarkPaths(left.path,right.path)==0; +} + +std::vector readViewerBookmarks(const std::filesystem::path &file) +{ + if(!std::filesystem::exists(file)) return {}; + const auto saved=nlohmann::json::parse(readFile(file,2*1024*1024)); + if(!saved.is_array()) throw std::runtime_error("Could not read the Viewer bookmarks."); + std::vector bookmarks; + for(const auto &item:saved) + { + if(!item.is_object() || !item.contains("path") || !item["path"].is_string() || + !item.contains("line") || !item["line"].is_number_unsigned()) continue; + std::filesystem::path path=wide(item["path"].get()); + const auto line=item["line"].get(); + if(!path.is_absolute() || !line || path.native().find(L'\0')!=std::wstring::npos) continue; + std::wstring name; + if(item.contains("name") && item["name"].is_string()) name=wide(item["name"].get()); + if(name.find(L'\0')!=std::wstring::npos) name.clear(); + bookmarks.push_back({std::move(path),line,std::move(name)}); + } + std::sort(bookmarks.begin(),bookmarks.end(),[](const auto &left,const auto &right) { + const auto pathOrder=compareBookmarkPaths(left.path,right.path); + return pathOrder?pathOrder<0:left.linename=bookmark.name; + auto saved=nlohmann::json::array(); + for(const auto &entry:bookmarks) + saved.push_back({{"path",utf8(entry.path.native())},{"line",entry.line},{"name",utf8(entry.name)}}); + const auto contents=saved.dump(); + if(contents.size()>2*1024*1024) throw std::runtime_error("Viewer bookmark storage is full."); + atomicWrite(file,Bytes(contents.begin(),contents.end())); +} + +struct BookmarkPrompt +{ + TextDialogs style; + ViewerBookmark bookmark; + bool rename{}; +}; + +constexpr int bookmarkName=535, bookmarkLine=536, bookmarkList=538, bookmarkRename=539, bookmarkRemove=540; + +INT_PTR CALLBACK bookmarkNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + SetWindowLongPtrW(dialog,DWLP_USER,lp); + auto &prompt=*reinterpret_cast(lp); + prompt.style.prepare(dialog); + SetDlgItemTextW(dialog,bookmarkName,prompt.bookmark.name.c_str()); + SetDlgItemTextW(dialog,bookmarkLine,std::to_wstring(prompt.bookmark.line).c_str()); + SendDlgItemMessageW(dialog,bookmarkName,EM_SETLIMITTEXT,160,0); + SendDlgItemMessageW(dialog,bookmarkLine,EM_SETLIMITTEXT,20,0); + SendDlgItemMessageW(dialog,bookmarkLine,EM_SETREADONLY,prompt.rename,0); + SendMessageW(dialog,DM_SETDEFID,IDOK,0); + SetFocus(GetDlgItem(dialog,bookmarkName)); + SendDlgItemMessageW(dialog,bookmarkName,EM_SETSEL,0,-1); + return FALSE; + } + const auto prompt=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(!prompt) return FALSE; + if(const auto painted=prompt->style.paint(dialog,message,wp,lp,prompt->rename?L" Rename bookmark ":L" Add bookmark ")) + return painted; + if(message!=WM_COMMAND) return FALSE; + if(LOWORD(wp)==IDCANCEL) {prompt->style.finish(dialog,IDCANCEL);return TRUE;} + if(LOWORD(wp)!=IDOK) return FALSE; + wchar_t line[24]{}; + GetDlgItemTextW(dialog,bookmarkLine,line,static_cast(std::size(line))); + wchar_t *end=nullptr; + errno=0; + const auto number=std::wcstoull(line,&end,10); + if(!number || errno==ERANGE || *end || line[0]L'9') + { + prompt->style.message(dialog,L"Enter a positive line number."); + SetFocus(GetDlgItem(dialog,bookmarkLine)); + return TRUE; + } + wchar_t name[161]{}; + GetDlgItemTextW(dialog,bookmarkName,name,static_cast(std::size(name))); + prompt->bookmark.line=number; + prompt->bookmark.name=name; + try {changeViewerBookmark(prompt->bookmark,prompt->rename?BookmarkChange::rename:BookmarkChange::upsert);} + catch(const std::exception &error) + { + prompt->style.message(dialog,wide(error.what()).c_str()); + return TRUE; + } + prompt->style.finish(dialog,IDOK); + return TRUE; +} + +struct ViewerBookmarkList +{ + TextDialogs style; + std::filesystem::path filter; + std::vector bookmarks; + std::optional opening; +}; + +void showBookmarkPath(HWND dialog,const ViewerBookmarkList &state) +{ + const auto row=SendDlgItemMessageW(dialog,bookmarkList,LB_GETCURSEL,0,0); + SetDlgItemTextW(dialog,541,row>=0 && static_cast(row)(font)); + LONG width=0; + for(const auto &item:state.bookmarks) + { + auto label=L"Line "+std::to_wstring(item.line); + if(state.filter.empty()) label+=L" "+item.path.filename().native(); + if(!item.name.empty()) label+=L" "+item.name; + SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast(label.c_str())); + SIZE dimensions{}; + if(dc && GetTextExtentPoint32W(dc,label.c_str(),static_cast(label.size()),&dimensions)) + width=std::max(width,dimensions.cx); + } + if(oldFont) SelectObject(dc,oldFont); + if(dc) ReleaseDC(list,dc); + SendMessageW(list,LB_SETHORIZONTALEXTENT,width,0); + const bool rows=!state.bookmarks.empty(); + if(rows) SendMessageW(list,LB_SETCURSEL,std::clamp(oldSelection,0,state.bookmarks.size()-1),0); + showBookmarkPath(dialog,state); + for(const auto button:{IDOK,bookmarkRename,bookmarkRemove}) EnableWindow(GetDlgItem(dialog,button),rows); +} + +INT_PTR CALLBACK viewerBookmarkDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + SetWindowLongPtrW(dialog,DWLP_USER,lp); + auto &state=*reinterpret_cast(lp); + state.style.prepare(dialog); + try {renderBookmarkList(dialog,state,0);} + catch(const std::exception &error) {state.style.message(dialog,wide(error.what()).c_str());} + SetFocus(GetDlgItem(dialog,state.bookmarks.empty()?IDCANCEL:bookmarkList)); + SendMessageW(dialog,DM_SETDEFID,IDOK,0); + return FALSE; + } + auto *state=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(!state) return FALSE; + if(const auto painted=state->style.paint(dialog,message,wp,lp, + state->filter.empty()?L" All Viewer bookmarks ":L" Bookmarks in this file ")) return painted; + if(message!=WM_COMMAND) return FALSE; + const auto id=LOWORD(wp); + if(id==IDCANCEL) {state->style.finish(dialog,IDCANCEL);return TRUE;} + if(id==bookmarkList && HIWORD(wp)==LBN_SELCHANGE) {showBookmarkPath(dialog,*state); return TRUE;} + const bool open=id==IDOK || (id==bookmarkList && HIWORD(wp)==LBN_DBLCLK); + if(!open && id!=bookmarkRename && id!=bookmarkRemove) return FALSE; + const auto selected=SendDlgItemMessageW(dialog,bookmarkList,LB_GETCURSEL,0,0); + if(selected<0 || static_cast(selected)>=state->bookmarks.size()) return TRUE; + const auto entry=state->bookmarks[selected]; + try + { + if(open) + { + const auto attr=GetFileAttributesW(entry.path.c_str()); + if(attr==INVALID_FILE_ATTRIBUTES || attr&FILE_ATTRIBUTE_DIRECTORY) + throw std::runtime_error("The bookmarked file is unavailable."); + state->opening=entry; + state->style.finish(dialog,IDOK); + } + else if(id==bookmarkRename) + { + BookmarkPrompt prompt{state->style,entry,true}; + if(state->style.run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(613),dialog,bookmarkNameDialog, + reinterpret_cast(&prompt))==IDOK) renderBookmarkList(dialog,*state,selected); + } + else + { + changeViewerBookmark(entry,BookmarkChange::remove); + renderBookmarkList(dialog,*state,selected); + } + } + catch(const std::exception &error) {state->style.message(dialog,wide(error.what()).c_str());} + return TRUE; +} + +std::optional selectViewerBookmark(HWND owner,TextDialogs style,std::filesystem::path filter={}) +{ + ViewerBookmarkList state{style,std::move(filter)}; + if(style.run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(614),owner,viewerBookmarkDialog, + reinterpret_cast(&state))==IDOK) return std::move(state.opening); + return {}; +} diff --git a/tests/files_text_document.cpp b/tests/files_text_document.cpp index 4ff152e..29d70aa 100644 --- a/tests/files_text_document.cpp +++ b/tests/files_text_document.cpp @@ -164,6 +164,31 @@ void hexBytes(const fs::path &file) "Hex offsets advance by the row width"); } +void bookmarkedLines(const fs::path &file) +{ + const auto longLine=std::string(TextDocument::pageBytes+32,'x'); + writeFile(file,"first\r\n"+longLine+"\r\nending\rtail\n"); + TextDocument document(file,false); + check(document.pages()==2 && document.lineAt(1,0)==3,"Absolute line numbering at a paged boundary"); + const auto second=document.locateLine(2); + check(second && second->page==0 && second->offset==7,"Locate an original CRLF line"); + const auto third=document.locateLine(3); + check(third && document.readPage(third->page).substr(third->offset).starts_with("ending"), + "Find a line after a long line and a page boundary"); + const auto fourth=document.locateLine(4); + check(fourth && document.readPage(fourth->page).substr(fourth->offset).starts_with("tail"), + "Locate a line after CR"); + const auto empty=document.locateLine(5); + check(empty && document.readPage(empty->page).size()==empty->offset && !document.locateLine(6), + "Locate the trailing empty line and reject out-of-range bookmarks"); + std::stop_source canceled; + canceled.request_stop(); + bool rejected=false; + try {document.locateLine(3,canceled.get_token());} + catch(const std::system_error &error) {rejected=error.code().value()==ERROR_CANCELLED;} + check(rejected,"Cancel a bookmark scan"); +} + void saveDraft(const fs::path &file) { TextDocument draft({}); @@ -212,6 +237,7 @@ int main() rejectExternalReplacement(fixture.directory / L"external.txt"); saveDraft(fixture.directory / L"created.txt"); hexBytes(fixture.directory / L"raw.bin"); + bookmarkedLines(fixture.directory / L"bookmarks.txt"); sparseFile(fixture.directory / L"5gib.log"); std::cout << "Files text document regressions passed.\n"; } From 872c03823fa83b3f6c962d7a8a25d882231f55e7 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 16:40:26 +0200 Subject: [PATCH 20/61] Keep editor drafts when switching to the saved Viewer Refs #104 --- FILES-UI.md | 7 +- src/files_text_window.cpp | 215 ++++++++++++++++++++++++++++---------- 2 files changed, 163 insertions(+), 59 deletions(-) diff --git a/FILES-UI.md b/FILES-UI.md index a6936a9..83943b0 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -311,8 +311,11 @@ Warning і початковий фокус на No. При повторному відкритті Files пропонує перейти до вже відкритого вікна. Закриття менеджера залишає вікна файлів відкритими. - У цьому вікні F6 перемикає перегляд і редагування для поточного файла. - За наявності змін перехід у перегляд пропонує Save, Discard або Cancel. - Помилка збереження залишає відкритим редактор зі змінами. + Viewer показує збережену версію, а чернетка зберігається в поточному + вікні з позначкою Draft retained. Повторне F6 повертає правки, сторінку, + виділення й прокрутку. + Для нового файла Viewer показує порожній документ. Закриття вікна + з чернеткою в обох режимах пропонує Save, Discard або Cancel. - **Shift+F3** або **Commands → View as hex** відкриває файл у Hex Viewer. **F4** у Viewer перемикає текстовий або форматований перегляд і Hex. Hex показує 64-бітну адресу, 16 вихідних байтів у рядку й ASCII. diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index 9555caa..668ec77 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -666,6 +666,19 @@ struct RemoteTextFile } }; +std::future> fetchRemoteText(const RemoteTextSource &source, + const std::filesystem::path &path,const std::shared_ptr> &canceled) +{ + std::packaged_task()> task([source,path,canceled] { + auto file=std::make_unique(source,path); + file->download(false,[canceled](uint64_t,uint64_t){return !*canceled;}); + return file; + }); + auto result=task.get_future(); + std::thread(std::move(task)).detach(); + return result; +} + class TextWindow; std::map> textWindows; std::vector textWindowOrder; @@ -773,6 +786,7 @@ public: static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam); ~TextWindow() { + if(savedViewerFile) document.reset(); if(smallIcon) DestroyIcon(smallIcon); if(largeIcon) DestroyIcon(largeIcon); } @@ -799,6 +813,16 @@ private: LRESULT anchor{}, caret{}, firstLine{}, horizontal{}; }; std::optional beforeHex; + struct SuspendedEditor + { + std::unique_ptr document; + ViewerPosition position; + bool uploadPending{}; + }; + std::optional suspendedEditor; + std::unique_ptr savedViewerFile; + std::future> savedViewerLoad; + std::shared_ptr> cancelSavedViewer; TextSaveFormat newFormat; std::filesystem::path pendingSavePath; HICON smallIcon{},largeIcon{}; @@ -821,7 +845,6 @@ private: int pageEol = SC_EOL_CRLF; size_t undoBytes{}; bool uploadPending{}; - bool switchAfterSave{}; FilesTerminalView preview; bool previewWanted{}, previewVisible{}, previewRetried{}; ULONGLONG previewDeadline{}; @@ -882,6 +905,7 @@ private: static constexpr UINT_PTR navigationTimer = 4; static constexpr UINT_PTR quickViewTimer = 5; static constexpr UINT_PTR bookmarkTimer = 6; + static constexpr UINT_PTR savedViewerTimer = 7; struct BookmarkLocation { std::filesystem::path path; @@ -961,6 +985,13 @@ private: void requestClose(); void toggleMode(); void changeMode(); + ViewerPosition currentPosition() const; + void restorePosition(const ViewerPosition &position); + void showTextMode(const ViewerPosition &position,std::string contents); + void suspendEditor(std::unique_ptr saved={}); + void restoreEditor(); + void finishSavedViewer(); + void cancelSavedViewerLoad(); bool needsSave() const; bool canPreview() const; void updatePreview(); @@ -1408,9 +1439,7 @@ void TextWindow::toggleHex() beforeHex.reset(); installLexer(); loadPage(index,std::move(text)); - send(SCI_SETSEL,restored.anchor,restored.caret); - send(SCI_SETFIRSTVISIBLELINE,restored.firstLine); - send(SCI_SETXOFFSET,restored.horizontal); + restorePosition(restored); updatePreview(); } else @@ -1418,8 +1447,7 @@ void TextWindow::toggleHex() const auto index=pageOffset/hexPageBytes; const auto offset=index*hexPageBytes; auto bytes=formatHexPage(document->readBytes(offset,hexPageBytes),offset); - beforeHex=ViewerPosition{page,send(SCI_GETANCHOR),send(SCI_GETCURRENTPOS), - send(SCI_GETFIRSTVISIBLELINE),send(SCI_GETXOFFSET)}; + beforeHex=currentPosition(); hex=true; stopPreview(false,true); installLexer(); @@ -1664,14 +1692,13 @@ void TextWindow::finishOpen() void TextWindow::saveFile(bool closeWhenDone) { - if (busy() || !edit) return; + if (busy() || savedViewerLoad.valid() || !edit) return; auto destination=original; if(draft && !search.style.saveOptions(window,destination,newFormat)) return; stagePage(); if (!draft && !stagedDirty && !uploadPending) { if (closeWhenDone) DestroyWindow(window); - else if (std::exchange(switchAfterSave, false)) changeMode(); return; } pendingCaret = send(SCI_GETCURRENTPOS); @@ -1712,7 +1739,6 @@ void TextWindow::finishSave() return; } send(SCI_SETREADONLY, !edit); - const auto change = std::exchange(switchAfterSave, false); const auto reopened = saving.get(); stagedDirty = false; const bool created=std::exchange(draft,false); @@ -1730,7 +1756,6 @@ void TextWindow::finishSave() return; } if (closeAfterSave) { DestroyWindow(window); return; } - if (change) { changeMode(); return; } if(created) { initializeDocument(); @@ -1751,11 +1776,17 @@ void TextWindow::requestClose() { if (opening.valid()) { cancelOpen=true; return; } if (busy()) return; + cancelSavedViewerLoad(); if (needsSave()) { const auto answer = search.style.confirmSave(window,draft); if (answer == IDCANCEL) return; - if (answer == IDYES) { saveFile(true); return; } + if (answer == IDYES) + { + if(suspendedEditor) restoreEditor(); + saveFile(true); + return; + } if (answer != IDNO) return; } DestroyWindow(window); @@ -1763,54 +1794,61 @@ void TextWindow::requestClose() bool TextWindow::needsSave() const { + if(suspendedEditor) return suspendedEditor->uploadPending || suspendedEditor->document->modified(); return uploadPending || (currentChanged() ? document->modifiedWith(page, pageText()) : stagedDirty); } void TextWindow::toggleMode() { - if (busy() || navigation.valid()) return; - if(draft) return; - if (edit && needsSave()) + if (busy() || navigation.valid() || savedViewerLoad.valid()) return; + if(suspendedEditor) { - const auto answer = search.style.confirmSave(window,false); - if (answer == IDYES) + restoreEditor(); + return; + } + if(edit && (draft || needsSave())) + { + if(!uploadPending) suspendEditor(); + else { - switchAfterSave = true; - try { saveFile(false); } - catch (...) { switchAfterSave = false; throw; } - return; - } - if (answer != IDNO) return; - // The local LAN cache may already contain changes from a failed upload. - if (uploadPending) - { - auto refreshed = std::make_unique(remote->source,original); - refreshed->download(false,{}); - auto replacement = std::make_unique(refreshed->cache,false); - document.reset(); - remote = std::move(refreshed); - document = std::move(replacement); - uploadPending = false; + auto cancel=std::make_shared>(false); + if(!SetTimer(window,savedViewerTimer,75,nullptr)) + throw std::runtime_error("Cannot start loading the saved version."); + try + { + savedViewerLoad=fetchRemoteText(remote->source,original,cancel); + cancelSavedViewer=std::move(cancel); + } + catch(...) {KillTimer(window,savedViewerTimer); throw;} + invalidate(); } + return; } changeMode(); } -void TextWindow::changeMode() +TextWindow::ViewerPosition TextWindow::currentPosition() const +{ + return {page,send(SCI_GETANCHOR),send(SCI_GETCURRENTPOS),send(SCI_GETFIRSTVISIBLELINE),send(SCI_GETXOFFSET)}; +} + +void TextWindow::restorePosition(const ViewerPosition &position) +{ + const auto length=send(SCI_GETLENGTH); + send(SCI_SETSEL,std::clamp(position.anchor,0,length),std::clamp(position.caret,0,length)); + send(SCI_SETFIRSTVISIBLELINE,position.firstLine); + send(SCI_SETXOFFSET,position.horizontal); +} + +void TextWindow::showTextMode(const ViewerPosition &position,std::string contents) { - if (!edit && remote && !remote->revision.editable) - throw std::runtime_error("The remote file does not support editing."); - auto replacement = std::make_unique(remote ? remote->cache : original, !edit); - const auto caret = send(SCI_GETCURRENTPOS); - document = std::move(replacement); - edit = !edit; if(canPreview()) ShowWindow(editor,SW_HIDE); prefs = loadTextPreferences().profiles[edit]; releaseMenu(); createMenu(); installLexer(); - loadPage(std::min(page, document->pages() - 1)); - send(SCI_GOTOPOS, std::min(caret, send(SCI_GETLENGTH))); + loadPage(position.page,std::move(contents)); + restorePosition(position); updateTitle(); updateIcons(GetDpiForWindow(window)); updateTaskbarGroup(); @@ -1819,6 +1857,68 @@ void TextWindow::changeMode() focusContent(); } +void TextWindow::changeMode() +{ + if(!edit && remote && !remote->revision.editable) + throw std::runtime_error("The remote file does not support editing."); + auto position=currentPosition(); + auto replacement=std::make_unique(remote?remote->cache:original,!edit,document->encoding()); + position.page=std::min(position.page,replacement->pages()-1); + auto contents=replacement->readPage(position.page); + document=std::move(replacement); + edit=!edit; + showTextMode(position,std::move(contents)); +} + +void TextWindow::suspendEditor(std::unique_ptr saved) +{ + const auto position=currentPosition(); + const auto path=draft?std::filesystem::path{}:saved?saved->cache:remote?remote->cache:original; + auto replacement=std::make_unique(path,false,document->encoding()); + auto viewing=position; + viewing.page=std::min(viewing.page,replacement->pages()-1); + auto contents=replacement->readPage(viewing.page); + stagePage(); + suspendedEditor=SuspendedEditor{std::move(document),position,std::exchange(uploadPending,false)}; + document=std::move(replacement); + savedViewerFile=std::move(saved); + edit=false; + showTextMode(viewing,std::move(contents)); +} + +void TextWindow::restoreEditor() +{ + const auto position=suspendedEditor->position; + auto contents=suspendedEditor->document->readPage(position.page); + document=std::move(suspendedEditor->document); + uploadPending=suspendedEditor->uploadPending; + suspendedEditor.reset(); + savedViewerFile.reset(); + edit=true; + hex=false; + beforeHex.reset(); + showTextMode(position,std::move(contents)); +} + +void TextWindow::finishSavedViewer() +{ + if(!savedViewerLoad.valid() || savedViewerLoad.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return; + KillTimer(window,savedViewerTimer); + cancelSavedViewer.reset(); + invalidate(); + suspendEditor(savedViewerLoad.get()); +} + +void TextWindow::cancelSavedViewerLoad() +{ + if(!savedViewerLoad.valid()) return; + *cancelSavedViewer=true; + cancelSavedViewer.reset(); + savedViewerLoad={}; + KillTimer(window,savedViewerTimer); + invalidate(); +} + void TextWindow::updateTitle() { const auto title = std::wstring(edit ? L"Editor — " : hex ? L"Hex Viewer — " : L"Viewer — ") + @@ -1985,7 +2085,7 @@ void TextWindow::renderPreview(bool keepPosition) previewText=quickMarkdown?*quickMarkdown:readMarkdownDocument(*document); if(!remote) document->releaseReadHandle(); nlohmann::json message{{"action","render"},{"text",previewText},{"revision",++previewRevision}, - {"canSave",!embedded && (!remote || remote->revision.editable)},{"compact",embedded}, + {"canSave",!embedded && !suspendedEditor && (!remote || remote->revision.editable)},{"compact",embedded}, {"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)}, {"keepPosition",keepPosition}}; if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll; @@ -2035,7 +2135,7 @@ void TextWindow::startMarkdownTask() { const auto task=std::exchange(pendingTask,{}); if(!task) return; - if(!previewVisible || edit || busy() || navigation.valid() || task->revision!=previewRevision || + if(!previewVisible || edit || suspendedEditor || busy() || navigation.valid() || task->revision!=previewRevision || (remote && !remote->revision.editable)) { reportMarkdownTask(task->revision,false); @@ -2225,13 +2325,18 @@ void TextWindow::previewMessage(const std::wstring &value) void TextWindow::syncNavigation() { - preview.post(wide(nlohmann::json{{"action","history"},{"back",navigationIndex>0}, - {"forward",navigationIndex+10}, + {"forward",!suspendedEditor && navigationIndex+1>(false); - std::packaged_task()> task( - [backend=remote->source,path=destination.path,cancel] { - auto file=std::make_unique(backend,path); - file->download(false,[cancel](uint64_t,uint64_t){return !*cancel;}); - return file; - }); if(!SetTimer(window,navigationTimer,75,nullptr)) throw std::runtime_error("Cannot start the remote navigation timer."); try { - auto result=task.get_future(); - std::thread(std::move(task)).detach(); - navigation=std::move(result); + navigation=fetchRemoteText(remote->source,destination.path,cancel); cancelNavigation=std::move(cancel); } catch(...) { KillTimer(window,navigationTimer); throw; } @@ -2480,8 +2577,9 @@ void TextWindow::paint() const auto position=send(SCI_GETCURRENTPOS); const auto line=send(SCI_LINEFROMPOSITION,position)+1; const auto column=send(SCI_GETCOLUMN,position)+1; - auto status=hex?filename+L" (Hex) │ 0x"+wide(formatHexAddress(pageOffset+(line-1)*16)): - filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+ + const auto retained=suspendedEditor?L" │ Draft retained":L""; + auto status=hex?filename+L" (Hex)"+retained+L" │ 0x"+wide(formatHexAddress(pageOffset+(line-1)*16)): + filename+(edit?L" (Edit)":L" (View)")+(dirty()?L" *":L"")+retained+ L" │ "+(document?document->encodingName():L"Loading…")+L" │ "+textLanguageLabel(language)+ L" │ Ln "+std::to_wstring(line)+L":"+std::to_wstring(column); if(pageTotal>1) @@ -2491,7 +2589,8 @@ void TextWindow::paint() if(bookmarkTask.valid()) status+=L" │ Locating line…"; drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status); } - const auto hints = busy() ? L"Saving…" : hex?L"F4 Text F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close": + const auto hints = busy() ? L"Saving…" : savedViewerLoad.valid()?L"Loading saved version…" : + hex?L"F4 Text F5 Go to page Ctrl+PgUp/PgDn Pages F10 Close": insertRejected ? L"Page edit limit: 8 MiB" : edit ? L"F2 Save F3 Find next F5 Go to page F6 View Ctrl+PgUp/PgDn Pages F10 Close" : previewVisible ? L"F4 Hex F6 Edit Ctrl+W Close" : @@ -2868,6 +2967,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, if (wparam == navigationTimer) self->finishNavigation(); if (wparam == quickViewTimer) self->pollQuickView(); if (wparam == bookmarkTimer) self->finishBookmark(); + if (wparam == savedViewerTimer) self->finishSavedViewer(); return 0; case trimUndo: if (self->undoBytes >= 32 * TextDocument::pageBytes) @@ -2879,6 +2979,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, } return 0; case WM_DESTROY: + self->cancelSavedViewerLoad(); self->bookmarkStop.request_stop(); if(self->cancelNavigation) *self->cancelNavigation=true; if(!self->embedded) self->updateTaskbarGroup(true); From 5bf2d7ab455e2a68629179c0f69e4512f282f467 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 16:54:25 +0200 Subject: [PATCH 21/61] Apply selected blocks in file comparison Refs #105 --- FILES-UI.md | 12 +- resources/files.rc | 9 +- src/files_compare.inl | 460 ++++++++++++++++++++++++++++------ src/files_compare_text.h | 81 ++++++ src/files_main.cpp | 3 +- src/files_text_window.cpp | 30 ++- src/files_text_window.h | 3 + tests/files_text_document.cpp | 20 ++ 8 files changed, 536 insertions(+), 82 deletions(-) create mode 100644 src/files_compare_text.h diff --git a/FILES-UI.md b/FILES-UI.md index 83943b0..59d70e8 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -81,11 +81,17 @@ Warning і початковий фокус на No. Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах типово пропускаються. Перемикач **Show whitespace changes** показує їх. Вставлені й видалені порожні рядки враховуються завжди. + **Apply to left/right** копіює виділений блок у відповідну сторону. + Порівняння перераховується, а змінену сторону позначає зірочка. + **Undo** або **Ctrl+Z** повертає останню незаписану дію. + **Save left/right** зберігає відповідну сторону, **Ctrl+S** зберігає обидві. + Зовнішня зміна цільового файла зупиняє запис і залишає правки для перегляду. + Закриття зі змінами пропонує Save, Discard або Cancel. Кнопка розгортання в системному заголовку збільшує вікно порівняння до робочої області екрана. Повторне натискання відновлює попередній розмір. - Вікно працює в режимі перегляду. Підтримуються UTF-8 і UTF-16 з BOM, - до 2 МіБ і 100 000 рядків на файл. Стилі переносу рядків порівнюються - як рівнозначні. + Підтримуються UTF-8 і UTF-16 з BOM, до 2 МіБ і 100 000 рядків на файл. + Стилі переносу рядків порівнюються як рівнозначні. Під час запису + зберігаються кодування, BOM і наявні кінці рядків цільового файла. - У меню Files і його списках, що випадають, стрілки вгору й вниз переходять між першим і останнім пунктами циклічно та оминають розділювачі. diff --git a/resources/files.rc b/resources/files.rc index 91d1978..da18279 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -418,11 +418,12 @@ EXSTYLE WS_EX_APPWINDOW CAPTION "Compare files" FONT 9, "Segoe UI" BEGIN - LTEXT "", 400, 4, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX - LTEXT "", 401, 259, 30, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX - CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 45, 510, 207 + LTEXT "", 400, 4, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX + LTEXT "", 401, 259, 50, 247, 13, SS_ENDELLIPSIS | SS_NOPREFIX + CONTROL "", 402, "ListBox", LBS_OWNERDRAWFIXED | LBS_NODATA | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP | WS_BORDER, 0, 65, 510, 187 CONTROL "", 407, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 8, 200, 19 LTEXT "", 403, 216, 12, 98, 14 + CONTROL "", 408, "ToolbarWindow32", CCS_NORESIZE | CCS_NOPARENTALIGN | TBSTYLE_FLAT | TBSTYLE_LIST | WS_TABSTOP, 10, 28, 490, 19 END 115 DIALOGEX 0, 0, 290, 58 @@ -430,7 +431,7 @@ STYLE DS_SETFONT | DS_CENTER | WS_POPUP CAPTION "Compare files" FONT 10, "Consolas" BEGIN - LTEXT "Reading and comparing files...", -1, 14, 15, 262, 13 + LTEXT "Reading and comparing files...", 548, 14, 15, 262, 13 CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 101, 31, 88, 17 END diff --git a/src/files_compare.inl b/src/files_compare.inl index 0518253..43d603e 100644 --- a/src/files_compare.inl +++ b/src/files_compare.inl @@ -67,6 +67,11 @@ struct CompareFile std::wstring label; std::optional peer; std::optional ftp; + std::optional remote; + ks::files::RemoteTextRevision revision; + std::string originalBytes; + std::wstring originalText; + bool dirty{}; }; struct CompareRow @@ -81,11 +86,18 @@ struct CompareRow struct FileComparison { - static constexpr std::array controls{400,401,402,403,407}; + static constexpr std::array controls{400,401,402,403,407,408}; CompareFile files[2]; - std::vector lines[2]; + ks::files::ComparisonText text[2]; std::vector rows; std::vector changes,allChanges; + struct Undo + { + int side{}; + ks::files::ComparisonReplace edit; + }; + std::vector undo; + bool working{}; bool showWhitespace{}; RECT initialClient{}; std::array initialControls{}; @@ -206,63 +218,132 @@ bool handleComparisonMessage(MSG &message) } return true; } -std::vector readComparisonLines(const CompareFile &input,const std::atomic_bool &canceled) +struct CompareCache { - struct TemporaryDirectory + fs::path directory; + + fs::path create() { - fs::path path; - ~TemporaryDirectory() - { - if(path.empty()) return; - std::error_code ignored; - fs::remove_all(path,ignored); - } - } temporary; - auto path=input.path; - if(input.ftp || input.peer) - { - const auto directory=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16))); - requireFileOperation(fs::create_directory(directory),ERROR_ALREADY_EXISTS); - temporary.path=directory; - path=directory/L"file"; - CopyHost source(input.peer?&*input.peer:nullptr,input.ftp); - const auto info=source.stat(input.path,canceled); - requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND); - requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)), - ERROR_NOT_SUPPORTED); - requireFileOperation(info->size<=compareFileLimit,ERROR_FILE_TOO_LARGE); - FilesConnection local; - const auto progress=[&](uint64_t,uint64_t){return !canceled;}; - if(source.ftp) downloadFtpFile(*source.ftp,local,input.path,path,*info,false,progress); - else ks::lan::streamFile(*source.files,local,input.peer->id,input.path,path,info->size, - info->modified,false,false,progress); + auto path=fs::temp_directory_path()/(L"ks-files-compare-"+ks::wide(ks::lan::randomHex(16))); + requireFileOperation(fs::create_directory(path),ERROR_ALREADY_EXISTS); + directory=std::move(path); + return directory/L"file"; } - ks::files::TextDocument document(path,false); + + ~CompareCache() + { + if(directory.empty()) return; + std::error_code ignored; + fs::remove_all(directory,ignored); + } +}; + +ks::files::RemoteTextRevision comparisonLocalRevision(const fs::path &path) +{ + WIN32_FILE_ATTRIBUTE_DATA info{}; + checkFileOperation(GetFileAttributesExW(path.c_str(),GetFileExInfoStandard,&info)!=FALSE); + requireFileOperation(!(info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY),ERROR_NOT_SUPPORTED); + const auto size=(uint64_t(info.nFileSizeHigh)<<32)|info.nFileSizeLow; + const auto stamp=(uint64_t(info.ftLastWriteTime.dwHighDateTime)<<32)|info.ftLastWriteTime.dwLowDateTime; + return {size,stamp,(info.dwFileAttributes&(FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_REPARSE_POINT))==0}; +} + +std::string comparisonRawBytes(const ks::files::TextDocument &document,const std::atomic_bool &canceled) +{ requireFileOperation(document.size()<=compareFileLimit,ERROR_FILE_TOO_LARGE); + std::string raw; + raw.reserve(static_cast(document.size())); + while(raw.size()attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)),ERROR_NOT_SUPPORTED); + input.remote=ks::files::createLanTextSource(*input.peer); + } + if(input.remote) + { + path=temp.create(); + input.revision=input.remote->download(input.path,path,false,[&](uint64_t,uint64_t){return !canceled;}, + compareFileLimit); + } + else input.revision=comparisonLocalRevision(path); + + ks::files::TextDocument document(path,false); + input.originalBytes=comparisonRawBytes(document,canceled); std::string text; for(uint64_t page=0;page(text.size()); const auto count=MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,nullptr,0); if(!count) throw std::runtime_error("Compare files supports UTF-8 and UTF-16 text."); std::wstring decoded(count,L'\0'); checkFileOperation(MultiByteToWideChar(CP_UTF8,MB_ERR_INVALID_CHARS,text.data(),bytes,decoded.data(),count)!=0); - std::vector lines; - size_t start=0; - while(true) + auto result=ks::files::splitComparisonText(decoded); + if(result.lines.size()>100'000) throw std::runtime_error("Each file can contain up to 100,000 lines."); + input.originalText=std::move(decoded); + return result; +} + +void saveComparisonFile(CompareFile &file,const ks::files::ComparisonText &text,const std::atomic_bool &canceled) +{ + requireFileOperation(file.revision.editable,ERROR_ACCESS_DENIED); + CompareCache temporary; + auto target=file.path; + if(file.remote) { - requireFileOperation(!canceled,ERROR_CANCELLED); - if(lines.size()==100'000) throw std::runtime_error("Each file can contain up to 100,000 lines."); - const auto end=decoded.find_first_of(L"\r\n",start); - lines.push_back(decoded.substr(start,end==decoded.npos?end:end-start)); - if(end==decoded.npos) break; - start=end+((decoded[end]==L'\r' && end+1download(file.path,target,true,[&](uint64_t,uint64_t){return !canceled;}, + compareFileLimit); + if(revision.modified!=file.revision.modified || revision.size!=file.revision.size) + throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving."); } - return lines; + else + { + const auto revision=comparisonLocalRevision(target); + requireFileOperation(revision.editable,ERROR_ACCESS_DENIED); + if(revision.modified!=file.revision.modified || revision.size!=file.revision.size) + throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving."); + } + ks::files::TextDocument document(target,true); + if(comparisonRawBytes(document,canceled)!=file.originalBytes) + throw std::runtime_error("The file changed since it was compared. Open a new comparison before saving."); + auto joined=text.joined(); + const auto contents=ks::utf8(joined); + const auto bytes=document.encoding()==ks::files::TextEncoding::utf8?contents.size(): + joined.size()*sizeof(wchar_t); + requireFileOperation(bytes+document.boundary(0)<=compareFileLimit,ERROR_FILE_TOO_LARGE); + for(uint64_t page=1;pageupload(file.path,target,file.revision); + else file.revision=comparisonLocalRevision(target); + const std::atomic_bool committed{}; + file.originalBytes=comparisonRawBytes(document,committed); + file.originalText=std::move(joined); + file.dirty=false; } std::wstring_view comparisonContent(std::wstring_view line) @@ -274,7 +355,7 @@ std::wstring_view comparisonContent(std::wstring_view line) void alignComparison(FileComparison &result,const std::atomic_bool &canceled) { - const auto &left=result.lines[0],&right=result.lines[1]; + const auto &left=result.text[0].lines,&right=result.text[1].lines; std::map ids; std::map blankIds; unsigned nextId=1; @@ -436,6 +517,174 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled) append(static_cast(a.size()-suffix+i),static_cast(b.size()-suffix+i)); } +enum ComparisonCommand { applyLeft=409,applyRight,undoCompare,saveLeft,saveRight,saveComparison }; + +struct ComparisonProgress +{ + const wchar_t *status; + bool cancelable=true; + std::atomic_bool canceled{}; +}; + +INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp); + +template +bool runComparisonWork(HWND owner,const wchar_t *status,bool cancelable,const Work &work) +{ + ComparisonProgress state{status,cancelable}; + FileOperationUi worker; + FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner, + comparisonProgressDialog,reinterpret_cast(&state),false); + if(!progress.window()) throw std::runtime_error("Could not open the comparison progress dialog."); + progress.show(); + try {worker.run(progress.window(),state.canceled,[&]{work(state.canceled);});} + catch(const std::system_error &error) + { + if(error.code().value()==ERROR_CANCELLED) return false; + throw; + } + return !state.canceled; +} + +std::optional comparisonBlock(const FileComparison &comparison,int side,LRESULT selected) +{ + if(selected<0 || static_cast(selected)>=comparison.rows.size() || + !comparison.rows[selected].hasChange(comparison.showWhitespace)) return {}; + auto first=static_cast(selected),end=first+1; + while(first>0 && comparison.rows[first-1].hasChange(comparison.showWhitespace)) --first; + while(end=0) + { + edit.start=std::min(edit.start,static_cast(old)); + ++edit.count; + } + if(incoming>=0) + { + edit.lines.push_back(source.lines[incoming]); + edit.endings.push_back(old>=0?target.endings[old]:target.preferred); + } + } + if(!edit.count) + for(size_t row=end;row=0) + { + edit.start=static_cast(next); + break; + } + return edit; +} + +void updateComparisonSummary(HWND dialog,const FileComparison &comparison); + +void comparisonUpdateRows(HWND dialog,const FileComparison &comparison,LRESULT selected,LRESULT top) +{ + const auto list=GetDlgItem(dialog,402); + SendMessageW(list,LB_SETCOUNT,comparison.rows.size(),0); + if(!comparison.rows.empty()) + { + const auto last=static_cast(comparison.rows.size())-1; + SendMessageW(list,LB_SETCURSEL,std::clamp(selected,0,last),0); + SendMessageW(list,LB_SETTOPINDEX,std::clamp(top,0,last),0); + } + updateComparisonSummary(dialog,comparison); + InvalidateRect(list,nullptr,TRUE); +} + +bool applyComparisonEdit(HWND dialog,FileComparison &comparison,int side,const ks::files::ComparisonReplace &edit, + bool remember) +{ + const auto list=GetDlgItem(dialog,402); + const auto selected=SendMessageW(list,LB_GETCURSEL,0,0); + const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0); + FileComparison candidate; + ks::files::ComparisonReplace reverse; + comparison.working=true; + try + { + const bool success=runComparisonWork(dialog,L"Updating comparison…",true,[&](const auto &stop) { + candidate.text[0]=comparison.text[0]; + candidate.text[1]=comparison.text[1]; + reverse=ks::files::replaceComparisonText(candidate.text[side],edit); + if(candidate.text[side].lines.size()>100'000) + throw std::runtime_error("Each file can contain up to 100,000 lines."); + alignComparison(candidate,stop); + }); + comparison.working=false; + if(!success) return false; + if(remember) comparison.undo.push_back({side,std::move(reverse)}); + else comparison.undo.pop_back(); + comparison.text[side]=std::move(candidate.text[side]); + comparison.rows=std::move(candidate.rows); + comparison.changes=std::move(candidate.changes); + comparison.allChanges=std::move(candidate.allChanges); + comparison.files[side].dirty=comparison.text[side].joined()!=comparison.files[side].originalText; + comparisonUpdateRows(dialog,comparison,selected,top); + return true; + } + catch(const std::exception &error) + { + comparison.working=false; + showFileOperationError(dialog,L"Could not apply the block",ks::wide(error.what())); + return false; + } +} + +bool commitComparison(HWND dialog,FileComparison &comparison,int requested=-1) +{ + std::array committed{comparison.files[0],comparison.files[1]}; + comparison.working=true; + bool success=true; + try + { + runComparisonWork(dialog,L"Saving comparison changes…",false,[&](const auto &stop) { + for(int side=0;side<2;++side) + if((requested<0 || requested==side) && comparison.files[side].dirty) + saveComparisonFile(committed[side],comparison.text[side],stop); + }); + } + catch(const std::system_error &error) + { + const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.":fileError(error); + showFileOperationError(dialog,L"Comparison save failed",detail); + success=false; + } + catch(const std::exception &error) + { + showFileOperationError(dialog,L"Comparison save failed",ks::wide(error.what())); + success=false; + } + comparison.working=false; + for(int side=0;side<2;++side) + if(!committed[side].dirty) comparison.files[side]=std::move(committed[side]); + std::erase_if(comparison.undo,[&](const auto &previous){return !comparison.files[previous.side].dirty;}); + updateComparisonSummary(dialog,comparison); + return success; +} + +void closeComparison(HWND dialog,FileComparison &comparison) +{ + if(comparison.working || FilesModalDialog::dismissOwned(dialog)) return; + if(comparison.files[0].dirty || comparison.files[1].dirty) + { + const auto choice=showFilesNotice(dialog,L"Save changes from the comparison?",L"Compare files", + {.saveChanges=true}); + if(choice==IDYES) + { + if(!commitComparison(dialog,comparison)) return; + } + else if(choice!=IDNO) return; + } + DestroyWindow(dialog); +} + void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &item) { const auto dc=item.hDC; @@ -488,7 +737,7 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it numberArea.right=std::min(area.right,area.left+7*cell); DrawTextW(dc,numberText.c_str(),-1,&numberArea,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX); area.left=std::min(area.right,numberArea.right+cell); - const auto &line=comparison.lines[side][number]; + const auto &line=comparison.text[side].lines[number]; const auto paneWidth=area.right-area.left; if(paneWidth<=0) return; const auto limit=static_cast(paneWidth/cell+2)*4; @@ -530,6 +779,11 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) { + if(message==WM_KEYDOWN && (GetKeyState(VK_CONTROL)&0x8000) && (wp=='Z' || wp=='S')) + { + SendMessageW(GetParent(control),WM_COMMAND,wp=='Z'?undoCompare:saveComparison,0); + return 0; + } if(message==WM_KEYDOWN && (wp==VK_F7 || wp==VK_F8)) { SendMessageW(GetParent(control),WM_COMMAND,wp==VK_F7?404:405,0); @@ -626,6 +880,7 @@ void layoutComparison(HWND dialog) if(id==400 || id==401) continue; auto bounds=comparison->initialControls[i]; if(id==402) bounds={0,bounds.top,client.right,client.bottom}; + if(id==408) bounds.right=client.right-bounds.left; SetWindowPos(GetDlgItem(dialog,id),nullptr,bounds.left,bounds.top, bounds.right-bounds.left,std::max(0L,bounds.bottom-bounds.top), SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS); @@ -642,6 +897,19 @@ void updateComparisonSummary(HWND dialog,const FileComparison &comparison) SetDlgItemTextW(dialog,403,summary.c_str()); const auto toolbar=GetDlgItem(dialog,407); for(const auto id:{404,405}) SendMessageW(toolbar,TB_ENABLEBUTTON,id,MAKELONG(blocks!=0,0)); + const auto actions=GetDlgItem(dialog,408); + const auto row=SendDlgItemMessageW(dialog,402,LB_GETCURSEL,0,0); + const bool selected=row>=0 && static_cast(row)(buttons)); } +void initializeComparisonActions(HWND toolbar) +{ + SendMessageW(toolbar,TB_BUTTONSTRUCTSIZE,sizeof(TBBUTTON),0); + SendMessageW(toolbar,TB_SETEXTENDEDSTYLE,0,TBSTYLE_EX_MIXEDBUTTONS); + SendMessageW(toolbar,TB_SETMAXTEXTROWS,1,0); + constexpr BYTE text=BTNS_AUTOSIZE|BTNS_SHOWTEXT; + const auto separator=MulDiv(8,GetDpiForWindow(toolbar),96); + const TBBUTTON buttons[]{ + {I_IMAGENONE,applyLeft,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Apply to left")}, + {I_IMAGENONE,applyRight,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Apply to right")}, + {I_IMAGENONE,undoCompare,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Undo")}, + {separator,0,0,BTNS_SEP,{},0,0}, + {I_IMAGENONE,saveLeft,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Save left")}, + {I_IMAGENONE,saveRight,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Save right")} + }; + SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast(buttons)); +} + INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) { auto *comparison=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); @@ -685,15 +971,17 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) SendMessageW(dialog,WM_SETICON,ICON_SMALL,reinterpret_cast(small)); SendMessageW(dialog,WM_SETICON,ICON_BIG,reinterpret_cast(large)); ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,L"HrynCo.KSwitcher.Files.Compare"); - for(int side=0;side<2;++side) SetDlgItemTextW(dialog,400+side,comparison->files[side].label.c_str()); initializeComparisonToolbar(toolbar); - updateComparisonSummary(dialog,*comparison); + const auto actions=GetDlgItem(dialog,408); + initializeComparisonActions(actions); SetWindowSubclass(list,comparisonKeys,1,0); SetWindowSubclass(toolbar,comparisonKeys,1,0); + SetWindowSubclass(actions,comparisonKeys,1,0); applyComparisonAppearance(dialog,*comparison); SendMessageW(list,LB_SETCOUNT,comparison->rows.size(),0); layoutComparisonHeaders(dialog,*comparison); if(!comparison->changes.empty()) SendMessageW(list,LB_SETCURSEL,comparison->changes.front(),0); + updateComparisonSummary(dialog,*comparison); return TRUE; } if(message==filesPreferencesChanged && comparison) @@ -702,16 +990,16 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) layoutComparisonHeaders(dialog,*comparison); return TRUE; } - if(message==WM_CLOSE) + if(message==WM_CLOSE && comparison) { - DestroyWindow(dialog); + closeComparison(dialog,*comparison); return TRUE; } if(message==WM_MOUSEWHEEL && comparison && zoomComparison(dialog,*comparison,wp)) return TRUE; if(message==WM_NCDESTROY) { ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,nullptr); - comparisonWindows.erase(dialog); + if(comparisonWindows.erase(dialog)) ks::files::standaloneFilesWindowClosed(); return FALSE; } if(message==WM_GETMINMAXINFO && comparison && comparison->minimumWindow.cx) @@ -737,7 +1025,34 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) if(message==WM_COMMAND && comparison) { const auto id=LOWORD(wp); - if(id==IDCANCEL) {DestroyWindow(dialog);return TRUE;} + if(comparison->working) return TRUE; + if(id==IDCANCEL) {closeComparison(dialog,*comparison);return TRUE;} + if(id==applyLeft || id==applyRight) + { + const auto side=id-applyLeft; + if(comparison->files[side].revision.editable) + if(const auto edit=comparisonBlock(*comparison,side,SendMessageW(list,LB_GETCURSEL,0,0))) + applyComparisonEdit(dialog,*comparison,side,*edit,true); + SetFocus(list); + return TRUE; + } + if(id==undoCompare) + { + if(!comparison->undo.empty()) + { + const auto &previous=comparison->undo.back(); + applyComparisonEdit(dialog,*comparison,previous.side,previous.edit,false); + } + SetFocus(list); + return TRUE; + } + if(id==saveLeft || id==saveRight || id==saveComparison) + { + if(comparison->files[0].dirty || comparison->files[1].dirty) + commitComparison(dialog,*comparison,id==saveComparison?-1:id-saveLeft); + SetFocus(list); + return TRUE; + } if(id==406 && HIWORD(wp)==BN_CLICKED) { comparison->showWhitespace=SendMessageW(toolbar,TB_ISBUTTONCHECKED,id,0)!=0; @@ -759,6 +1074,7 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) const auto next=std::upper_bound(changes.begin(),changes.end(),current); if(next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0); } + updateComparisonSummary(dialog,*comparison); return TRUE; } if(id==402 && HIWORD(wp)==LBN_DBLCLK) @@ -769,13 +1085,18 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) const auto &row=comparison->rows[current]; const auto side=[&](int file,int line) { - return line<0?std::wstring(L"—"):comparison->lines[file][line]; + return line<0?std::wstring(L"—"):comparison->text[file].lines[line]; }; const auto detail=L"Left\n"+side(0,row.left)+L"\n\nRight\n"+side(1,row.right); showFilesNotice(dialog,detail.c_str(),L"Line details"); } return TRUE; } + if(id==402 && HIWORD(wp)==LBN_SELCHANGE) + { + updateComparisonSummary(dialog,*comparison); + return TRUE; + } } return FALSE; } @@ -785,13 +1106,20 @@ INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPA if(message==WM_INITDIALOG) { SetWindowLongPtrW(dialog,DWLP_USER,lp); + const auto &state=*reinterpret_cast(lp); prepareTextDialog(dialog); + SetDlgItemTextW(dialog,548,state.status); + EnableWindow(GetDlgItem(dialog,IDCANCEL),state.cancelable); return TRUE; } - if(message==WM_COMMAND && LOWORD(wp)==IDCANCEL) + if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) { - *reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER))=true; - EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE); + auto &state=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(state.cancelable) + { + state.canceled=true; + EnableWindow(GetDlgItem(dialog,IDCANCEL),FALSE); + } return TRUE; } return paintTextDialog(dialog,message,wp,lp,L" Compare files "); @@ -828,41 +1156,33 @@ void compareSelectedFiles(HWND owner) L"Compare files"); return; } - std::atomic_bool canceled{}; try { - { - FileOperationUi worker; - FilesModalDialog progress(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(115),owner, - comparisonProgressDialog,reinterpret_cast(&canceled),false); - if(!progress.window()) throw std::runtime_error("Could not open the progress dialog."); - progress.show(); - worker.run(progress.window(),canceled,[&] - { - for(int side=0;side<2;++side) - comparison.lines[side]=readComparisonLines(comparison.files[side],canceled); - alignComparison(comparison,canceled); - }); - } - if(!canceled) + const bool read=runComparisonWork(owner,L"Reading and comparing files…",true,[&](const auto &stop) { + for(int side=0;side<2;++side) + comparison.text[side]=readComparisonLines(comparison.files[side],stop); + alignComparison(comparison,stop); + }); + if(read) { const auto window=CreateDialogParamW(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(114),nullptr, comparisonDialog,reinterpret_cast(&comparison)); if(!window) throw std::runtime_error("Could not open the comparison window."); comparisonWindows.emplace(window,std::move(state)); + ks::files::standaloneFilesWindowOpened(); ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW); SetFocus(GetDlgItem(window,402)); } } catch(const std::system_error &error) { - if(canceled || error.code().value()==ERROR_CANCELLED) return; + if(error.code().value()==ERROR_CANCELLED) return; const auto detail=error.code().value()==ERROR_FILE_TOO_LARGE?L"Each text file can be up to 2 MiB.": fileError(error); showFileOperationError(owner,L"Comparison failed",detail); } catch(const std::exception &error) { - if(!canceled) showFileOperationError(owner,L"Comparison failed",ks::wide(error.what())); + showFileOperationError(owner,L"Comparison failed",ks::wide(error.what())); } } diff --git a/src/files_compare_text.h b/src/files_compare_text.h new file mode 100644 index 0000000..cf33d48 --- /dev/null +++ b/src/files_compare_text.h @@ -0,0 +1,81 @@ +#pragma once + +#include +#include +#include +#include + +namespace ks::files +{ +enum class ComparisonEnding { absent, crlf, lf, cr }; + +inline std::wstring_view comparisonEndingText(ComparisonEnding ending) +{ + switch(ending) + { + case ComparisonEnding::crlf: return L"\r\n"; + case ComparisonEnding::lf: return L"\n"; + case ComparisonEnding::cr: return L"\r"; + default: return {}; + } +} + +struct ComparisonText +{ + std::vector lines; + std::vector endings; + ComparisonEnding preferred=ComparisonEnding::crlf; + + std::wstring joined() const + { + std::wstring result; + for(size_t i=0;i lines; + std::vector endings; +}; + +inline ComparisonReplace replaceComparisonText(ComparisonText &document,const ComparisonReplace &change) +{ + const auto first=document.lines.begin()+change.start, last=first+change.count; + const auto firstEnding=document.endings.begin()+change.start, lastEnding=firstEnding+change.count; + ComparisonReplace reverse{change.start,change.lines.size(),{first,last},{firstEnding,lastEnding}}; + document.lines.erase(first,last); + document.lines.insert(document.lines.begin()+change.start,change.lines.begin(),change.lines.end()); + document.endings.erase(firstEnding,lastEnding); + document.endings.insert(document.endings.begin()+change.start,change.endings.begin(),change.endings.end()); + return reverse; +} +} diff --git a/src/files_main.cpp b/src/files_main.cpp index 12a1621..d05abad 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -28,6 +28,7 @@ #include #include "files_terminal.h" #include "files_archive.h" +#include "files_compare_text.h" #include "files_image_decode.h" #include "files_win32_directory.h" #include "files_command_completion.h" @@ -5860,7 +5861,7 @@ ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile) ERROR_NOT_SUPPORTED); const bool editable=!(info->attributes&FILE_ATTRIBUTE_READONLY); if(edit && !editable) throw std::runtime_error("The FTP file is read-only."); - if(info->size>limit) throw std::runtime_error("The image is too large to preview."); + if(info->size>limit) throw std::system_error(ERROR_FILE_TOO_LARGE,std::system_category()); FilesConnection local; downloadFtpFile(ftp,local,path,cache,*info,false,progress); return ks::files::RemoteTextRevision{info->size,info->modified,editable}; diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index 668ec77..1eeeec9 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -600,7 +600,7 @@ RemoteTextSource lanTextSource(const lan::FilesPeer &peer) throw std::runtime_error("Update KSwitcher on the remote computer to edit this file."); if(edit && readOnly) throw std::runtime_error("The remote file is read-only."); const RemoteTextRevision revision{info.at("size"),info.at("modified"),canCommit && !readOnly}; - if(revision.size>sizeLimit) throw std::runtime_error("The image is too large to preview."); + if(revision.size>sizeLimit) throw std::system_error(ERROR_FILE_TOO_LARGE,std::system_category()); try { lan::streamFile(source,target,peer.id,original,cache,revision.size,revision.modified,false,false,progress); @@ -684,6 +684,12 @@ std::map> textWindows; std::vector textWindowOrder; HWND filesOwner{}; bool textOwnerClosed=false; +unsigned standaloneFilesWindows{}; +void quitWhenFilesWindowsClose() +{ + if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty() && !standaloneFilesWindows) + PostQuitMessage(0); +} constexpr ULONG_PTR openDocumentQuery=0x4B534644; std::wstring documentIdentity(const std::filesystem::path &path,std::string_view peer) @@ -2990,7 +2996,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, self->window=nullptr; textWindows.erase(window); std::erase(textWindowOrder,window); - if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0); + quitWhenFilesWindowsClose(); break; } } @@ -3108,7 +3114,18 @@ void textWindowOwnerClosed() { filesOwner=nullptr; textOwnerClosed=true; - if(textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0); + quitWhenFilesWindowsClose(); +} + +void standaloneFilesWindowOpened() +{ + ++standaloneFilesWindows; +} + +void standaloneFilesWindowClosed() +{ + if(standaloneFilesWindows) --standaloneFilesWindows; + quitWhenFilesWindowsClose(); } bool cycleTextWindows(HWND current,bool reverse) @@ -3221,7 +3238,7 @@ void openImageWindow(HWND owner,std::vector images,const const auto window=createImageView(owner,false,imageViewStyle(dialogs),std::move(images),path,std::move(load), [](HWND closed) { std::erase(textWindowOrder,closed); - if(textOwnerClosed && textWindows.empty() && textWindowOrder.empty()) PostQuitMessage(0); + quitWhenFilesWindowsClose(); }); if(!window) throw std::runtime_error("Could not open the image viewer."); textWindowOrder.push_back(window); @@ -3292,6 +3309,11 @@ void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit openTextWindowImpl(owner,path,edit,dialogs,&source,fragment,newWindow,options); } +RemoteTextSource createLanTextSource(const lan::FilesPeer &peer) +{ + return lanTextSource(peer); +} + void showAllViewerBookmarks(HWND owner,TextDialogs dialogs) { try diff --git a/src/files_text_window.h b/src/files_text_window.h index a7c0764..e750b4f 100644 --- a/src/files_text_window.h +++ b/src/files_text_window.h @@ -81,6 +81,7 @@ struct RemoteTextSource std::function upload; }; +RemoteTextSource createLanTextSource(const lan::FilesPeer &peer); inline constexpr UINT quickViewToggleMessage=WM_APP+31; HWND createQuickView(HWND owner,TextDialogs dialogs); @@ -97,5 +98,7 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false,TextOpenOptions options={}); void textWindowOwnerClosed(); +void standaloneFilesWindowOpened(); +void standaloneFilesWindowClosed(); bool cycleTextWindows(HWND current,bool reverse); } diff --git a/tests/files_text_document.cpp b/tests/files_text_document.cpp index 29d70aa..0340d9b 100644 --- a/tests/files_text_document.cpp +++ b/tests/files_text_document.cpp @@ -1,4 +1,5 @@ #include "files_text_document.h" +#include "files_compare_text.h" #include #include @@ -189,6 +190,24 @@ void bookmarkedLines(const fs::path &file) check(rejected,"Cancel a bookmark scan"); } +void comparisonEdits() +{ + using namespace ks::files; + auto mixed=splitComparisonText(L"alpha\r\nbeta\nlast\r"); + check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Round-trip mixed line endings"); + const auto replace=replaceComparisonText(mixed,{1,1,{L"new",L"extra"},{ComparisonEnding::lf,ComparisonEnding::crlf}}); + check(mixed.joined()==L"alpha\r\nnew\nextra\r\nlast\r","Replace a block and retain the other line endings"); + replaceComparisonText(mixed,replace); + check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Undo a block replacement"); + const auto shorten=replaceComparisonText(mixed,{3,1,{},{}}); + check(mixed.joined()==L"alpha\r\nbeta\nlast","Remove the terminating empty line"); + replaceComparisonText(mixed,shorten); + check(mixed.joined()==L"alpha\r\nbeta\nlast\r","Undo preserves the original trailing separator"); + auto single=splitComparisonText(L"first"); + replaceComparisonText(single,{1,0,{L"second"},{ComparisonEnding::absent}}); + check(single.joined()==L"first\r\nsecond","Use the target convention when inserting past EOF"); +} + void saveDraft(const fs::path &file) { TextDocument draft({}); @@ -238,6 +257,7 @@ int main() saveDraft(fixture.directory / L"created.txt"); hexBytes(fixture.directory / L"raw.bin"); bookmarkedLines(fixture.directory / L"bookmarks.txt"); + comparisonEdits(); sparseFile(fixture.directory / L"5gib.log"); std::cout << "Files text document regressions passed.\n"; } From 9d57568351c9ba59b873c6ae6332f12ee741d4ae Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 17:04:05 +0200 Subject: [PATCH 22/61] Add unified comparison and context folding Refs #106 --- FILES-UI.md | 16 +- src/files_compare.inl | 287 ++++++++++++++++++++-------- tests/files_comparison_splitter.ps1 | 32 +++- 3 files changed, 242 insertions(+), 93 deletions(-) diff --git a/FILES-UI.md b/FILES-UI.md index 59d70e8..e84d2f5 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -61,16 +61,21 @@ Warning і початковий фокус на No. активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає позначок, береться файл під курсором. Підтримуються локальні, LAN- та FTP-файли. Файли показуються поруч із синхронною прокруткою, номерами - рядків і підсвічуванням вставок, видалень і замін. У замінених рядках - виділяється змінений фрагмент. **Previous** (F7) і **Next** (F8) - переходять між блоками змін. Подвійний клік відкриває повний текст пари рядків. + рядків і підсвічуванням вставок, видалень і замін. **Unified** перемикає + на єдину колонку з номерами рядків обох файлів, видаленнями зі знаком − + і вставками зі знаком +. Перемикання зберігає поточний блок. + **Fold unchanged** згортає довгі незмінені ділянки до рядка з лічильником + і залишає до трьох рядків контексту перед і після кожного блока. + У замінених рядках виділяється змінений фрагмент. **Previous** (F7) і + **Next** (F8) переходять між блоками змін в обох поданнях. + Подвійний клік відкриває повний текст пари рядків. Лічильник, навігація й перемикач пробілів розміщені в одному компактному рядку над заголовками файлів. Вікно закривається системним хрестиком або Esc. Вікно має системну рамку зі зміною розміру й нативний тулбар Windows зі стрілками переходу, розділювачами та кнопкою-перемикачем пробілів. Текст файлів і порожня область під ним мають білий фон, рядки зі змінами виділяються кольором. Область порівняння займає всю ширину вікна. - Центральний розділювач можна перетягнути мишею. Під час зміни розміру + У поданні поруч центральний розділювач можна перетягнути мишею. Під час зміни розміру вікна пропорція колонок зберігається. Ctrl+колесо змінює масштаб тексту в поточному вікні. Порівняння відкривається в окремому вікні із власною іконкою та кнопкою @@ -79,7 +84,8 @@ Warning і початковий фокус на No. Shift+F11 відкриває порівняння. Комбінацію можна змінити в тому ж розділі, і меню Commands показує поточне призначення. Рядки зіставляються за вмістом. Зміни лише у відступах і кінцевих пробілах - типово пропускаються. Перемикач **Show whitespace changes** показує їх. + типово пропускаються. Перемикач **Show whitespace changes** показує їх + в обох поданнях і враховує під час згортання. Вставлені й видалені порожні рядки враховуються завжди. **Apply to left/right** копіює виділений блок у відповідну сторону. Порівняння перераховується, а змінену сторону позначає зірочка. diff --git a/src/files_compare.inl b/src/files_compare.inl index 43d603e..6a2dba3 100644 --- a/src/files_compare.inl +++ b/src/files_compare.inl @@ -84,13 +84,23 @@ struct CompareRow bool hasChange(bool showWhitespace) const {return changed && (showWhitespace || !whitespaceOnly);} }; +struct ComparisonDisplayRow +{ + int first=-1,past{}; + int side=-1; + + bool folded() const {return past>first+1;} +}; + struct FileComparison { static constexpr std::array controls{400,401,402,403,407,408}; CompareFile files[2]; ks::files::ComparisonText text[2]; std::vector rows; - std::vector changes,allChanges; + std::vector displayRows; + std::vector> displayPositions; + std::vector displayBlockStarts; struct Undo { int side{}; @@ -98,7 +108,7 @@ struct FileComparison }; std::vector undo; bool working{}; - bool showWhitespace{}; + bool showWhitespace{},unified{},foldContext{}; RECT initialClient{}; std::array initialControls{}; SIZE minimumWindow{}; @@ -130,7 +140,8 @@ void layoutComparisonHeaders(HWND dialog,const FileComparison &comparison) RECT bounds{}; GetClientRect(list,&bounds); MapWindowPoints(list,dialog,reinterpret_cast(&bounds),2); - const auto middle=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left); + const auto width=bounds.right-bounds.left; + const auto middle=bounds.left+(comparison.unified?width/2:comparisonSplitX(comparison,width)); const auto inset=comparison.initialControls[0].left; for(int side=0;side<2;++side) { @@ -394,8 +405,6 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled) const auto append=[&](int x,int y) { CompareRow row{x,y,x<0 || y<0 || left[x]!=right[y]}; - if(row.changed && (result.rows.empty() || !result.rows.back().changed)) - result.allChanges.push_back(static_cast(result.rows.size())); if(row.changed && x>=0 && y>=0) { const auto &l=left[x],&r=right[y]; @@ -409,8 +418,6 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled) if(row.commonEnd && l[l.size()-row.commonEnd]>=0xdc00 && l[l.size()-row.commonEnd]<=0xdfff) --row.commonEnd; } - if(row.hasChange(false) && (result.rows.empty() || !result.rows.back().hasChange(false))) - result.changes.push_back(static_cast(result.rows.size())); result.rows.push_back(row); }; const auto change=[&](size_t x,size_t y,size_t countLeft,size_t countRight) @@ -517,7 +524,8 @@ void alignComparison(FileComparison &result,const std::atomic_bool &canceled) append(static_cast(a.size()-suffix+i),static_cast(b.size()-suffix+i)); } -enum ComparisonCommand { applyLeft=409,applyRight,undoCompare,saveLeft,saveRight,saveComparison }; +enum ComparisonCommand { applyLeft=409,applyRight,undoCompare,saveLeft,saveRight,saveComparison, + unifiedCompare,foldCompareContext }; struct ComparisonProgress { @@ -584,16 +592,76 @@ std::optional comparisonBlock(const FileComparison void updateComparisonSummary(HWND dialog,const FileComparison &comparison); -void comparisonUpdateRows(HWND dialog,const FileComparison &comparison,LRESULT selected,LRESULT top) +ComparisonDisplayRow comparisonDisplayAnchor(const FileComparison &comparison,LRESULT position) +{ + if(position<0 || static_cast(position)>=comparison.displayRows.size()) return {}; + return comparison.displayRows[position]; +} + +int comparisonDisplayPosition(const FileComparison &comparison,ComparisonDisplayRow anchor) +{ + if(anchor.first<0 || comparison.displayPositions.empty()) return -1; + const auto last=static_cast(comparison.displayPositions.size())-1; + const auto &positions=comparison.displayPositions[std::min(anchor.first,last)]; + if(anchor.side>=0 && positions[anchor.side]>=0) return positions[anchor.side]; + if(positions[0]<0) return positions[1]; + if(positions[1]<0) return positions[0]; + return std::min(positions[0],positions[1]); +} + +void comparisonUpdateRows(HWND dialog,FileComparison &comparison,ComparisonDisplayRow selected, + ComparisonDisplayRow top={}) { const auto list=GetDlgItem(dialog,402); - SendMessageW(list,LB_SETCOUNT,comparison.rows.size(),0); - if(!comparison.rows.empty()) + comparison.displayRows.clear(); + const auto size=static_cast(comparison.rows.size()); + comparison.displayPositions.assign(size,{-1,-1}); + comparison.displayBlockStarts.clear(); + const auto append=[&](int first,int past,int side=-1) { - const auto last=static_cast(comparison.rows.size())-1; - SendMessageW(list,LB_SETCURSEL,std::clamp(selected,0,last),0); - SendMessageW(list,LB_SETTOPINDEX,std::clamp(top,0,last),0); + const auto position=static_cast(comparison.displayRows.size()); + comparison.displayRows.push_back({first,past,side}); + for(int row=first;row(comparison.displayRows.size())); + if(isChange && comparison.unified) + { + for(int row=first;row=0) append(row,row+1,0); + for(int row=first;row=0) append(row,row+1,1); + } + else + { + constexpr int context=3; + const int hiddenFirst=comparison.foldContext && !isChange?first+(first>0?context:0):past; + const int hiddenPast=past-(past=2) + { + for(int row=first;row=0) + SendMessageW(list,LB_SETTOPINDEX,firstVisible,0); + SendMessageW(list,LB_SETCURSEL,position,0); updateComparisonSummary(dialog,comparison); InvalidateRect(list,nullptr,TRUE); } @@ -602,8 +670,8 @@ bool applyComparisonEdit(HWND dialog,FileComparison &comparison,int side,const k bool remember) { const auto list=GetDlgItem(dialog,402); - const auto selected=SendMessageW(list,LB_GETCURSEL,0,0); - const auto top=SendMessageW(list,LB_GETTOPINDEX,0,0); + const auto selected=comparisonDisplayAnchor(comparison,SendMessageW(list,LB_GETCURSEL,0,0)); + const auto top=comparisonDisplayAnchor(comparison,SendMessageW(list,LB_GETTOPINDEX,0,0)); FileComparison candidate; ks::files::ComparisonReplace reverse; comparison.working=true; @@ -623,8 +691,6 @@ bool applyComparisonEdit(HWND dialog,FileComparison &comparison,int side,const k else comparison.undo.pop_back(); comparison.text[side]=std::move(candidate.text[side]); comparison.rows=std::move(candidate.rows); - comparison.changes=std::move(candidate.changes); - comparison.allChanges=std::move(candidate.allChanges); comparison.files[side].dirty=comparison.text[side].joined()!=comparison.files[side].originalText; comparisonUpdateRows(dialog,comparison,selected,top); return true; @@ -697,46 +763,22 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it const auto &palette=comparison.appearance.palette; const auto cell=comparison.characterWidth; fill(bounds,palette[CompareBackground]); - if(item.itemID>=comparison.rows.size()) return; - const auto &row=comparison.rows[item.itemID]; + if(item.itemID>=comparison.displayRows.size()) return; + const auto &display=comparison.displayRows[item.itemID]; + const auto &row=comparison.rows[display.first]; const bool changed=row.hasChange(comparison.showWhitespace); - const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left); - const LONG gutter=std::max(4,cell); - const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom}; - const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace]; - if(changed) fill(link,highlight); - else - { - const RECT divider{center,bounds.top,center+1,bounds.bottom}; - fill(divider,palette[CompareDivider]); - } - if(changed) - { - const LONG middle=(bounds.top+bounds.bottom)/2; - const LONG start=row.left<0?bounds.top:middle,end=row.right<0?bounds.top:middle; - SetDCPenColor(dc,palette[CompareChangedText]); - const auto pen=SelectObject(dc,GetStockObject(DC_PEN)); - MoveToEx(dc,link.left,start,nullptr); - LineTo(dc,link.right,end); - SelectObject(dc,pen); - } + const auto ink=palette[changed?CompareChangedText:CompareText]; SelectObject(dc,comparison.font?comparison.font:mono); SetBkMode(dc,TRANSPARENT); - const auto ink=palette[changed?CompareChangedText:CompareText]; SetTextColor(dc,ink); - const auto drawSide=[&](int side,int number,RECT area) + const auto drawNumber=[&](int number,RECT area) + { + if(number<0) return; + const auto text=std::to_wstring(number+1); + DrawTextW(dc,text.c_str(),-1,&area,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX); + }; + const auto drawContent=[&](int side,int number,RECT area) { - if(number<0) - { - fill(area,palette[ComparePadding]); - return; - } - if(changed) fill(area,highlight); - const auto numberText=std::to_wstring(number+1); - RECT numberArea=area; - numberArea.right=std::min(area.right,area.left+7*cell); - DrawTextW(dc,numberText.c_str(),-1,&numberArea,DT_RIGHT|DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX); - area.left=std::min(area.right,numberArea.right+cell); const auto &line=comparison.text[side].lines[number]; const auto paneWidth=area.right-area.left; if(paneWidth<=0) return; @@ -768,8 +810,62 @@ void drawComparisonRow(const FileComparison &comparison,const DRAWITEMSTRUCT &it } else if(!visible.empty()) DrawTextW(dc,visible.data(),static_cast(visible.size()),&area,flags); }; - drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom}); - drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom}); + if(display.folded()) + { + fill(bounds,palette[ComparePadding]); + auto line=bounds; + line.left+=2*cell; + const auto label=L"… "+std::to_wstring(display.past-display.first)+L" unchanged lines …"; + DrawTextW(dc,label.c_str(),-1,&line,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX); + } + else if(comparison.unified) + { + if(changed) fill(bounds,palette[display.side==0?CompareDelete:CompareInsert]); + RECT number=bounds; + number.right=std::min(bounds.right,bounds.left+7*cell); + if(display.side!=1) drawNumber(row.left,number); + number.left=number.right; + number.right=std::min(bounds.right,number.left+7*cell); + if(display.side!=0) drawNumber(row.right,number); + auto content=bounds; + content.left=std::min(bounds.right,number.right+3*cell); + if(changed) + { + RECT marker{std::min(bounds.right,number.right+cell),bounds.top,content.left,bounds.bottom}; + DrawTextW(dc,display.side==0?L"−":L"+",1,&marker,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX); + } + const auto side=display.side<0?1:display.side; + drawContent(side,side==0?row.left:row.right,content); + } + else + { + const LONG center=bounds.left+comparisonSplitX(comparison,bounds.right-bounds.left); + const LONG gutter=std::max(4,cell); + const RECT link{center-gutter,bounds.top,center+gutter,bounds.bottom}; + const auto highlight=palette[row.left<0?CompareInsert:row.right<0?CompareDelete:CompareReplace]; + if(changed) + { + fill(link,highlight); + const LONG middle=(bounds.top+bounds.bottom)/2; + SetDCPenColor(dc,ink); + const auto pen=SelectObject(dc,GetStockObject(DC_PEN)); + MoveToEx(dc,link.left,row.left<0?bounds.top:middle,nullptr); + LineTo(dc,link.right,row.right<0?bounds.top:middle); + SelectObject(dc,pen); + } + else fill({center,bounds.top,center+1,bounds.bottom},palette[CompareDivider]); + const auto drawSide=[&](int side,int number,RECT area) + { + if(number<0) {fill(area,palette[ComparePadding]);return;} + if(changed) fill(area,highlight); + const auto end=std::min(area.right,area.left+7*cell); + drawNumber(number,{area.left,area.top,end,area.bottom}); + area.left=std::min(area.right,end+cell); + drawContent(side,number,area); + }; + drawSide(0,row.left,{bounds.left,bounds.top,link.left,bounds.bottom}); + drawSide(1,row.right,{link.right,bounds.top,bounds.right,bounds.bottom}); + } if(item.itemState&ODS_SELECTED) { SetDCBrushColor(dc,ink); @@ -794,7 +890,7 @@ LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UI auto *comparison=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); if(!comparison) return DefSubclassProc(control,message,wp,lp); if(message==WM_MOUSEWHEEL && zoomComparison(dialog,*comparison,wp)) return 0; - if(message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK) + if(!comparison->unified && (message==WM_SETCURSOR || message==WM_LBUTTONDOWN || message==WM_LBUTTONDBLCLK)) { RECT client{}; GetClientRect(control,&client); @@ -858,9 +954,12 @@ LRESULT CALLBACK comparisonKeys(HWND control,UINT message,WPARAM wp,LPARAM lp,UI // The list box repaints its rows but can leave earlier divider marks below them. FillRect(dc,&blank,comparison->background?comparison->background: static_cast(GetStockObject(WHITE_BRUSH))); - const RECT divider{middle,blank.top,middle+1,blank.bottom}; - SetDCBrushColor(dc,comparison->appearance.palette[CompareDivider]); - FillRect(dc,÷r,static_cast(GetStockObject(DC_BRUSH))); + if(!comparison->unified) + { + const RECT divider{middle,blank.top,middle+1,blank.bottom}; + SetDCBrushColor(dc,comparison->appearance.palette[CompareDivider]); + FillRect(dc,÷r,static_cast(GetStockObject(DC_BRUSH))); + } ReleaseDC(control,dc); } } @@ -891,16 +990,15 @@ void layoutComparison(HWND dialog) void updateComparisonSummary(HWND dialog,const FileComparison &comparison) { - const auto blocks=(comparison.showWhitespace?comparison.allChanges:comparison.changes).size(); + const auto blocks=comparison.displayBlockStarts.size(); const auto summary=blocks==0?L"Text is identical":blocks==1?L"1 change block": std::to_wstring(blocks)+L" change blocks"; SetDlgItemTextW(dialog,403,summary.c_str()); const auto toolbar=GetDlgItem(dialog,407); for(const auto id:{404,405}) SendMessageW(toolbar,TB_ENABLEBUTTON,id,MAKELONG(blocks!=0,0)); const auto actions=GetDlgItem(dialog,408); - const auto row=SendDlgItemMessageW(dialog,402,LB_GETCURSEL,0,0); - const bool selected=row>=0 && static_cast(row)=0 && !row.folded() && comparison.rows[row.first].hasChange(comparison.showWhitespace); for(int side=0;side<2;++side) { const auto &file=comparison.files[side]; @@ -943,7 +1041,10 @@ void initializeComparisonActions(HWND toolbar) {I_IMAGENONE,undoCompare,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Undo")}, {separator,0,0,BTNS_SEP,{},0,0}, {I_IMAGENONE,saveLeft,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Save left")}, - {I_IMAGENONE,saveRight,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Save right")} + {I_IMAGENONE,saveRight,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Save right")}, + {separator,0,0,BTNS_SEP,{},0,0}, + {I_IMAGENONE,unifiedCompare,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast(L"Unified")}, + {I_IMAGENONE,foldCompareContext,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast(L"Fold unchanged")} }; SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast(buttons)); } @@ -978,10 +1079,12 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) SetWindowSubclass(toolbar,comparisonKeys,1,0); SetWindowSubclass(actions,comparisonKeys,1,0); applyComparisonAppearance(dialog,*comparison); - SendMessageW(list,LB_SETCOUNT,comparison->rows.size(),0); layoutComparisonHeaders(dialog,*comparison); - if(!comparison->changes.empty()) SendMessageW(list,LB_SETCURSEL,comparison->changes.front(),0); - updateComparisonSummary(dialog,*comparison); + const auto first=std::find_if(comparison->rows.begin(),comparison->rows.end(), + [](const auto &row){return row.hasChange(false);}); + ComparisonDisplayRow selected; + if(first!=comparison->rows.end()) selected.first=static_cast(first-comparison->rows.begin()); + comparisonUpdateRows(dialog,*comparison,selected); return TRUE; } if(message==filesPreferencesChanged && comparison) @@ -1030,8 +1133,9 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) if(id==applyLeft || id==applyRight) { const auto side=id-applyLeft; - if(comparison->files[side].revision.editable) - if(const auto edit=comparisonBlock(*comparison,side,SendMessageW(list,LB_GETCURSEL,0,0))) + const auto selected=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0)); + if(!selected.folded() && comparison->files[side].revision.editable) + if(const auto edit=comparisonBlock(*comparison,side,selected.first)) applyComparisonEdit(dialog,*comparison,side,*edit,true); SetFocus(list); return TRUE; @@ -1053,36 +1157,49 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) SetFocus(list); return TRUE; } - if(id==406 && HIWORD(wp)==BN_CLICKED) + if((id==406 || id==unifiedCompare || id==foldCompareContext) && HIWORD(wp)==BN_CLICKED) { - comparison->showWhitespace=SendMessageW(toolbar,TB_ISBUTTONCHECKED,id,0)!=0; - updateComparisonSummary(dialog,*comparison); - InvalidateRect(list,nullptr,FALSE); + const auto selected=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0)); + const auto top=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETTOPINDEX,0,0)); + const auto source=id==406?toolbar:GetDlgItem(dialog,408); + const bool enabled=SendMessageW(source,TB_ISBUTTONCHECKED,id,0)!=0; + if(id==406) comparison->showWhitespace=enabled; + if(id==unifiedCompare) + { + if(comparison->splitDragOffset) ReleaseCapture(); + comparison->unified=enabled; + layoutComparisonHeaders(dialog,*comparison); + } + if(id==foldCompareContext) comparison->foldContext=enabled; + comparisonUpdateRows(dialog,*comparison,selected,top); + SetFocus(list); return TRUE; } - const auto &changes=comparison->showWhitespace?comparison->allChanges:comparison->changes; + const auto &changes=comparison->displayBlockStarts; if((id==404 || id==405) && !changes.empty()) { const auto current=SendMessageW(list,LB_GETCURSEL,0,0); - if(id==404) + const auto next=std::upper_bound(changes.begin(),changes.end(),current); + if(id==404 && next!=changes.begin()) { - const auto previous=std::lower_bound(changes.begin(),changes.end(),current); - if(previous!=changes.begin()) SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0); - } - else - { - const auto next=std::upper_bound(changes.begin(),changes.end(),current); - if(next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0); + const auto here=comparisonDisplayAnchor(*comparison,current); + const bool inBlock=here.first>=0 && !here.folded() && + comparison->rows[here.first].hasChange(comparison->showWhitespace); + const auto previous=std::prev(next); + if(!inBlock) SendMessageW(list,LB_SETCURSEL,*previous,0); + if(inBlock && previous!=changes.begin()) + SendMessageW(list,LB_SETCURSEL,*std::prev(previous),0); } + if(id==405 && next!=changes.end()) SendMessageW(list,LB_SETCURSEL,*next,0); updateComparisonSummary(dialog,*comparison); return TRUE; } if(id==402 && HIWORD(wp)==LBN_DBLCLK) { - const auto current=SendMessageW(list,LB_GETCURSEL,0,0); - if(current>=0 && static_cast(current)rows.size()) + const auto current=comparisonDisplayAnchor(*comparison,SendMessageW(list,LB_GETCURSEL,0,0)); + if(current.first>=0 && !current.folded()) { - const auto &row=comparison->rows[current]; + const auto &row=comparison->rows[current.first]; const auto side=[&](int file,int line) { return line<0?std::wstring(L"—"):comparison->text[file].lines[line]; diff --git a/tests/files_comparison_splitter.ps1 b/tests/files_comparison_splitter.ps1 index 41f4fe7..9776b90 100644 --- a/tests/files_comparison_splitter.ps1 +++ b/tests/files_comparison_splitter.ps1 @@ -42,7 +42,7 @@ try { [void][FilesCommandsUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero) } Invoke-FilesCommand $main 'Compare files*' - $list = Wait-For 'the foreground comparison list' { + $comparison = Wait-For 'the foreground comparison window' { $dialog = [IntPtr]::Zero while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) { [uint32]$ownerPid = 0 @@ -50,11 +50,12 @@ try { if ($ownerPid -ne $process.Id) { continue } $control = [FilesCommandsUi]::GetDlgItem($dialog, 402) if ([FilesCommandsUi]::IsWindowVisible($control) -and [FilesCommandsUi]::Activate($dialog)) { - return $control + return $dialog } } } + $list = [FilesCommandsUi]::GetDlgItem($comparison, 402) $bounds = [FilesCommandsUi+Rect]::new() [void][FilesCommandsUi]::GetClientRect($list, [ref]$bounds) $middle = [int]($bounds.Right / 2) @@ -83,7 +84,32 @@ try { throw "Expected one divider under the last row at $destination. Found $($ink.Count) marked pixels, starting at $($ink | Select-Object -First 8)." } } finally { $bitmap.Dispose() } - 'Verified that dragging leaves exactly one divider below the file contents.' + $toolbar = [FilesCommandsUi]::GetDlgItem($comparison, 408) + if ([FilesCommandsUi]::Send($toolbar, 0x402, [IntPtr]415, [IntPtr]1) -eq [IntPtr]::Zero) { + throw 'The Unified toolbar button is missing.' + } + [void][FilesCommandsUi]::Send($comparison, 0x111, [IntPtr]415, $toolbar) + [void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101) + $height = [FilesCommandsUi]::Send($list, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() + # This part of the first unchanged row contains the right line number in the default font. + $numbers = [Drawing.Bitmap]::new([int]($height * 1.45), $height) + try { + $graphics = [Drawing.Graphics]::FromImage($numbers) + try { $graphics.CopyFromScreen(($origin.X + [int]($height * 3.6)), $origin.Y, 0, 0, $numbers.Size) } + finally { $graphics.Dispose() } + $hasNumber = $false + for ($y = [int]($height / 4); $y -lt [int]($height * 3 / 4) -and !$hasNumber; ++$y) { + for ($x = 0; $x -lt $numbers.Width; ++$x) { + $pixel = $numbers.GetPixel($x, $y) + if ($pixel.R -lt 90 -and $pixel.G -lt 90 -and $pixel.B -lt 90) { + $hasNumber = $true + break + } + } + } + if (!$hasNumber) { throw 'The right line number did not render in the Unified view.' } + } finally { $numbers.Dispose() } + 'Verified the dragged divider and both line numbers in the Unified view.' } finally { if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() } foreach ($name in $names) { From 7033c1e336de6e0394f5e9c308ba03079c6ce95e Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 17:22:44 +0200 Subject: [PATCH 23/61] Restore FTP panels and recover interrupted LAN scans Refs #107 --- FILES-UI.md | 12 ++ src/files_find.inl | 1 + src/files_ftp.inl | 41 ++++++- src/files_ftp_dialog.inl | 1 + src/files_main.cpp | 163 +++++++++++++++++++++------- src/files_panel_recovery.inl | 148 +++++++++++++++++++++++++ tests/files_commands_ui.ps1 | 1 + tests/files_comparison_splitter.ps1 | 48 +++++--- 8 files changed, 354 insertions(+), 61 deletions(-) create mode 100644 src/files_panel_recovery.inl diff --git a/FILES-UI.md b/FILES-UI.md index e84d2f5..943ae31 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -42,6 +42,13 @@ Warning і початковий фокус на No. Назви файлів і папок передаються в UTF-8. Для старого сервера, який використовує системну кодову сторінку Windows, увімкни в профілі **Use Windows encoding for file names** і підключися знову. + Після закриття Files окремо для кожної FTP-панелі зберігаються профіль, + каталог і рядок курсора. При наступному запуску Files відкриває цей каталог + і вибирає попередній рядок, якщо він ще існує. Коли каталог недоступний, + панель показує попередню локальну папку й причину помилки. **Ctrl+R** + повторює підключення. Натискання рядка стану відкриває повну причину + помилки й підтвердження повторної спроби. Вибір іншого джерела скасовує + відновлення. - F5 копіює поточний або позначені файли й папки між локальною та підключеною FTP-панелями в обидва боки. Призначенням є каталог іншої панелі. Для одного елемента можна вказати ім’я копії в цьому каталозі. @@ -553,6 +560,11 @@ Warning і початковий фокус на No. - Меню Change drive показує літеру, тип, загальний обсяг і вільне місце. Відкриття меню запускає нове LAN-виявлення. Секція KSwitcher LAN показує збережені пари, зокрема офлайн. Після кожного відкриття меню асинхронно запитує диски й показує їх під назвою відповідного ПК. Поки триває запит, видно стан завантаження. Якщо запит не вдався, видно помилку. Повторне відкриття запускає новий запит. Кожна панель має власний диск і шлях, а в заголовку віддаленої панелі перед шляхом показано назву ПК. - Список дисків і файлові операції використовують права облікового запису Windows, під яким працює віддалений KSwitcher. Достатньо спарювання й доступного TCP 45885, спільні папки налаштовувати не потрібно. +- Якщо читання LAN-папки переривається через мережеву помилку, Files + зберігає поточний список і до трьох разів повторює читання того самого + ПК, диска й каталогу. Після відновлення курсор залишається на наявному + рядку. Рядок стану показує причину збою й дію **Ctrl+R** для повторної + спроби. Перехід в інший каталог або джерело скасовує попередню спробу. - F5, F6, F8 і Shift+Delete у віддалених панелях використовують спільні підтвердження, попередження й прогрес. F5/F6 працюють із файлами та деревами папок між локальними й віддаленими панелями, зокрема між двома різними ПК. Між шляхами одного віддаленого ПК вміст копіюється на ньому. F8 використовує кошик того ПК, на якому лежить файл. - Після розриву з’єднання повтори F5 або F6 до того самого призначення. Віддалене копіювання відновлюється з підтвердженої позиції, якщо збережені байти відповідають початку вихідного файла. Підтверджене скасування видаляє частковий запис поточного файла. Завершені файли лишаються на місці. Наявний файл призначення замінюється після повного запису, а при переміщенні джерело видаляється після підтвердження запису призначення. diff --git a/src/files_find.inl b/src/files_find.inl index a7a7e47..8d21397 100644 --- a/src/files_find.inl +++ b/src/files_find.inl @@ -75,6 +75,7 @@ void startFileSearch(Panel &panel,Panel::FindOptions options) { if(panel.scanRequest) return; cancelFolderSizes(panel); + panel.remoteRetry.reset(); panel.scanRequest=Panel::ScanRequest{.directory=panel.directory,.statusRevision=statusRevision,.find=std::move(options)}; startDirectoryScan(panel); } diff --git a/src/files_ftp.inl b/src/files_ftp.inl index 857efc5..1c82b35 100644 --- a/src/files_ftp.inl +++ b/src/files_ftp.inl @@ -4,6 +4,7 @@ struct FtpProfile INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT; ks::Bytes secret; bool legacyNames{}; + std::string id; }; std::vector ftpProfiles; @@ -25,7 +26,7 @@ bool saveFtpProfiles(const std::vector &profiles) for(const auto &profile:profiles) rows.push_back({{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)}, {"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret}, - {"legacyNames",profile.legacyNames}}); + {"legacyNames",profile.legacyNames},{"id",profile.id}}); const auto data=rows.dump(); return data.size()<=ftpProfilesMaxBytes && RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,REG_BINARY,data.data(), @@ -58,7 +59,8 @@ bool loadFtpProfiles() if(!port || port>65535) return false; FtpProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")), ks::wide(row.at("user")),static_cast(port),row.at("secret").get(), - row.value("legacyNames",false)}; + row.value("legacyNames",false),row.value("id",std::string{})}; + if(profile.id.empty()) profile.id="legacy:"+ks::utf8(profile.name); if(profile.name.empty() || profile.host.empty()) return false; profiles.push_back(std::move(profile)); } @@ -99,6 +101,41 @@ void checkFileOperation(bool success) if(!success) requireFileOperation(false,GetLastError()); } +std::wstring ftpFolderError(const std::system_error &error) +{ + switch(error.code().value()) + { + case ERROR_INTERNET_CANNOT_CONNECT: return L"Cannot reach FTP server."; + case ERROR_INTERNET_NAME_NOT_RESOLVED: return L"FTP host name could not be resolved."; + case ERROR_INTERNET_LOGIN_FAILURE: return L"FTP sign-in failed."; + case ERROR_INTERNET_TIMEOUT: return L"FTP connection timed out."; + default: break; + } + if(error.code().value()==ERROR_INTERNET_EXTENDED_ERROR) + { + DWORD response{},length{}; + InternetGetLastResponseInfoW(&response,nullptr,&length); + if(length && length<=2048) + { + std::wstring text(length,L'\0'); + if(InternetGetLastResponseInfoW(&response,text.data(),&length)) + { + text.resize(length); + text.resize(std::min(text.size(),text.find_first_of(L"\r\n"))); + if(!text.empty()) return text; + } + } + return L"The FTP server rejected the request."; + } + wchar_t message[256]{}; + const DWORD length=FormatMessageW(FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS, + GetModuleHandleW(L"wininet.dll"),error.code().value(),0,message,static_cast(std::size(message)),nullptr); + if(!length) return fileError(error); + std::wstring text(message,length); + while(!text.empty() && (text.back()==L'\r' || text.back()==L'\n')) text.pop_back(); + return text; +} + class FtpSession { FtpHandle internet_{InternetOpenW(L"KSwitcher Files",INTERNET_OPEN_TYPE_DIRECT,nullptr,nullptr,0)}; diff --git a/src/files_ftp_dialog.inl b/src/files_ftp_dialog.inl index e918a17..e1b982c 100644 --- a/src/files_ftp_dialog.inl +++ b/src/files_ftp_dialog.inl @@ -91,6 +91,7 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp) profile.secret=ks::protect(bytes); SecureZeroMemory(bytes.data(),bytes.size()); } + profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16); auto updated=ftpProfiles; if(edit.index) updated[*edit.index]=std::move(profile); else updated.push_back(std::move(profile)); diff --git a/src/files_main.cpp b/src/files_main.cpp index d05abad..4ccb16f 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -493,6 +493,13 @@ struct ArchiveLocation std::shared_ptr entries; }; +struct RemotePanelLocation +{ + fs::path directory,cursor; + std::string ftpProfile; + std::optional peer; +}; + struct Panel { HWND path{}, list{}, heading{}; @@ -552,7 +559,17 @@ struct Panel std::optional find; std::optional navigationPosition; std::optional archive; + unsigned reconnectAttempt{}; + fs::path fallbackSelection; }; + struct RemoteRetry + { + RemotePanelLocation location; + std::wstring failure; + ULONGLONG retryAt{}; + unsigned reconnectAttempt{}; + }; + std::optional remoteRetry; struct ScanResult { DirectoryWatch watch; @@ -717,8 +734,14 @@ DWORD statusFields=defaultStatusFields; std::vector drivePaths; int driveHover=-1; std::array driveColumnStarts{}; -HWND drivePeerService{}; -bool drivePeerReplyReceived{}; +struct FilesPeerLookup +{ + HWND service{}; + bool received{}; + std::wstring error; + std::vector peers; +}; +FilesPeerLookup *peerLookupRequest{}; std::wstring drivePeerLookupError; std::vector drivePeers; std::future pendingPeerAction; @@ -831,7 +854,7 @@ FileRowStyle panelRowStyle(const Panel &panel,size_t row,bool cursor,bool active return resolveFileStyle(panel.rows[row].extension().native(),panel.sizes[row]!=L"Folder",panel.dimmed[row], focused || marked || transferred,foreground,background,fileStyles,state,transferred); } -void setStatus(const std::wstring &message); +void setStatus(const std::wstring &message,bool retryAction=false); void refreshCommandHistory(); #include "files_command_history.inl" @@ -1594,9 +1617,13 @@ void layout(HWND window,bool activeOnly) } uint64_t statusRevision{}; -void setStatus(const std::wstring &message) +void setStatus(const std::wstring &message,bool retryAction) { ++statusRevision; + const auto style=GetWindowLongPtrW(status,GWL_STYLE); + const auto actionStyle=(style&~(SS_ENDELLIPSIS|SS_PATHELLIPSIS|SS_WORDELLIPSIS|SS_NOTIFY)) | + (retryAction?(SS_ENDELLIPSIS|SS_NOTIFY):SS_PATHELLIPSIS); + if(style!=actionStyle) SetWindowLongPtrW(status,GWL_STYLE,actionStyle); SetWindowTextW(status, message.c_str()); } @@ -2059,12 +2086,15 @@ void copyCommandLineOrPanelNames(HWND owner) void startFileSearch(Panel &panel,Panel::FindOptions options); void refreshArchive(Panel &panel); +bool retryRemotePanel(Panel &panel,bool automatic=false,const fs::path &fallback={}); void refreshPanel(Panel &panel) { cancelFolderSizes(panel); if(!panel.view.automaticSizes) panel.folderSizes.clear(); updateSelectionSummary(panel); + if(retryRemotePanel(panel)) return; + if(panel.scanRequest && (panel.scanRequest->peer || panel.scanRequest->ftp)) return; if(panel.archive) refreshArchive(panel); else if(panel.findOrigin) startFileSearch(panel,panel.findOrigin->options); else open(panel,panel.directory,false); @@ -2507,6 +2537,11 @@ void showFileDetails(const Panel &panel) { refreshQuickView(panel); if(&panel==&panels[active] && showDirectoryScanProgress(panels[active])) return; + if(panel.remoteRetry) + { + setStatus(L"Ctrl+R to retry · "+panel.remoteRetry->failure,true); + return; + } if(panel.findOrigin) { const auto error=panel.findOrigin->error; @@ -2629,13 +2664,14 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque (info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path); entriesRead.store(folders.size()+files.size(),std::memory_order_relaxed); return !stop.stop_requested(); - }); + },stop); if(stop.stop_requested()) error=ERROR_CANCELLED; if(error!=ERROR_NO_MORE_FILES && error!=ERROR_CANCELLED) requireFileOperation(false,error); } catch(const std::system_error &e) { - failure=L"Cannot read FTP folder on "+request.ftp->name+L": "+fileError(e); + error=static_cast(e.code().value()); + failure=ftpFolderError(e)+L" ("+request.ftp->name+L")"; } catch(const std::exception &e) { @@ -2683,7 +2719,11 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque opened=true; if(!complete) error=ERROR_CANCELLED; } - catch(const std::system_error &e){result->failure=peer->name+L" — "+fileError(e);} + catch(const std::system_error &e) + { + error=static_cast(e.code().value()); + failure=peer->name+L" — "+fileError(e); + } catch(const std::exception &){result->failure=L"Cannot open folder on "+peer->name;} if(!opened && stop.stop_requested()) { @@ -2728,7 +2768,7 @@ void appendTreeRows(Panel &panel,PanelRowsUpdate &rows); bool samePanelSource(const Panel &panel,const std::optional &peer,const std::optional &ftp) { return (panel.peer?panel.peer->id:std::string{})==(peer?peer->id:std::string{}) && - panel.ftp.has_value()==ftp.has_value() && (!panel.ftp || panel.ftp->name==ftp->name); + panel.ftp.has_value()==ftp.has_value() && (!panel.ftp || panel.ftp->id==ftp->id); } bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResult &scan) @@ -2741,7 +2781,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul const bool partial=error==ERROR_CANCELLED; if(!failure.empty()) { - setStatus(failure); + if((!peer && !request.ftp) || &panel==&panels[active]) setStatus(failure); return false; } if(partial && !opened) @@ -2978,15 +3018,18 @@ void startDirectoryScan(Panel &panel) void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional peer, fs::path selection={},fs::path fallback={},std::optional ftp={}, - std::optional navigationPosition={},std::optional archive={}) + std::optional navigationPosition={},std::optional archive={}, + unsigned reconnectAttempt=0,fs::path fallbackSelection={}) { if(directory.empty() && !ftp) return; + panel.remoteRetry.reset(); if(!panel.view.revealedFile.empty() && (peer || ftp || panel.view.revealedFile.parent_path()!=directory)) panel.view.revealedFile.clear(); if(directory!=panel.directory || !samePanelSource(panel,peer,ftp)) cancelFolderSizes(panel); panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback), - std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition,std::move(archive)}; + std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition, + std::move(archive),reconnectAttempt,std::move(fallbackSelection)}; if(panel.scan.valid()) { panel.scanSuperseded=true; @@ -2996,6 +3039,8 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti else startDirectoryScan(panel); } +#include "files_panel_recovery.inl" + void collectDirectoryScans() { for(auto &panel:panels) @@ -3012,21 +3057,37 @@ void collectDirectoryScans() panel.scanRequest.reset(); panel.scanEntriesRead.reset(); bool applied=false; + auto retry=panel.remoteRetry; const auto fallback=request.fallback; + const auto fallbackSelection=request.fallbackSelection; + const bool usesFtp=request.ftp && !request.ftp->id.empty(); try { auto result=panel.scan.get(); + if(!result->failure.empty() && (request.peer || usesFtp) && !panel.scanStop.stop_requested()) + { + retry=Panel::RemoteRetry{{request.directory,request.selection,usesFtp?request.ftp->id:std::string{}, + request.peer},result->failure,0,request.reconnectAttempt}; + if(request.peer && transientLanError(result->error) && retry->reconnectAttemptretryAt=GetTickCount64()+lanRetryDelays[retry->reconnectAttempt]; + } applied=applyDirectoryScan(panel,std::move(request),*result); - if(result->error==ERROR_CANCELLED) continue; + if(result->error==ERROR_CANCELLED && fallback.empty()) continue; } catch(const std::exception &) {setStatus(L"Could not read the folder.");} - if(!applied && !fallback.empty()) openOn(panel,fallback,false,{}); - else if(applied && !panel.scan.valid() && !panel.peer && panel.watch.handle!=INVALID_HANDLE_VALUE && - WaitForSingleObject(panel.watch.handle,0)==WAIT_OBJECT_0) + if(!applied && !fallback.empty()) + { + const auto root=usesFtp?systemPanelRoot():fs::path{}; + openOn(panel,fallback,false,{},fallbackSelection,fallback==root?fs::path{}:root); + } + else if(applied && !panel.scan.valid() && !panel.peer && !panel.ftp && + panel.watch.handle!=INVALID_HANDLE_VALUE && WaitForSingleObject(panel.watch.handle,0)==WAIT_OBJECT_0) { if(!FindNextChangeNotification(panel.watch.handle)) panel.watch.reset(); openOn(panel,panel.directory,false,{}); } + panel.remoteRetry=std::move(retry); + if(panel.remoteRetry && !panel.scan.valid() && &panel==&panels[active]) showFileDetails(panel); } } @@ -3202,7 +3263,9 @@ void refreshChangedPanels() // Pass a copy because opening the folder rebuilds the panel. const auto directory=panel.directory; if(panel.view.automaticSizes) cancelFolderSizes(panel); + auto retry=std::move(panel.remoteRetry); open(panel,directory); + panel.remoteRetry=std::move(retry); } } @@ -3713,44 +3776,51 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT return DefSubclassProc(window,msg,wp,lp); } -void queryDrivePeers() +FilesPeerLookup lookupFilesPeers(HWND owner) { - drivePeers.clear(); - drivePeerLookupError.clear(); - drivePeerReplyReceived=false; - drivePeerService=FindWindowW(L"KSwitcher.Main",L"KSwitcher"); - if(drivePeerService) + FilesPeerLookup lookup; + lookup.service=FindWindowW(L"KSwitcher.Main",L"KSwitcher"); + if(lookup.service) { COPYDATASTRUCT request{FilesLanPeers,0,nullptr}; DWORD_PTR result{}; + auto *previous=std::exchange(peerLookupRequest,&lookup); SetLastError(ERROR_SUCCESS); - const auto delivered=SendMessageTimeoutW(drivePeerService,WM_COPYDATA, - reinterpret_cast(GetParent(picker)),reinterpret_cast(&request), + const auto delivered=SendMessageTimeoutW(lookup.service,WM_COPYDATA, + reinterpret_cast(owner),reinterpret_cast(&request), SMTO_ABORTIFHUNG|SMTO_ERRORONEXIT,350,&result); const auto error=GetLastError(); - if(!delivered || result!=1 || !drivePeerReplyReceived) + peerLookupRequest=previous; + if(!delivered || result!=1 || !lookup.received) { - drivePeers.clear(); + lookup.peers.clear(); if(delivered && result!=1) - drivePeerLookupError=L"KSwitcher rejected the peer request"; + lookup.error=L"KSwitcher rejected the peer request"; else if(delivered) - drivePeerLookupError=L"Invalid peer list from KSwitcher"; + lookup.error=L"Invalid peer list from KSwitcher"; else if(error==ERROR_ACCESS_DENIED) - drivePeerLookupError=L"Access denied by Windows"; + lookup.error=L"Access denied by Windows"; else if(error==ERROR_TIMEOUT) - drivePeerLookupError=L"KSwitcher did not respond in time"; + lookup.error=L"KSwitcher did not respond in time"; else - drivePeerLookupError=L"Peer request failed (Windows code "+std::to_wstring(error)+L")"; + lookup.error=L"Peer request failed (Windows code "+std::to_wstring(error)+L")"; ks::log(L"LAN Files peer lookup failed: delivered="+std::to_wstring(delivered!=0)+ L", reply="+std::to_wstring(result)+L", Windows error="+std::to_wstring(error)); } } else { - drivePeerLookupError=L"KSwitcher is not running"; + lookup.error=L"KSwitcher is not running"; ks::log(L"LAN Files peer lookup failed: local KSwitcher window not found"); } - drivePeerService=nullptr; + return lookup; +} + +void queryDrivePeers() +{ + auto lookup=lookupFilesPeers(GetParent(picker)); + drivePeers=std::move(lookup.peers); + drivePeerLookupError=std::move(lookup.error); } void startDriveQuery(DriveQuery &query) @@ -7766,7 +7836,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) case WM_COPYDATA: { const auto *reply=reinterpret_cast(lp); - if(!drivePeerService || reinterpret_cast(wp)!=drivePeerService || !reply || + auto *lookup=peerLookupRequest; + if(!lookup || reinterpret_cast(wp)!=lookup->service || !reply || reply->dwData!=FilesLanPeersReply || reply->cbData>FilesLanPeersLimit || (!reply->cbData || !reply->lpData)) return FALSE; try @@ -7775,11 +7846,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) const auto rows=Json::parse(begin,begin+reply->cbData); if(!rows.is_array()) return FALSE; for(const auto &row:rows) - drivePeers.push_back({row.at("id"),row.at("address"),ks::wide(row.at("name")),ks::lan::FilesPort, + lookup->peers.push_back({row.at("id"),row.at("address"),ks::wide(row.at("name")),ks::lan::FilesPort, row.value("filesBrowse",false)}); } - catch(const std::exception &){drivePeers.clear();return FALSE;} - drivePeerReplyReceived=true; + catch(const std::exception &){lookup->peers.clear();return FALSE;} + lookup->received=true; return TRUE; } case ks::files::quickViewToggleMessage: @@ -7812,6 +7883,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) { collectDirectoryScans(); collectTreeBranches(); + pollRemotePanels(); refreshChangedPanels(); showDirectoryScanProgress(panels[active]); } @@ -7898,12 +7970,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) for (auto child : {panel.path, panel.list, panel.selectionSummary}) SendMessageW(child, WM_SETFONT, reinterpret_cast(mono), FALSE); SendMessageW(panel.list,LB_SETITEMHEIGHT,0,textHeight); - wchar_t system[MAX_PATH]{}; - GetWindowsDirectoryW(system, MAX_PATH); - const auto saved=savedPanelPath(panelPathKeys[i]); - const auto root=fs::path(system).root_path(); - openOn(panel,saved.is_absolute()?saved:root,false,{},savedPanelPath(panelCursorKeys[i]), - saved.is_absolute() && saved!=root?root:fs::path{}); + restorePanelLocation(panel,i); SetWindowSubclass(panel.list, panelKeys, 1, 0); if(auto target=new(std::nothrow) PanelDropTarget(panel.list)) { @@ -8451,6 +8518,17 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) resetCompletion(); } if(copyInProgress || commandHistoryWindow || FilesModalDialog::activeFor(window)) return 0; + if(reinterpret_cast(lp)==status && HIWORD(wp)==STN_CLICKED) + { + auto &panel=panels[active]; + if(panel.remoteRetry && !panel.scan.valid()) + { + const auto message=panel.remoteRetry->failure+L"\r\n\r\nRetry opening this folder?"; + if(showFilesNotice(window,message.c_str(),L"Remote folder",{.confirm=true})==IDYES) + refreshPanel(panel); + } + return 0; + } if(LOWORD(wp)==121 && HIWORD(wp)==LBN_DBLCLK) selectDrive(); if(LOWORD(wp)>=130 && LOWORD(wp)<=134 && HIWORD(wp)==BN_CLICKED) { @@ -8486,6 +8564,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) savePlacement(window); for(int i=0;i<2;++i) { + saveFtpPanelLocation(panels[i],i); const auto path=(panels[i].archive?panels[i].archive->file.parent_path():panels[i].directory).native(); if(!panels[i].peer && !panels[i].ftp && !path.empty()) RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelPathKeys[i],REG_SZ,path.c_str(), diff --git a/src/files_panel_recovery.inl b/src/files_panel_recovery.inl new file mode 100644 index 0000000..c05c95c --- /dev/null +++ b/src/files_panel_recovery.inl @@ -0,0 +1,148 @@ +constexpr std::array lanRetryDelays{1200,2500,5000}; +constexpr const wchar_t *ftpPanelLocationKeys[]{L"LeftFtpLocation",L"RightFtpLocation"}; +constexpr DWORD maxFtpLocationBytes=256*1024; + +FilesPeerLookup lookupFilesPeers(HWND owner); + +bool transientLanError(DWORD code) +{ + switch(code) + { + case WSAENETDOWN: + case WSAENETUNREACH: + case WSAENETRESET: + case WSAECONNABORTED: + case WSAECONNRESET: + case WSAECONNREFUSED: + case WSAETIMEDOUT: + case WSAEHOSTDOWN: + case WSAEHOSTUNREACH: + case ERROR_CONNECTION_ABORTED: + case ERROR_NETNAME_DELETED: + case ERROR_NETWORK_UNREACHABLE: + case ERROR_SEM_TIMEOUT: + return true; + default: + return false; + } +} + +bool retryRemotePanel(Panel &panel,bool automatic,const fs::path &fallback) +{ + if(!panel.remoteRetry) return false; + auto &retry=*panel.remoteRetry; + auto location=retry.location; + const auto attempt=automatic?retry.reconnectAttempt+1:0; + if(location.peer) + { + const auto lookup=lookupFilesPeers(GetParent(panel.list)); + const auto peer=std::find_if(lookup.peers.begin(),lookup.peers.end(),[&](const auto &entry) { + return entry.id==location.peer->id && !entry.address.empty(); + }); + if(peer!=lookup.peers.end()) location.peer=*peer; + openOn(panel,location.directory,false,std::move(location.peer),location.cursor, + {},{},{},{},attempt); + return true; + } + const bool loaded=loadFtpProfiles(); + const auto profile=std::find_if(ftpProfiles.begin(),ftpProfiles.end(),[&](const auto &entry) { + return entry.id==location.ftpProfile; + }); + if(!loaded || profile==ftpProfiles.end()) + { + retry.failure=loaded?L"The saved FTP connection is missing. Select a profile in Change drive → FTP.": + L"Could not load the saved FTP connections."; + if(&panel==&panels[active] && !panel.scan.valid()) showFileDetails(panel); + return true; + } + openOn(panel,location.directory,false,{},location.cursor,fallback,*profile,{},{},0, + fallback.empty()?fs::path{}:savedPanelPath(panelCursorKeys[&panel-panels])); + return true; +} + +void pollRemotePanels() +{ + const auto now=GetTickCount64(); + for(auto &panel:panels) + if(!panel.scan.valid() && panel.remoteRetry && panel.remoteRetry->retryAt && + now>=panel.remoteRetry->retryAt) + retryRemotePanel(panel,true); +} + +bool ftpPanelPath(const fs::path &path) +{ + return path.has_root_directory() && !path.has_root_name(); +} + +std::optional savedFtpPanelLocation(int index) +{ + DWORD size{}; + if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpPanelLocationKeys[index],RRF_RT_REG_BINARY,nullptr, + nullptr,&size)!=ERROR_SUCCESS || !size || size>maxFtpLocationBytes) return {}; + std::string data(size,'\0'); + if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpPanelLocationKeys[index],RRF_RT_REG_BINARY,nullptr, + data.data(),&size)!=ERROR_SUCCESS) return {}; + try + { + const auto saved=Json::parse(data.begin(),data.begin()+size); + RemotePanelLocation location{fs::path(ks::wide(saved.at("directory"))),fs::path(ks::wide(saved.at("cursor"))), + saved.at("profile").get()}; + if(!ftpPanelPath(location.directory) || location.ftpProfile.empty()) return {}; + if(!location.cursor.empty() && !ftpPanelPath(location.cursor)) location.cursor.clear(); + return location; + } + catch(const std::exception &) {return {};} +} + +void saveFtpPanelLocation(const Panel &panel,int index) +{ + RemotePanelLocation location; + if(panel.ftp && !panel.ftp->id.empty()) + { + const auto row=currentPanelRow(panel); + location={panel.directory,row<0?fs::path{}:panel.rows[row],panel.ftp->id}; + } + else if(panel.remoteRetry && !panel.remoteRetry->location.ftpProfile.empty()) + location=panel.remoteRetry->location; + else if(panel.scanRequest && panel.scanRequest->ftp) + location={panel.scanRequest->directory,panel.scanRequest->selection,panel.scanRequest->ftp->id}; + + const auto key=ftpPanelLocationKeys[index]; + if(location.ftpProfile.empty() || !ftpPanelPath(location.directory)) + { + RegDeleteKeyValueW(HKEY_CURRENT_USER,schemeKey,key); + return; + } + try + { + const auto data=Json{{"profile",location.ftpProfile},{"directory",ks::utf8(location.directory.native())}, + {"cursor",ks::utf8(location.cursor.native())}}.dump(); + if(data.size()<=maxFtpLocationBytes) + RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,key,REG_BINARY,data.data(),static_cast(data.size())); + } + catch(const std::exception &) {} +} + +fs::path systemPanelRoot() +{ + wchar_t system[MAX_PATH]{}; + GetWindowsDirectoryW(system,MAX_PATH); + return fs::path(system).root_path(); +} + +void restorePanelLocation(Panel &panel,int index) +{ + const auto root=systemPanelRoot(); + const auto saved=savedPanelPath(panelPathKeys[index]); + const auto local=saved.is_absolute()?saved:root; + auto remote=savedFtpPanelLocation(index); + if(remote) + { + panel.remoteRetry=Panel::RemoteRetry{std::move(*remote),L"Could not restore the saved FTP folder."}; + retryRemotePanel(panel,false,local); + if(panel.scan.valid()) return; + } + auto retry=std::move(panel.remoteRetry); + openOn(panel,local,false,{},savedPanelPath(panelCursorKeys[index]),local!=root?root:fs::path{}); + panel.remoteRetry=std::move(retry); +} diff --git a/tests/files_commands_ui.ps1 b/tests/files_commands_ui.ps1 index 38efd08..09d2eaf 100644 --- a/tests/files_commands_ui.ps1 +++ b/tests/files_commands_ui.ps1 @@ -24,6 +24,7 @@ public static class FilesCommandsUi { [DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr window, out Rect rect); [DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr window, ref Point point); [DllImport("user32.dll")] public static extern bool RedrawWindow(IntPtr window, IntPtr rect, IntPtr region, uint flags); + [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr window, IntPtr target, uint flags); [DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint msg, IntPtr w, IntPtr l); [DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint msg, IntPtr w, IntPtr l); [DllImport("user32.dll", CharSet=CharSet.Unicode, EntryPoint="SendMessageW")] diff --git a/tests/files_comparison_splitter.ps1 b/tests/files_comparison_splitter.ps1 index 9776b90..bfc2424 100644 --- a/tests/files_comparison_splitter.ps1 +++ b/tests/files_comparison_splitter.ps1 @@ -5,7 +5,8 @@ Add-Type -AssemblyName System.Drawing . "$PSScriptRoot/files_commands_ui.ps1" $preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files') -$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance' +$names = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance', + 'LeftFtpLocation', 'RightFtpLocation' $saved = @{} foreach ($name in $names) { if ($name -in $preferences.GetValueNames()) { @@ -16,6 +17,24 @@ $temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\') $root = Join-Path $temp ('ks-files-splitter-' + [Guid]::NewGuid().ToString('N')) $dpi = [FilesCommandsUi]::SetThreadDpiAwarenessContext([IntPtr](-4)) $process = $null + +function Render-ComparisonList([IntPtr]$List, [FilesCommandsUi+Rect]$Bounds) { + $bitmap = [Drawing.Bitmap]::new($Bounds.Right, $Bounds.Bottom) + try { + $graphics = [Drawing.Graphics]::FromImage($bitmap) + try { + $dc = $graphics.GetHdc() + try { + if (![FilesCommandsUi]::PrintWindow($List, $dc, 3)) { throw 'Could not render the comparison list.' } + } finally { $graphics.ReleaseHdc($dc) } + } finally { $graphics.Dispose() } + } catch { + $bitmap.Dispose() + throw + } + $bitmap +} + try { $left = Join-Path $root 'left' $right = Join-Path $root 'right' @@ -25,7 +44,8 @@ try { [IO.File]::WriteAllText((Join-Path $right 'sample.txt'), "one`nthree") $preferences.SetValue('LeftPath', $left) $preferences.SetValue('RightPath', $right) - foreach ($name in 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance') { + foreach ($name in 'LeftCursor', 'RightCursor', 'WindowPlacement', 'ComparisonAppearance', + 'LeftFtpLocation', 'RightFtpLocation') { $preferences.DeleteValue($name, $false) } @@ -42,14 +62,14 @@ try { [void][FilesCommandsUi]::Send($panel, 390, [IntPtr]1, [IntPtr]::Zero) } Invoke-FilesCommand $main 'Compare files*' - $comparison = Wait-For 'the foreground comparison window' { + $comparison = Wait-For 'the rendered comparison window' { $dialog = [IntPtr]::Zero while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero,$dialog,'#32770','Compare files')) -ne [IntPtr]::Zero) { [uint32]$ownerPid = 0 [void][FilesCommandsUi]::GetWindowThreadProcessId($dialog, [ref]$ownerPid) if ($ownerPid -ne $process.Id) { continue } $control = [FilesCommandsUi]::GetDlgItem($dialog, 402) - if ([FilesCommandsUi]::IsWindowVisible($control) -and [FilesCommandsUi]::Activate($dialog)) { + if ([FilesCommandsUi]::IsWindowVisible($control)) { return $dialog } } @@ -68,15 +88,10 @@ try { } [void][FilesCommandsUi]::Send($list, 514, [IntPtr]::Zero, [IntPtr]($mouseY -bor $destination)) [void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101) - $origin = [FilesCommandsUi+Point]::new() - [void][FilesCommandsUi]::ClientToScreen($list, [ref]$origin) - $bitmap = [Drawing.Bitmap]::new($bounds.Right, 1) + $bitmap = Render-ComparisonList $list $bounds try { - $graphics = [Drawing.Graphics]::FromImage($bitmap) - try { $graphics.CopyFromScreen($origin.X, ($origin.Y + $bounds.Bottom - 10), 0, 0, $bitmap.Size) } - finally { $graphics.Dispose() } $ink = @(for ($x = $middle - 4; $x -le $destination + 4; ++$x) { - if ($bitmap.GetPixel($x, 0).ToArgb() -ne [Drawing.Color]::White.ToArgb()) { $x } + if ($bitmap.GetPixel($x, $bounds.Bottom - 10).ToArgb() -ne [Drawing.Color]::White.ToArgb()) { $x } }) # Desktop scaling can spread the single-pixel divider across two adjacent screen pixels. if (!$ink.Count -or $ink.Count -gt 2 -or [Math]::Abs($ink[0] - $destination) -gt 1 -or @@ -92,14 +107,13 @@ try { [void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101) $height = [FilesCommandsUi]::Send($list, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() # This part of the first unchanged row contains the right line number in the default font. - $numbers = [Drawing.Bitmap]::new([int]($height * 1.45), $height) + $numbers = Render-ComparisonList $list $bounds try { - $graphics = [Drawing.Graphics]::FromImage($numbers) - try { $graphics.CopyFromScreen(($origin.X + [int]($height * 3.6)), $origin.Y, 0, 0, $numbers.Size) } - finally { $graphics.Dispose() } + $left = [int]($height * 3.6) + $right = [int]($height * 5.05) $hasNumber = $false for ($y = [int]($height / 4); $y -lt [int]($height * 3 / 4) -and !$hasNumber; ++$y) { - for ($x = 0; $x -lt $numbers.Width; ++$x) { + for ($x = $left; $x -lt $right; ++$x) { $pixel = $numbers.GetPixel($x, $y) if ($pixel.R -lt 90 -and $pixel.G -lt 90 -and $pixel.B -lt 90) { $hasNumber = $true @@ -109,7 +123,7 @@ try { } if (!$hasNumber) { throw 'The right line number did not render in the Unified view.' } } finally { $numbers.Dispose() } - 'Verified the dragged divider and both line numbers in the Unified view.' + 'Verified the dragged divider and the right line number in the Unified view.' } finally { if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() } foreach ($name in $names) { From 20d95b37aa502ec8bb1ff63eac9f24bc947e7c87 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 17:34:22 +0200 Subject: [PATCH 24/61] Add remote folder breadcrumbs and recent locations Refs #108 --- FILES-UI.md | 18 ++- src/files_ftp.inl | 13 ++ src/files_main.cpp | 135 +++++++++++------ src/files_panel_recovery.inl | 41 +++-- src/files_path_navigation.inl | 226 +++++++++++++++++++--------- src/files_recent_folders.inl | 57 +++++-- tests/files_comparison_splitter.ps1 | 3 +- 7 files changed, 343 insertions(+), 150 deletions(-) diff --git a/FILES-UI.md b/FILES-UI.md index 943ae31..63a2da9 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -614,12 +614,15 @@ Warning і початковий фокус на No. показують перший кадр. Пошкоджені та надто великі файли показують повідомлення. - **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує - останні відвідані локальні папки. Повторний візит підіймає один запис - угору, порядок зберігається після перезапуску. Enter або клік відкриває - шлях у панелі, з якої викликали меню. Delete прибирає вибраний запис. + останні відвідані локальні, FTP та LAN-папки. Повторний візит підіймає + один запис угору, порядок зберігається після перезапуску. Enter або клік + відкриває шлях у панелі, з якої викликали меню. Віддалені записи містять + шлях і ідентифікатор збереженого FTP-профілю або спареного ПК. Паролі + зберігаються лише в налаштуваннях FTP-профілів. Delete прибирає вибраний + запис із недавніх. -- У локальному заголовку кнопки ← та → переходять назад і вперед - в історії відповідної панелі. Стрілка ↑, Alt+↑ та рядок `..` +- Кнопки ← та → переходять назад і вперед в історії відповідної панелі, + зокрема між локальними, FTP та LAN-папками. Стрілка ↑, Alt+↑ та рядок `..` відкривають безпосередню батьківську папку. На корені стрілка вимкнена, а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі. - Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва @@ -628,7 +631,10 @@ Warning і початковий фокус на No. відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях, а Esc повертає до тих самих панелей і курсора. -- Для LAN і FTP поточний шлях відображається по центру верхньої подвійної лінії панелі. Довгий шлях скорочується в межах панелі. +- У заголовку FTP-папки клік по назві профілю відкриває збережені + підключення. У LAN-папці клік по назві ПК відкриває спарені комп’ютери + та їхні диски. Поле шляху й доповнення працюють у поточному джерелі. + Для FTP абсолютний шлях починається з /. ## Спільні елементи діалогів diff --git a/src/files_ftp.inl b/src/files_ftp.inl index 1c82b35..eb8f75b 100644 --- a/src/files_ftp.inl +++ b/src/files_ftp.inl @@ -13,6 +13,11 @@ constexpr wchar_t ftpProfilesValue[]=L"FtpProfiles"; constexpr DWORD ftpProfilesMaxBytes=1024*1024; const fs::path ftpRoot=L"\\"; +bool isFtpFolderPath(const fs::path &path) +{ + return path.has_root_directory() && !path.has_root_name(); +} + std::wstring ftpPath(const fs::path &path) { auto value=path.native(); @@ -71,6 +76,14 @@ bool loadFtpProfiles() catch(const std::exception &) {return false;} } +const FtpProfile *findFtpProfile(std::string_view id) +{ + const auto profile=std::find_if(ftpProfiles.begin(),ftpProfiles.end(),[&](const auto &entry) { + return entry.id==id; + }); + return profile==ftpProfiles.end()?nullptr:&*profile; +} + std::wstring ftpPassword(const FtpProfile &profile) { if(profile.secret.empty()) return {}; diff --git a/src/files_main.cpp b/src/files_main.cpp index 4ccb16f..112b247 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -381,48 +381,72 @@ fs::path panelParentPath(const fs::path &directory,bool local) return parent; } -bool sameLocalFolder(const fs::path &a,const fs::path &b) +enum class FolderProvider { local, ftp, lan }; + +struct FolderLocation { - return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,TRUE)==CSTR_EQUAL; + fs::path directory; + FolderProvider provider{FolderProvider::local}; + std::string id; + std::wstring label; + + bool sameSource(const FolderLocation &other) const {return provider==other.provider && id==other.id;} +}; + +bool sameFolderPath(const fs::path &a,const fs::path &b,FolderProvider provider) +{ + return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,provider==FolderProvider::ftp?FALSE:TRUE)==CSTR_EQUAL; } -bool inLocalBranch(const fs::path &ancestor,fs::path directory) +bool sameFolderLocation(const FolderLocation &a,const FolderLocation &b) +{ + return a.sameSource(b) && sameFolderPath(a.directory,b.directory,a.provider); +} + +bool inFolderBranch(const fs::path &ancestor,fs::path directory,FolderProvider provider) { while(!directory.empty()) { - if(sameLocalFolder(ancestor,directory)) return true; - directory=panelParentPath(directory,true); + if(sameFolderPath(ancestor,directory,provider)) return true; + directory=panelParentPath(directory,provider==FolderProvider::local); } return false; } #include "files_recent_folders.inl" -struct LocalNavigation +struct FolderNavigation { - std::vector history; + std::vector history; size_t current{}; fs::path previousBranch; - void opened(const fs::path &directory,std::optional position) + void opened(FolderLocation location,std::optional position) { if(!history.empty()) { const auto &previous=history[current]; - if(sameLocalFolder(previous,directory)) return; - if(inLocalBranch(directory,previous)) + if(sameFolderLocation(previous,location)) { - if(!inLocalBranch(previous,previousBranch)) previousBranch=previous; + history[current]=std::move(location); + return; } - else if(!inLocalBranch(directory,previousBranch)) previousBranch.clear(); + const auto provider=location.provider; + if(!previous.sameSource(location)) previousBranch.clear(); + else if(inFolderBranch(location.directory,previous.directory,provider)) + { + if(!inFolderBranch(previous.directory,previousBranch,provider)) previousBranch=previous.directory; + } + else if(!inFolderBranch(location.directory,previousBranch,provider)) previousBranch.clear(); } - if(position && *position peer; + std::optional navigationPosition; }; struct Panel { HWND path{}, list{}, heading{}; fs::path directory; - LocalNavigation navigation; + FolderNavigation navigation; std::optional peer; std::optional ftp; std::optional archive; @@ -627,6 +652,13 @@ bool ftpProfileList(const Panel &panel) return panel.ftp && panel.ftp->name.empty(); } +FolderLocation folderLocation(const Panel &panel,const fs::path &directory) +{ + if(panel.ftp) return {directory,FolderProvider::ftp,panel.ftp->id,panel.ftp->name}; + if(panel.peer) return {directory,FolderProvider::lan,panel.peer->id,panel.peer->name}; + return {directory}; +} + std::wstring panelLocation(const Panel &panel) { if(panel.ftp) @@ -720,7 +752,7 @@ bool commandPicker{}; struct FolderPicker { const wchar_t *caption; - std::vector paths; + std::vector locations; bool recent{}; }; std::optional folderPicker; @@ -732,6 +764,7 @@ bool alignExtensions=defaultAlignExtensions, showDetails=defaultShowDetails; bool alignFolders=defaultAlignFolders; DWORD statusFields=defaultStatusFields; std::vector drivePaths; +bool lanDrivePicker{}; int driveHover=-1; std::array driveColumnStarts{}; struct FilesPeerLookup @@ -801,7 +834,7 @@ void savePlacement(HWND window) RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,placementPreference,REG_BINARY, &placement,sizeof(placement)); } -void chooseDrive(int index, bool fromMenu = false); +void chooseDrive(int index,bool fromMenu=false,bool lanOnly=false); enum class FilesNoticeTone { dialog, neutral, warning }; struct FilesNoticeOptions { @@ -2776,7 +2809,8 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul const auto &directory=scan.ftpInitialDirectory.empty()?request.directory:scan.ftpInitialDirectory; auto &peer=request.peer; const auto previousDirectory=samePanelSource(panel,peer,request.ftp)?panel.directory:fs::path{}; - const bool sameDirectory=previousDirectory==directory; + const auto provider=peer?FolderProvider::lan:request.ftp?FolderProvider::ftp:FolderProvider::local; + const bool sameDirectory=sameFolderPath(previousDirectory,directory,provider); auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=scan; const bool partial=error==ERROR_CANCELLED; if(!failure.empty()) @@ -2869,12 +2903,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul if(mark.parent_path()==folderPathWithoutSeparator(directory)) markedPaths.insert(mark); panel.listReturnMarks.clear(); } - if(peer || request.ftp) panel.navigation={}; - else if(!finding && !request.archive) - { - panel.navigation.opened(directory,request.navigationPosition); - if(!sameDirectory && !panel.directory.empty() && !partial) updateRecentFolders(directory,true); - } + const bool rememberFolder=!sameDirectory && !partial && (!panel.directory.empty() || peer || request.ftp); panel.directory = directory; panel.peer=std::move(peer); panel.ftp=std::move(request.ftp); @@ -2892,6 +2921,12 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul std::swap(panel.watch.handle,nextWatch.handle); } const bool profiles=ftpProfileList(panel); + if(!finding && !panel.archive && !profiles) + { + auto location=folderLocation(panel,directory); + if(rememberFolder) updateRecentFolders(location,true); + panel.navigation.opened(std::move(location),request.navigationPosition); + } const bool renderTree=panel.view.tree && !finding && !profiles && !panel.archive; panel.filteredMarks.clear(); if(renderTree) replaceTreeRoot(panel,scan,sameDirectory,markedPaths); @@ -3067,7 +3102,7 @@ void collectDirectoryScans() if(!result->failure.empty() && (request.peer || usesFtp) && !panel.scanStop.stop_requested()) { retry=Panel::RemoteRetry{{request.directory,request.selection,usesFtp?request.ftp->id:std::string{}, - request.peer},result->failure,0,request.reconnectAttempt}; + request.peer,request.navigationPosition},result->failure,0,request.reconnectAttempt}; if(request.peer && transientLanError(result->error) && retry->reconnectAttemptretryAt=GetTickCount64()+lanRetryDelays[retry->reconnectAttempt]; } @@ -3553,14 +3588,15 @@ void runActivePeerAction(HWND owner,bool update) (update?L"Requesting a KSwitcher update on ":L"Requesting hibernation for ")+peer.name+L"..."); } -LRESULT ftpDriveRow() {return static_cast(drivePaths.size())+1;} -LRESULT recentDriveRow() {return ftpDriveRow()+1;} +LRESULT ftpDriveRow() {return lanDrivePicker?-1:static_cast(drivePaths.size())+1;} +LRESULT recentDriveRow() {return lanDrivePicker?-1:ftpDriveRow()+1;} +LRESULT lanHeaderRow() {return recentDriveRow()+1;} void showRecentFolders(int side); bool selectablePickerRow(LRESULT row) { if(row<0) return false; - if(folderPicker) return static_cast(row)paths.size(); + if(folderPicker) return static_cast(row)locations.size(); if(commandPicker) return static_cast(row)=0; return row(drivePaths.size()) || row==ftpDriveRow() || row==recentDriveRow() || @@ -3573,10 +3609,10 @@ void selectDrive() if(!selectablePickerRow(row)) return; if(folderPicker) { - const auto path=folderPicker->paths[row]; + const auto location=folderPicker->locations[row]; auto &panel=panels[pickerPanel]; hidePicker(); - openOn(panel,path,true,{}); + openFolderLocation(panel,location); return; } if(commandPicker) row=commandActions[row]; @@ -3638,7 +3674,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT { const auto row=SendMessageW(window,LB_GETCURSEL,0,0); if(!selectablePickerRow(row)) return 0; - auto &paths=folderPicker->paths; + auto &paths=folderPicker->locations; if(!updateRecentFolders(paths[row],false)) { setStatus(L"Could not remove the recent folder."); @@ -3649,7 +3685,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT if(paths.empty()) { hidePicker(); - setStatus(L"No recent local folders."); + setStatus(L"No recent folders."); } else SendMessageW(window,LB_SETCURSEL,std::min(row,static_cast(paths.size()-1)),0); return 0; @@ -3854,7 +3890,8 @@ void layoutDrivePicker(int selected,bool focus) const int panelWidth=panel.right-panel.left; const auto frame=dialogFrameMetrics(GetDpiForWindow(owner)); const int inset=frame.content(),vertical=dialogListInset(frame,textHeight); - const int width=std::clamp(drivePickerWidth,90,std::max(90,panelWidth*4/5-2*inset)); + const int limit=lanDrivePicker?panelWidth:panelWidth*4/5; + const int width=std::clamp(drivePickerWidth,90,std::max(90,limit-2*inset)); const int height=std::min(std::max(1,(static_cast(panel.bottom-panel.top)-2*vertical)/textHeight), static_cast(SendMessageW(picker,LB_GETCOUNT,0,0)))*textHeight; const int x=panel.left+(panel.right-panel.left-width)/2; @@ -3880,7 +3917,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0) auto selection=SendMessageW(picker,LB_GETCURSEL,0,0); std::optional previous; if(auto row=remoteDriveRows.find(selection);row!=remoteDriveRows.end()) previous=row->second; - if(selection>recentDriveRow()) selection=-1; + if(selection>=lanHeaderRow()) selection=-1; if(focus) selection=initialRow; const auto top=SendMessageW(picker,LB_GETTOPINDEX,0,0); for(auto count=SendMessageW(picker,LB_GETCOUNT,0,0);count>static_cast(drivePaths.size());--count) @@ -3891,12 +3928,17 @@ void showRemoteDrives(bool focus=false,int initialRow=0) drivePickerWidth=std::max(drivePickerWidth,static_cast(label.size()+2)*cellWidth); return SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast(label.c_str())); }; - add(L""); - add(L"FTP"); - add(L"Recent folders"); + if(!lanDrivePicker) + { + add(L""); + add(L"FTP"); + add(L"Recent folders"); + } add(L"KSwitcher LAN"); if(!drivePeerLookupError.empty()) add(L" "+drivePeerLookupError); else if(driveQueries.empty()) add(L" No paired computers"); + LRESULT firstDrive=-1,matchingDrive=-1; + const auto ¤t=panels[pickerPanel]; for(const auto &query:driveQueries) { add(query.peer.name); @@ -3905,6 +3947,9 @@ void showRemoteDrives(bool focus=false,int initialRow=0) const auto row=add(label); if(row<0) return; if(previous && previous->peer.id==query.peer.id && previous->path==path) selection=row; + if(firstDrive<0) firstDrive=row; + if(current.peer && current.peer->id==query.peer.id && path==current.directory.root_path()) + matchingDrive=row; const auto id=std::pair{query.peer.id,path}; constexpr std::wstring_view available=L"234567890"; auto digit=driveDigits.find(id); @@ -3929,6 +3974,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0) addChoice(L" "+labels[0]+L" "+labels[1]+L" "+labels[2],root); } } + if(lanDrivePicker && selection<=0) selection=matchingDrive>=0?matchingDrive:firstDrive; layoutDrivePicker(static_cast(selection),focus); InvalidateRect(picker,nullptr,FALSE); if(!focus) SendMessageW(picker,LB_SETTOPINDEX,top,0); @@ -4002,8 +4048,9 @@ void pollDriveQueries(HWND owner) if(!pending && !nextDriveRefresh) KillTimer(owner,driveQueryTimer); } -void chooseDrive(int index,bool fromMenu) +void chooseDrive(int index,bool fromMenu,bool lanOnly) { + lanDrivePicker=lanOnly; if(quickViewWindow && index!=quickViewSource) toggleQuickView(GetParent(picker)); folderPicker.reset(); commandPicker=false; @@ -4025,7 +4072,7 @@ void chooseDrive(int index,bool fromMenu) const auto now=GetTickCount64(); nextDriveRefresh=now+500; driveRefreshDeadline=now+20000; - const DWORD disks=GetLogicalDrives(); + const DWORD disks=lanOnly?0:GetLogicalDrives(); int selected=0; int textWidth=0; auto dc=GetDC(picker); @@ -8154,9 +8201,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } } const bool highlighted=static_cast(item.CtlID)-142==active; - if(localNavigationAvailable(panel)) + if(pathNavigationAvailable(panel)) { - paintLocalPath(item.hDC,bounds,panel,highlighted); + paintPanelPath(item.hDC,bounds,panel,highlighted); return TRUE; } if(path.empty()) return TRUE; @@ -8265,7 +8312,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) auto background=item.CtlType==ODT_BUTTON?Footer:popupRow?Dialog:PanelBlue; auto foreground=colors[Text]; if(item.hwndItem==picker && !folderPicker && ((commandPicker && item.itemID(GetStockObject(DC_BRUSH))); return TRUE; } - if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID==recentDriveRow()+1) + if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID==lanHeaderRow()) { auto row=item.rcItem; FillRect(item.hDC,&row,teal); @@ -8686,7 +8733,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) if(message.hwnd==window && message.message>=WM_KEYFIRST && message.message<=WM_KEYLAST && GetFocus()==terminalInput) message.hwnd=terminalInput; - if(handleQuickViewKey(window,message) || handleLocalPathKey(window,message)) continue; + if(handleQuickViewKey(window,message) || handlePanelPathKey(window,message)) continue; if(message.hwnd==terminalInput && message.message==WM_KEYDOWN && !(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) && diff --git a/src/files_panel_recovery.inl b/src/files_panel_recovery.inl index c05c95c..b6e70d3 100644 --- a/src/files_panel_recovery.inl +++ b/src/files_panel_recovery.inl @@ -41,25 +41,43 @@ bool retryRemotePanel(Panel &panel,bool automatic,const fs::path &fallback) }); if(peer!=lookup.peers.end()) location.peer=*peer; openOn(panel,location.directory,false,std::move(location.peer),location.cursor, - {},{},{},{},attempt); + {},{},location.navigationPosition,{},attempt); return true; } const bool loaded=loadFtpProfiles(); - const auto profile=std::find_if(ftpProfiles.begin(),ftpProfiles.end(),[&](const auto &entry) { - return entry.id==location.ftpProfile; - }); - if(!loaded || profile==ftpProfiles.end()) + const auto *profile=loaded?findFtpProfile(location.ftpProfile):nullptr; + if(!profile) { retry.failure=loaded?L"The saved FTP connection is missing. Select a profile in Change drive → FTP.": L"Could not load the saved FTP connections."; if(&panel==&panels[active] && !panel.scan.valid()) showFileDetails(panel); return true; } - openOn(panel,location.directory,false,{},location.cursor,fallback,*profile,{},{},0, + openOn(panel,location.directory,false,{},location.cursor,fallback,*profile,location.navigationPosition,{},0, fallback.empty()?fs::path{}:savedPanelPath(panelCursorKeys[&panel-panels])); return true; } +void openFolderLocation(Panel &panel,const FolderLocation &location,std::optional position={}) +{ + if(location.directory.empty()) return; + if(location.provider==FolderProvider::local) + { + openOn(panel,location.directory,true,{},{},{},{},position); + return; + } + if(location.sameSource(folderLocation(panel,panel.directory))) + { + openOn(panel,location.directory,false,panel.peer,{},{},panel.ftp,position); + return; + } + RemotePanelLocation remote{location.directory,{},{},{},position}; + if(location.provider==FolderProvider::ftp) remote.ftpProfile=location.id; + else remote.peer=FilesPeer{location.id,{},location.label.empty()?L"LAN peer":location.label}; + panel.remoteRetry=Panel::RemoteRetry{std::move(remote),L"Could not restore the remote folder."}; + retryRemotePanel(panel); +} + void pollRemotePanels() { const auto now=GetTickCount64(); @@ -69,11 +87,6 @@ void pollRemotePanels() retryRemotePanel(panel,true); } -bool ftpPanelPath(const fs::path &path) -{ - return path.has_root_directory() && !path.has_root_name(); -} - std::optional savedFtpPanelLocation(int index) { DWORD size{}; @@ -87,8 +100,8 @@ std::optional savedFtpPanelLocation(int index) const auto saved=Json::parse(data.begin(),data.begin()+size); RemotePanelLocation location{fs::path(ks::wide(saved.at("directory"))),fs::path(ks::wide(saved.at("cursor"))), saved.at("profile").get()}; - if(!ftpPanelPath(location.directory) || location.ftpProfile.empty()) return {}; - if(!location.cursor.empty() && !ftpPanelPath(location.cursor)) location.cursor.clear(); + if(!isFtpFolderPath(location.directory) || location.ftpProfile.empty()) return {}; + if(!location.cursor.empty() && !isFtpFolderPath(location.cursor)) location.cursor.clear(); return location; } catch(const std::exception &) {return {};} @@ -108,7 +121,7 @@ void saveFtpPanelLocation(const Panel &panel,int index) location={panel.scanRequest->directory,panel.scanRequest->selection,panel.scanRequest->ftp->id}; const auto key=ftpPanelLocationKeys[index]; - if(location.ftpProfile.empty() || !ftpPanelPath(location.directory)) + if(location.ftpProfile.empty() || !isFtpFolderPath(location.directory)) { RegDeleteKeyValueW(HKEY_CURRENT_USER,schemeKey,key); return; diff --git a/src/files_path_navigation.inl b/src/files_path_navigation.inl index 97273bb..525a097 100644 --- a/src/files_path_navigation.inl +++ b/src/files_path_navigation.inl @@ -1,22 +1,28 @@ -bool localNavigationAvailable(const Panel &panel) +bool pathNavigationAvailable(const Panel &panel) { - return !panel.peer && !panel.ftp && !panel.findOrigin && !panel.archive && !panel.directory.empty(); + return !ftpProfileList(panel) && !panel.findOrigin && !panel.archive && !panel.directory.empty(); } -enum class PathAction { back, forward, up, edit, ancestors, previous, folder }; +enum class PathAction { back, forward, up, edit, source, ancestors, previous, folder }; -void navigateLocal(Panel &panel,const fs::path &path,std::optional position={}) +void navigatePanelPath(Panel &panel,const fs::path &path) { - if(path.empty() || sameLocalFolder(path,panel.directory)) return; + if(path.empty()) return; + const auto current=folderLocation(panel,panel.directory); + auto target=folderLocation(panel,path); + if(sameFolderLocation(current,target)) return; closePanelSearch(); - openOn(panel,path,true,{},{},{},{},position); + openFolderLocation(panel,target); } -void navigateLocalHistory(Panel &panel,int direction) +void navigatePanelHistory(Panel &panel,int direction) { if(const auto next=panel.navigation.neighbor(direction)) - navigateLocal(panel,panel.navigation.history[*next],next); + { + closePanelSearch(); + openFolderLocation(panel,panel.navigation.history[*next],next); + } } struct PathPart @@ -29,17 +35,18 @@ struct PathPart bool current{}, dim{}, enabled=true; }; -std::wstring pathSegmentLabel(const fs::path &path) +std::wstring pathSegmentLabel(const fs::path &path,FolderProvider provider) { - return panelParentPath(path,true).empty()?path.native():path.filename().native(); + if(provider==FolderProvider::ftp && path==ftpRoot) return L"/"; + return panelParentPath(path,provider==FolderProvider::local).empty()?path.native():path.filename().native(); } -LONG segmentWidth(const fs::path &path) +LONG segmentWidth(const fs::path &path,FolderProvider provider) { - return static_cast(pathSegmentLabel(path).size()+2)*cellWidth; + return static_cast(pathSegmentLabel(path,provider).size()+2)*cellWidth; } -std::vector localPathParts(const Panel &panel,RECT bounds) +std::vector panelPathParts(const Panel &panel,RECT bounds) { const LONG total=bounds.right-bounds.left; if(total<=0) return {}; @@ -52,64 +59,74 @@ std::vector localPathParts(const Panel &panel,RECT bounds) bounds.left=part.rect.right; parts.push_back(std::move(part)); }; - const auto parent=panelParentPath(panel.directory,true); + const auto location=folderLocation(panel,panel.directory); + const auto provider=location.provider; + const auto local=provider==FolderProvider::local; + const auto parent=panelParentPath(panel.directory,local); add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width); add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width); add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width); add({.action=PathAction::edit,.label=L"✎"},width); - std::vector ancestors, previous; - for(auto path=parent;!path.empty();path=panelParentPath(path,true)) ancestors.push_back(path); - std::reverse(ancestors.begin(),ancestors.end()); - if(inLocalBranch(panel.directory,panel.navigation.previousBranch)) + if(!local) { - for(auto path=panel.navigation.previousBranch;!sameLocalFolder(path,panel.directory); - path=panelParentPath(path,true)) + const auto available=std::max(1L,(bounds.right-bounds.left)/2); + const auto sourceWidth=std::min(available,static_cast(location.label.size()+2)*cellWidth); + add({.action=PathAction::source,.label=location.label},sourceWidth); + } + + std::vector ancestors, previous; + for(auto path=parent;!path.empty();path=panelParentPath(path,local)) ancestors.push_back(path); + std::reverse(ancestors.begin(),ancestors.end()); + if(inFolderBranch(panel.directory,panel.navigation.previousBranch,provider)) + { + for(auto path=panel.navigation.previousBranch;!sameFolderPath(path,panel.directory,provider); + path=panelParentPath(path,local)) previous.push_back(path); std::reverse(previous.begin(),previous.end()); } const LONG room=bounds.right-bounds.left; - LONG required=segmentWidth(panel.directory); - for(const auto &path:ancestors) required+=segmentWidth(path); - for(const auto &path:previous) required+=segmentWidth(path); + LONG required=segmentWidth(panel.directory,provider); + for(const auto &path:ancestors) required+=segmentWidth(path,provider); + for(const auto &path:previous) required+=segmentWidth(path,provider); size_t firstAncestor=0,visiblePrevious=previous.size(); - LONG currentWidth=segmentWidth(panel.directory); + LONG currentWidth=segmentWidth(panel.directory,provider); if(required>room) { const LONG reserved=(!ancestors.empty()?width:0)+(!previous.empty()?width:0); currentWidth=std::min(currentWidth,std::max(1L,room-reserved)); LONG remaining=room-currentWidth-reserved; firstAncestor=ancestors.size(); - while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1])) - remaining-=segmentWidth(ancestors[--firstAncestor]); + while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1],provider)) + remaining-=segmentWidth(ancestors[--firstAncestor],provider); visiblePrevious=0; - while(visiblePrevious=segmentWidth(previous[visiblePrevious])) - remaining-=segmentWidth(previous[visiblePrevious++]); + while(visiblePrevious=segmentWidth(previous[visiblePrevious],provider)) + remaining-=segmentWidth(previous[visiblePrevious++],provider); } if(firstAncestor) add({.action=PathAction::ancestors,.label=L"…", .hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width); for(size_t i=firstAncestor;i peer; + std::optional ftp; std::wstring completionInput; std::future completion; }; @@ -133,30 +152,62 @@ struct PathPrompt constexpr UINT addressComplete=WM_APP+29; constexpr UINT_PTR addressCompletionTimer=1; -fs::path enteredPanelPath(const fs::path &base,std::wstring text) +fs::path enteredPanelPath(const fs::path &base,std::wstring text,bool ftp) { if(text.size()>=2 && text.front()==L'"' && text.back()==L'"') text=text.substr(1,text.size()-2); - return fs::path(text).is_absolute()?fs::path(std::move(text)):base/fs::path(std::move(text)); + if(ftp && text.find_first_of(L":\r\n")!=text.npos) return {}; + auto path=fs::path(std::move(text)); + if(ftp) + { + if(path.has_root_name()) return {}; + return (path.has_root_directory()?path:base/path).lexically_normal(); + } + return path.is_absolute()?path:base/path; } -std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text) +std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text, + const std::optional &peer,const std::optional &ftp) { - const auto path=enteredPanelPath(base,text); + const auto path=enteredPanelPath(base,text,ftp.has_value()); + if(path.empty()) return {}; const auto directory=path.has_filename()?path.parent_path():path; const auto prefix=path.filename().native(); fs::path best; - std::error_code error; - for(fs::directory_iterator it(directory,error),end;!error && it!=end;it.increment(error)) + const auto accept=[&](const fs::path &candidate) { - const auto name=it->path().filename().native(); + const auto name=candidate.filename().native(); if(name.size()(prefix.size()),prefix.data(),static_cast(prefix.size()),TRUE)!=CSTR_EQUAL)) - continue; - std::error_code typeError; - if(it->is_directory(typeError) && (best.empty() || it->path()path(); + static_cast(prefix.size()),prefix.data(),static_cast(prefix.size()),ftp?FALSE:TRUE)!=CSTR_EQUAL)) + return; + if(best.empty() || candidateis_directory(typeError)) accept(it->path()); + } + } + if(best.empty()) return {}; + return ftp?ftpPath(best)+L"/":best.native()+L"\\"; } LRESULT CALLBACK addressFieldKeys(HWND field,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) @@ -194,7 +245,8 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) layoutDialogButtons(dialog,addressFooter,{IDOK,IDCANCEL}); const auto field=GetDlgItem(dialog,addressField); SendMessageW(field,EM_SETLIMITTEXT,32767,0); - SetWindowTextW(field,(prompt.base/fs::path{}).c_str()); + const auto initial=prompt.base/fs::path{}; + SetWindowTextW(field,(prompt.ftp?ftpPath(initial):initial.native()).c_str()); SetWindowSubclass(field,addressFieldKeys,4,0); SetFocus(field); SendMessageW(field,EM_SETSEL,0,-1); @@ -205,9 +257,10 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) auto &prompt=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); if(prompt.completion.valid()) return TRUE; prompt.completionInput=shortcutField(dialog,addressField); - std::packaged_task task([base=prompt.base,text=prompt.completionInput] + std::packaged_task task([base=prompt.base,text=prompt.completionInput, + peer=prompt.peer,ftp=prompt.ftp] { - return panelPathCompletion(base,text); + return panelPathCompletion(base,text,peer,ftp); }); if(!SetTimer(dialog,addressCompletionTimer,30,nullptr)) return TRUE; prompt.completion=task.get_future(); @@ -237,8 +290,8 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) if(message==WM_COMMAND && LOWORD(wp)==IDOK) { auto &prompt=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); - auto path=enteredPanelPath(prompt.base,shortcutField(dialog,addressField)).lexically_normal(); - if(!path.is_absolute()) + auto path=enteredPanelPath(prompt.base,shortcutField(dialog,addressField),prompt.ftp.has_value()).lexically_normal(); + if(prompt.ftp?!isFtpFolderPath(path):!path.is_absolute()) { showFilesNotice(dialog,L"Enter a folder path.",L"Go to folder"); return TRUE; @@ -258,25 +311,33 @@ INT_PTR CALLBACK editPathDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) void editPanelPath(Panel &panel) { - PathPrompt prompt{panel.directory}; + PathPrompt prompt{panel.directory,{},panel.peer,panel.ftp}; if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(117),GetParent(panel.list), editPathDialog,reinterpret_cast(&prompt))==IDOK) - navigateLocal(panel,prompt.result); + navigatePanelPath(panel,prompt.result); } -void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector paths,RECT anchor,bool recent=false) +void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector locations, + RECT anchor,bool recent=false) { hidePicker(); showMenu(false); commandPicker=false; pickerPanel=side; - folderPicker=FolderPicker{caption,std::move(paths),recent}; + folderPicker=FolderPicker{caption,std::move(locations),recent}; SendMessageW(picker,LB_RESETCONTENT,0,0); size_t longest=wcslen(caption); - for(const auto &path:folderPicker->paths) + for(const auto &location:folderPicker->locations) { - longest=std::max(longest,path.native().size()); - SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast(path.c_str())); + auto label=location.provider==FolderProvider::ftp?ftpPath(location.directory):location.directory.native(); + if(recent && location.provider!=FolderProvider::local) + { + const auto &source=location.label; + const auto kind=location.provider==FolderProvider::ftp?L"FTP":L"LAN"; + label=std::wstring(kind)+L" · "+(source.empty()?std::wstring{}:source+L" · ")+label; + } + longest=std::max(longest,label.size()); + SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast(label.c_str())); } RECT client{}; GetClientRect(owner,&client); @@ -289,7 +350,7 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector(&input),2); const int bottom=std::min(client.bottom,input.top); - const int shown=std::clamp((bottom-y-inset)/row,1,static_cast(folderPicker->paths.size())); + const int shown=std::clamp((bottom-y-inset)/row,1,static_cast(folderPicker->locations.size())); showFramedList(picker,pickerFrame,x,y,width,row*shown,inset); SendMessageW(picker,LB_SETCURSEL,0,0); SetFocus(picker); @@ -297,17 +358,23 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vector(&anchor),2); - showFolderPicker(owner,side,L"Recent folders",std::move(paths),anchor,true); + if(loadFtpProfiles()) + for(auto &location:locations) + { + if(location.provider!=FolderProvider::ftp) continue; + if(const auto *profile=findFtpProfile(location.id)) location.label=profile->name; + } + showFolderPicker(owner,side,L"Recent folders",std::move(locations),anchor,true); } void showHiddenPathParts(HWND window,int side,const PathPart &part) @@ -315,8 +382,11 @@ void showHiddenPathParts(HWND window,int side,const PathPart &part) const auto owner=GetParent(window); auto anchor=part.rect; MapWindowPoints(window,owner,reinterpret_cast(&anchor),2); + std::vector locations; + locations.reserve(part.hidden.size()); + for(const auto &path:part.hidden) locations.push_back(folderLocation(panels[side],path)); showFolderPicker(owner,side,part.action==PathAction::ancestors?L"Parent folders":L"Previous path", - part.hidden,anchor); + std::move(locations),anchor); } LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) @@ -333,7 +403,7 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_ if(index<0 || index>=2) return 0; panelClipboardContext=true; auto &panel=panels[index]; - if(!localNavigationAvailable(panel)) + if(!pathNavigationAvailable(panel)) { selectPanelEdge(panel,true); return 0; @@ -342,16 +412,24 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_ RECT bounds{}; GetClientRect(window,&bounds); const POINT mouse{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; - const auto parts=localPathParts(panel,bounds); + const auto parts=panelPathParts(panel,bounds); for(const auto &part:parts) { if(!part.enabled || !PtInRect(&part.rect,mouse)) continue; switch(part.action) { - case PathAction::back: navigateLocalHistory(panel,-1); break; - case PathAction::forward: navigateLocalHistory(panel,1); break; - case PathAction::up: case PathAction::folder: navigateLocal(panel,part.target); break; + case PathAction::back: navigatePanelHistory(panel,-1); break; + case PathAction::forward: navigatePanelHistory(panel,1); break; + case PathAction::up: case PathAction::folder: navigatePanelPath(panel,part.target); break; case PathAction::edit: editPanelPath(panel); break; + case PathAction::source: + if(panel.peer) chooseDrive(index,false,true); + else + { + const auto *profile=findFtpProfile(panel.ftp->id); + showFtpProfiles(panel,profile?ftpRoot/std::to_wstring(profile-ftpProfiles.data()):fs::path{}); + } + break; case PathAction::ancestors: case PathAction::previous: showHiddenPathParts(window,index,part); break; } break; @@ -361,7 +439,7 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_ return DefSubclassProc(window,message,wp,lp); } -bool handleLocalPathKey(HWND owner,const MSG &message) +bool handlePanelPathKey(HWND owner,const MSG &message) { if(!commandLineAvailable(owner) || terminalVisible || (message.hwnd!=terminalInput && message.hwnd!=panels[active].list) || @@ -374,7 +452,7 @@ bool handleLocalPathKey(HWND owner,const MSG &message) if(!(message.lParam&(1LL<<30))) parentArchive(panel); return true; } - if(!localNavigationAvailable(panel)) return false; + if(!pathNavigationAvailable(panel)) return false; if(message.message==WM_KEYDOWN && message.wParam=='L' && (GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000)) { @@ -384,9 +462,9 @@ bool handleLocalPathKey(HWND owner,const MSG &message) if(message.message!=WM_SYSKEYDOWN || !(message.lParam&(1LL<<29)) || (GetKeyState(VK_CONTROL)&0x8000)) return false; if(message.wParam==VK_UP) - navigateLocal(panel,panelParentPath(panel.directory,true)); + navigatePanelPath(panel,panelParentPath(panel.directory,!panel.peer && !panel.ftp)); else if(message.wParam==VK_LEFT || message.wParam==VK_RIGHT) - navigateLocalHistory(panel,message.wParam==VK_LEFT?-1:1); + navigatePanelHistory(panel,message.wParam==VK_LEFT?-1:1); else return false; return true; } diff --git a/src/files_recent_folders.inl b/src/files_recent_folders.inl index 40b88fd..f6bef21 100644 --- a/src/files_recent_folders.inl +++ b/src/files_recent_folders.inl @@ -1,24 +1,53 @@ constexpr wchar_t recentFoldersKey[]=L"RecentFolders"; constexpr size_t recentFoldersLimit=100; -std::vector readRecentFolders() +std::optional readRecentFolder(const Json &entry) +{ + FolderLocation location; + if(entry.is_string()) location.directory=filePath(entry); + else if(entry.is_object()) + { + const auto source=entry.value("source",std::string{}); + if(source=="ftp") location.provider=FolderProvider::ftp; + else if(source=="lan") location.provider=FolderProvider::lan; + else return {}; + location.id=entry.at("id").get(); + if(location.id.empty()) return {}; + location.label=ks::wide(entry.value("label",std::string{})); + location.directory=filePath(entry.at("path")); + } + else return {}; + const auto &path=location.directory; + if(path.native().find(L'\0')!=std::wstring::npos) return {}; + if(location.provider==FolderProvider::ftp) + { + if(!isFtpFolderPath(path)) return {}; + } + else if(!path.is_absolute()) return {}; + return location; +} + +std::vector readRecentFolders() { const auto saved=readFilesJsonPreference(recentFoldersKey); - std::vector folders; + std::vector folders; if(!saved || !saved->is_array()) return folders; for(const auto &entry:*saved) { - if(!entry.is_string()) continue; - const auto path=filePath(entry); - if(!path.is_absolute() || path.native().find(L'\0')!=std::wstring::npos) continue; - if(std::none_of(folders.begin(),folders.end(),[&](const auto &known){return sameLocalFolder(path,known);})) - folders.push_back(path); + try + { + auto location=readRecentFolder(entry); + if(location && std::none_of(folders.begin(),folders.end(), + [&](const auto &known){return sameFolderLocation(*location,known);})) + folders.push_back(std::move(*location)); + } + catch(const std::exception &) {} if(folders.size()==recentFoldersLimit) break; } return folders; } -bool updateRecentFolders(const fs::path &path,bool remember) +bool updateRecentFolders(const FolderLocation &location,bool remember) { const Handle lock{CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.RecentFolders")}; if(!lock.value) return false; @@ -28,11 +57,17 @@ bool updateRecentFolders(const fs::path &path,bool remember) try { auto folders=readRecentFolders(); - std::erase_if(folders,[&](const auto &known){return sameLocalFolder(path,known);}); - if(remember) folders.insert(folders.begin(),path); + std::erase_if(folders,[&](const auto &known){return sameFolderLocation(location,known);}); + if(remember) folders.insert(folders.begin(),location); if(folders.size()>recentFoldersLimit) folders.resize(recentFoldersLimit); auto data=Json::array(); - for(const auto &folder:folders) data.push_back(ks::utf8(folder.native())); + for(const auto &folder:folders) + { + const auto path=ks::utf8(folder.directory.native()); + if(folder.provider==FolderProvider::local) data.push_back(path); + else data.push_back({{"source",folder.provider==FolderProvider::ftp?"ftp":"lan"},{"id",folder.id}, + {"label",ks::utf8(folder.label)},{"path",path}}); + } saved=writeFilesJsonPreference(recentFoldersKey,data); } catch(const std::exception &) {} diff --git a/tests/files_comparison_splitter.ps1 b/tests/files_comparison_splitter.ps1 index bfc2424..95b8180 100644 --- a/tests/files_comparison_splitter.ps1 +++ b/tests/files_comparison_splitter.ps1 @@ -82,7 +82,8 @@ try { $destination = [int]($bounds.Right * 0.65) $mouseY = 30 -shl 16 [void][FilesCommandsUi]::Send($list, 513, [IntPtr]1, [IntPtr]($mouseY -bor $middle)) - for ($x = $middle + 5; $x -lt $destination; $x += 5) { + for ($step = 1; $step -lt 8; ++$step) { + $x = $middle + [int](($destination - $middle) * $step / 8) [void][FilesCommandsUi]::Send($list, 512, [IntPtr]1, [IntPtr]($mouseY -bor $x)) [void][FilesCommandsUi]::RedrawWindow($list, [IntPtr]::Zero, [IntPtr]::Zero, 0x101) } From c735c216826ca117be09c3bf44b5ee69c5df553e Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 17:53:30 +0200 Subject: [PATCH 25/61] Add saved SMB connection profiles and share browsing Refs #109 --- CMakeLists.txt | 7 +- FILES-UI.md | 17 +- resources/files.rc | 47 +++ src/files_folder_shortcuts.inl | 7 + src/files_ftp_dialog.inl | 11 +- src/files_main.cpp | 25 +- src/files_smb.inl | 633 ++++++++++++++++++++++++++++++++ tests/files_drive_shortcuts.ps1 | 32 +- tests/files_smb_password.ps1 | 111 ++++++ 9 files changed, 867 insertions(+), 23 deletions(-) create mode 100644 src/files_smb.inl create mode 100644 tests/files_smb_password.ps1 diff --git a/CMakeLists.txt b/CMakeLists.txt index ddf59cf..a3502da 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,7 +34,7 @@ add_custom_target(check-files-quick-view DEPENDS KSwitcherFiles VERBATIM) target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include") -target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet KSwitcherFilesImage) +target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr KSwitcherFilesImage) if(MSVC) target_compile_options(KSwitcherFiles PRIVATE /utf-8) else() @@ -222,6 +222,11 @@ add_test(NAME files-comparison-splitter -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_comparison_splitter.ps1" -Executable "$") set_tests_properties(files-comparison-splitter PROPERTIES RUN_SERIAL TRUE TIMEOUT 35) +add_test(NAME files-smb-password + COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass + -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_smb_password.ps1" + -Executable "$") +set_tests_properties(files-smb-password PROPERTIES RUN_SERIAL TRUE TIMEOUT 30) add_test(NAME files-space-analyzer-layout COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_layout.ps1" diff --git a/FILES-UI.md b/FILES-UI.md index 63a2da9..e7b3ead 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -64,6 +64,21 @@ Warning і початковий фокус на No. підтвердження й видаляє вибрані елементи з FTP-сервера без кошика. Для непорожньої папки Files окремо підтверджує видалення її вмісту. +- **SMB** у меню джерел обох панелей відкриває збережені підключення. + **New** додає назву й сервер або повний UNC-шлях. **Open** для сервера + показує видимі дискові шари. Відомий прихований шар можна додати як + повний UNC-шлях. Вибір шару або відкриття профілю з UNC-папкою переходить + до цієї папки в панелі, з якої викликали меню. +- Для SMB діють дозволи Windows. **Sign in** використовує вказаний + обліковий запис. Прапорець **Remember in Windows Credential Manager** + типово вимкнений. Коли його ввімкнено, після успішного підключення Windows + зберігає облікові дані для цього профілю. **Remove** видаляє профіль і + його збережені облікові дані після підтвердження. +- Якщо SMB недоступний, повідомлення показує причину й залишає список + підключень відкритим. **Open** повторює спробу. Коли Windows повідомляє + про наявний сеанс до цього сервера з іншим записом, Files пропонує + вибрати той запис або завершити попередній сеанс у Windows. + - **F9 → Commands → Compare files** порівнює два позначені текстові файли активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає позначок, береться файл під курсором. Підтримуються локальні, LAN- та @@ -109,7 +124,7 @@ Warning і початковий фокус на No. - У меню Files і його списках, що випадають, стрілки вгору й вниз переходять між першим і останнім пунктами циклічно та оминають розділювачі. У меню джерел горизонтальна лінія відділяє FTP від локальних дисків, - а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP. + а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP і SMB. Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається до закриття меню, навіть коли оновлюється список LAN. diff --git a/resources/files.rc b/resources/files.rc index da18279..3c34e3e 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -512,3 +512,50 @@ BEGIN CONTROL "&Create", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 63, 59, 80, 17 CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17 END + +121 DIALOGEX 0, 0, 430, 192 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "SMB connections" +FONT 10, "Consolas" +BEGIN + LTEXT "", 540, 16, 16, 398, 12, SS_ENDELLIPSIS | SS_NOPREFIX + CONTROL "", 541, "ListBox", LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP, 16, 31, 398, 103 + LTEXT "", 542, 16, 140, 398, 13, SS_ENDELLIPSIS | SS_NOPREFIX + LTEXT "", 543, 10, 159, 1, 1, NOT WS_VISIBLE + CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 19, 166, 56, 17 + CONTROL "&New", 544, "Button", BS_OWNERDRAW | WS_TABSTOP, 82, 166, 56, 17 + CONTROL "&Edit", 545, "Button", BS_OWNERDRAW | WS_TABSTOP, 145, 166, 56, 17 + CONTROL "Re&move", 546, "Button", BS_OWNERDRAW | WS_TABSTOP, 208, 166, 56, 17 + CONTROL "&Sign in", 547, "Button", BS_OWNERDRAW | WS_TABSTOP, 271, 166, 60, 17 + CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 338, 166, 56, 17 +END + +122 DIALOGEX 0, 0, 355, 113 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "SMB connection" +FONT 10, "Consolas" +BEGIN + LTEXT "Connection &name", 550, 16, 15, 323, 12 + FAR_EDIT(551, 0, 16, 29, 323, 15) + LTEXT "&Server or UNC folder", 552, 16, 52, 323, 12 + FAR_EDIT(553, 0, 16, 66, 323, 15) + LTEXT "", 554, 10, 87, 1, 1, NOT WS_VISIBLE + CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 93, 80, 17 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 93, 80, 17 +END + +123 DIALOGEX 0, 0, 355, 153 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "SMB sign in" +FONT 10, "Consolas" +BEGIN + LTEXT "", 555, 16, 15, 323, 12, SS_ENDELLIPSIS | SS_NOPREFIX + LTEXT "&User name", 556, 16, 32, 323, 12 + FAR_EDIT(557, 0, 16, 46, 323, 15) + LTEXT "&Password", 558, 16, 69, 323, 12 + EDITTEXT 559, 16, 83, 323, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL + AUTOCHECKBOX "&Remember in Windows Credential Manager", 560, 16, 106, 323, 13 + LTEXT "", 561, 10, 125, 1, 1, NOT WS_VISIBLE + CONTROL "&Connect", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 132, 80, 17 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 132, 80, 17 +END diff --git a/src/files_folder_shortcuts.inl b/src/files_folder_shortcuts.inl index c67ca9b..d299bbb 100644 --- a/src/files_folder_shortcuts.inl +++ b/src/files_folder_shortcuts.inl @@ -65,6 +65,13 @@ struct FolderShortcutEdit std::optional index; }; +std::wstring trimFilesField(std::wstring value) +{ + const auto first=value.find_first_not_of(L" \t\r\n"); + if(first==value.npos) return {}; + return value.substr(first,value.find_last_not_of(L" \t\r\n")-first+1); +} + std::wstring shortcutField(HWND dialog,int id) { const auto field=GetDlgItem(dialog,id); diff --git a/src/files_ftp_dialog.inl b/src/files_ftp_dialog.inl index e1b982c..8e1e32c 100644 --- a/src/files_ftp_dialog.inl +++ b/src/files_ftp_dialog.inl @@ -2,13 +2,6 @@ namespace ftpDialog { constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392; -std::wstring trim(std::wstring value) -{ - const auto first=value.find_first_not_of(L" \t\r\n"); - if(first==value.npos) return {}; - return value.substr(first,value.find_last_not_of(L" \t\r\n")-first+1); -} - struct Edit { FtpProfile profile; @@ -64,13 +57,13 @@ INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp) }; FtpProfile profile; profile.legacyNames=IsDlgButtonChecked(dialog,legacy)==BST_CHECKED; - profile.name=trim(shortcutField(dialog,name)); + profile.name=trimFilesField(shortcutField(dialog,name)); if(profile.name.empty() || profile.name==L".." || profile.name.find_first_of(L"\r\n\t")!=profile.name.npos) return invalid(name,L"Enter a name for this connection."); for(size_t i=0;i #include #include +#include +#include +#include #include "files_terminal.h" #include "files_archive.h" #include "files_compare_text.h" @@ -3589,9 +3592,17 @@ void runActivePeerAction(HWND owner,bool update) } LRESULT ftpDriveRow() {return lanDrivePicker?-1:static_cast(drivePaths.size())+1;} -LRESULT recentDriveRow() {return lanDrivePicker?-1:ftpDriveRow()+1;} +LRESULT smbDriveRow() {return lanDrivePicker?-1:ftpDriveRow()+1;} +LRESULT recentDriveRow() {return lanDrivePicker?-1:smbDriveRow()+1;} LRESULT lanHeaderRow() {return recentDriveRow()+1;} void showRecentFolders(int side); +void showSmbProfiles(Panel &panel); + +bool driveSourceRow(LRESULT row) +{ + return row>=0 && (row(drivePaths.size()) || row==ftpDriveRow() || + row==smbDriveRow() || row==recentDriveRow()); +} bool selectablePickerRow(LRESULT row) { @@ -3599,8 +3610,7 @@ bool selectablePickerRow(LRESULT row) if(folderPicker) return static_cast(row)locations.size(); if(commandPicker) return static_cast(row)=0; - return row(drivePaths.size()) || row==ftpDriveRow() || row==recentDriveRow() || - remoteDriveRows.contains(row); + return driveSourceRow(row) || remoteDriveRows.contains(row); } void selectDrive() @@ -3659,6 +3669,11 @@ void selectDrive() } else setStatus(L"Cannot load saved FTP connections."); } + else if(row==smbDriveRow()) + { + activatePanel(pickerPanel); + showSmbProfiles(panels[pickerPanel]); + } else if(row==recentDriveRow()) showRecentFolders(pickerPanel); else if(remote!=remoteDriveRows.end()) { @@ -3785,7 +3800,7 @@ LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PT if(!HIWORD(hit)) { const auto choice=remoteDriveRows.find(LOWORD(hit)); - if(LOWORD(hit)second.path && driveWakeAction.hit(window,LOWORD(hit),lp,cellWidth))) row=LOWORD(hit); @@ -3932,6 +3947,7 @@ void showRemoteDrives(bool focus=false,int initialRow=0) { add(L""); add(L"FTP"); + add(L"SMB"); add(L"Recent folders"); } add(L"KSwitcher LAN"); @@ -7851,6 +7867,7 @@ void submitTerminalReturn(HWND owner,bool shift) handleFilesReturn(shift); } +#include "files_smb.inl" #include "files_path_navigation.inl" LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) diff --git a/src/files_smb.inl b/src/files_smb.inl new file mode 100644 index 0000000..34d747e --- /dev/null +++ b/src/files_smb.inl @@ -0,0 +1,633 @@ +namespace smb +{ +constexpr wchar_t profilesKey[]=L"SmbProfiles"; +constexpr DWORD shareTypeMask=0xff; +constexpr int summary=540,list=541,status=542,footer=543,newProfile=544,editProfile=545,removeProfile=546,signIn=547; +constexpr int nameLabel=550,nameField=551,addressLabel=552,addressField=553,editFooter=554; +constexpr int loginLabel=555,userLabel=556,userField=557,passwordLabel=558,passwordField=559,rememberField=560,loginFooter=561; + +struct Target +{ + std::wstring server; + fs::path share,folder; +}; + +std::optional parseTarget(std::wstring address) +{ + address=trimFilesField(std::move(address)); + std::replace(address.begin(),address.end(),L'/',L'\\'); + if(address.starts_with(L"\\\\")) address.erase(0,2); + while(address.ends_with(L"\\")) address.pop_back(); + if(address.empty() || address.size()>=MAX_PATH-2) return {}; + const auto separator=address.find(L'\\'); + const auto host=address.substr(0,separator); + if(host.empty() || host==L"." || host==L".." || host.find_first_of(L" \t\r\n@<>:\"|?*")!=host.npos || + std::any_of(host.begin(),host.end(),[](auto c){return c:\"|?*")!=relative.npos || + std::any_of(relative.begin(),relative.end(),[](auto c){return cnative()); + target.folder=fs::path(target.server+L"\\"+relative); + return target; +} + +struct Profile +{ + std::string id; + std::wstring name; + Target target; +}; + +std::wstring profileAddress(const Profile &profile) +{ + return profile.target.folder.empty()?profile.target.server:profile.target.folder.native(); +} + +std::vector readProfiles() +{ + std::vector profiles; + const auto saved=readFilesJsonPreference(profilesKey); + if(!saved || !saved->is_array()) return profiles; + for(const auto &row:*saved) + { + try + { + const auto id=row.at("id").get(); + auto name=ks::wide(row.at("name")); + auto target=parseTarget(ks::wide(row.at("path"))); + if(ks::lan::identifier(id) && !name.empty() && target && + std::none_of(profiles.begin(),profiles.end(),[&](const auto &entry){return entry.id==id;})) + profiles.push_back({id,std::move(name),std::move(*target)}); + } + catch(const std::exception &) {} + } + return profiles; +} + +struct ProfilesLock +{ + Handle handle{CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.SmbProfiles")}; + bool locked{}; + ProfilesLock() + { + if(!handle.value) return; + const auto wait=WaitForSingleObject(handle.value,100); + locked=wait==WAIT_OBJECT_0 || wait==WAIT_ABANDONED; + } + ~ProfilesLock() {if(locked) ReleaseMutex(handle.value);} +}; + +bool sameServer(const Profile &a,const Profile &b) +{ + return CompareStringOrdinal(a.target.server.c_str(),-1,b.target.server.c_str(),-1,TRUE)==CSTR_EQUAL; +} + +template +std::optional> updateProfiles(Change change) +{ + const ProfilesLock lock; + if(!lock.locked) return {}; + std::optional> result; + try + { + auto profiles=readProfiles(); + if(change(profiles)) + { + auto data=Json::array(); + for(const auto &entry:profiles) + data.push_back({{"id",entry.id},{"name",ks::utf8(entry.name)},{"path",ks::utf8(profileAddress(entry))}}); + if(writeFilesJsonPreference(profilesKey,data)) result=std::move(profiles); + } + } + catch(const std::exception &) {} + return result; +} + +std::wstring credentialTarget(const Profile &profile) +{ + auto host=profile.target.server.substr(2); + for(auto &letter:host) + if(letter>=L'A' && letter<=L'Z') letter+=L'a'-L'A'; + return L"KSwitcher.Files/SMB/"+ks::wide(profile.id)+L"/"+host; +} + +DWORD deleteCredential(const Profile &profile) +{ + if(CredDeleteW(credentialTarget(profile).c_str(),CRED_TYPE_GENERIC,0)) return ERROR_SUCCESS; + const auto error=GetLastError(); + return error==ERROR_NOT_FOUND?ERROR_SUCCESS:error; +} + +struct Credentials +{ + std::wstring user; + std::vector password; + bool remember{}; + Credentials()=default; + Credentials(const Credentials &)=delete; + Credentials &operator=(const Credentials &)=delete; + ~Credentials() + { + if(!password.empty()) SecureZeroMemory(password.data(),password.size()*sizeof(wchar_t)); + } +}; + +DWORD loadCredential(const Profile &profile,Credentials &login) +{ + struct Allocation + { + PCREDENTIALW data{}; + ~Allocation() + { + if(!data) return; + if(data->CredentialBlobSize) SecureZeroMemory(data->CredentialBlob,data->CredentialBlobSize); + CredFree(data); + } + } response; + if(!CredReadW(credentialTarget(profile).c_str(),CRED_TYPE_GENERIC,0,&response.data)) + { + const auto error=GetLastError(); + return error==ERROR_NOT_FOUND?ERROR_SUCCESS:error; + } + const auto &credential=*response.data; + if(!credential.UserName || !*credential.UserName || credential.CredentialBlobSize%sizeof(wchar_t)) + return ERROR_INVALID_DATA; + login.user=credential.UserName; + login.password.resize(credential.CredentialBlobSize/sizeof(wchar_t)+1); + if(credential.CredentialBlobSize) + std::memcpy(login.password.data(),credential.CredentialBlob,credential.CredentialBlobSize); + return ERROR_SUCCESS; +} + +DWORD saveCredential(const Profile &profile,const Credentials &login) +{ + const ProfilesLock lock; + if(!lock.locked) return ERROR_BUSY; + const auto profiles=readProfiles(); + if(std::none_of(profiles.begin(),profiles.end(),[&](const auto &entry) { + return entry.id==profile.id && sameServer(profile,entry); + })) return ERROR_NOT_FOUND; + auto target=credentialTarget(profile); + CREDENTIALW credential{}; + credential.Type=CRED_TYPE_GENERIC; + credential.TargetName=target.data(); + credential.Persist=CRED_PERSIST_LOCAL_MACHINE; + credential.UserName=const_cast(login.user.c_str()); + credential.CredentialBlobSize=static_cast((login.password.size()-1)*sizeof(wchar_t)); + credential.CredentialBlob=reinterpret_cast(const_cast(login.password.data())); + return CredWriteW(&credential,0)?ERROR_SUCCESS:GetLastError(); +} + +std::wstring errorText(DWORD error) +{ + if(error==ERROR_SESSION_CREDENTIAL_CONFLICT) + return L"Windows already has a session to this server with another account. Use that account or disconnect that session in Windows before trying again."; + return fileError(std::system_error(error,std::system_category())); +} + +struct Connection +{ + fs::path folder; + std::vector shares; + DWORD error{},credentialError{}; +}; + +Connection connect(const Profile &profile,const Credentials *explicitLogin,const std::atomic_bool &canceled) +{ + Connection result; + Credentials stored; + auto login=explicitLogin; + if(!login) + { + result.error=loadCredential(profile,stored); + if(result.error) return result; + if(!stored.user.empty()) login=&stored; + } + if(login && !canceled) + { + auto resource=profile.target.share.empty()?profile.target.server+L"\\IPC$":profile.target.share.native(); + NETRESOURCEW endpoint{}; + endpoint.dwType=profile.target.share.empty()?RESOURCETYPE_ANY:RESOURCETYPE_DISK; + endpoint.lpRemoteName=resource.data(); + result.error=WNetAddConnection2W(&endpoint,login->password.data(),login->user.c_str(),CONNECT_TEMPORARY); + if(result.error) return result; + } + if(canceled) return result; + if(!profile.target.folder.empty()) + { + WIN32_FIND_DATAW first{}; + const auto listing=FindFirstFileW((profile.target.folder/L"*").c_str(),&first); + if(listing!=INVALID_HANDLE_VALUE) FindClose(listing); + else + { + const auto error=GetLastError(); + if(error!=ERROR_FILE_NOT_FOUND && error!=ERROR_NO_MORE_FILES) result.error=error; + } + if(!result.error) result.folder=profile.target.folder; + } + else + { + auto server=profile.target.server; + DWORD resume{}; + do + { + struct Buffer { BYTE *data{}; ~Buffer(){if(data) NetApiBufferFree(data);} } buffer; + DWORD read{},total{}; + const auto previous=resume; + result.error=NetShareEnum(server.data(),1,&buffer.data,MAX_PREFERRED_LENGTH,&read,&total,&resume); + if(result.error!=NERR_Success && result.error!=ERROR_MORE_DATA) return result; + const auto rows=reinterpret_cast(buffer.data); + for(DWORD i=0;iremember) + result.credentialError=saveCredential(profile,*explicitLogin); + return result; +} + +bool closeRequest(UINT message,WPARAM command) +{ + return message==WM_CLOSE || (message==WM_COMMAND && LOWORD(command)==IDCANCEL); +} + +struct EditProfile +{ + Profile profile; + std::optional> saved; +}; + +INT_PTR CALLBACK editDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" SMB connection ",false,{editFooter})) + return painted; + if(message==WM_INITDIALOG) + { + SetWindowLongPtrW(dialog,DWLP_USER,lp); + const auto &edit=*reinterpret_cast(lp); + prepareCopyDialog(dialog); + layoutDialogContent(dialog,nameLabel); + for(const auto id:{nameLabel,addressLabel}) + SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast(mono),FALSE); + SendDlgItemMessageW(dialog,nameField,EM_SETLIMITTEXT,255,0); + SendDlgItemMessageW(dialog,addressField,EM_SETLIMITTEXT,MAX_PATH-1,0); + SetDlgItemTextW(dialog,nameField,edit.profile.name.c_str()); + SetDlgItemTextW(dialog,addressField,profileAddress(edit.profile).c_str()); + layoutDialogButtons(dialog,editFooter,{IDOK,IDCANCEL}); + return TRUE; + } + if(closeRequest(message,wp)) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE; + auto &edit=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + auto name=trimFilesField(shortcutField(dialog,nameField)); + auto target=parseTarget(shortcutField(dialog,addressField)); + const bool validName=!name.empty() && name.find_first_of(L"\r\n\t")==name.npos; + if(!validName || !target) + { + showFilesNotice(dialog,!validName?L"Enter a connection name on one line.": + L"Enter a server name or a UNC folder such as \\\\server\\share.",L"SMB connection"); + SetFocus(GetDlgItem(dialog,validName?addressField:nameField)); + return TRUE; + } + const bool creating=edit.profile.id.empty(); + Profile next{creating?ks::lan::randomHex(16):edit.profile.id,std::move(name),std::move(*target)}; + DWORD error=ERROR_SUCCESS; + edit.saved=updateProfiles([&](auto &profiles) { + const auto previous=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry){return entry.id==next.id;}); + if(std::any_of(profiles.begin(),profiles.end(),[&](const auto &entry) { + return entry.id!=next.id && CompareStringOrdinal(entry.name.c_str(),-1,next.name.c_str(),-1,TRUE)==CSTR_EQUAL; + })) + { + error=ERROR_ALREADY_EXISTS; + return false; + } + if(creating) profiles.push_back(next); + else + { + if(previous==profiles.end()) {error=ERROR_NOT_FOUND;return false;} + if(!sameServer(*previous,next) && (error=deleteCredential(*previous))) return false; + *previous=next; + } + return true; + }); + if(!edit.saved) + { + const auto detail=error==ERROR_ALREADY_EXISTS?L"A connection with this name already exists.": + error?errorText(error):L"Could not save the SMB connection."; + showFilesNotice(dialog,detail.c_str(),L"SMB connection"); + return TRUE; + } + edit.profile=std::move(next); + FilesModalDialog::finish(dialog,IDOK); + return TRUE; +} + +struct LoginPrompt +{ + const Profile &profile; + Credentials &login; +}; + +INT_PTR CALLBACK loginDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" SMB sign in ",false,{loginFooter})) + return painted; + if(message==WM_INITDIALOG) + { + SetWindowLongPtrW(dialog,DWLP_USER,lp); + const auto &prompt=*reinterpret_cast(lp); + prepareCopyDialog(dialog); + layoutDialogContent(dialog,loginLabel); + for(const auto id:{loginLabel,userLabel,passwordLabel,rememberField}) + SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast(mono),FALSE); + SetDlgItemTextW(dialog,loginLabel,(L"Server "+prompt.profile.target.server).c_str()); + SendDlgItemMessageW(dialog,userField,EM_SETLIMITTEXT,256,0); + SendDlgItemMessageW(dialog,passwordField,EM_SETLIMITTEXT,CRED_MAX_CREDENTIAL_BLOB_SIZE/sizeof(wchar_t),0); + installFarCheckbox(GetDlgItem(dialog,rememberField),FarCheckboxSurface::gray); + layoutDialogButtons(dialog,loginFooter,{IDOK,IDCANCEL}); + return TRUE; + } + const auto clearPassword=[&] + { + SetDlgItemTextW(dialog,passwordField,L""); + SendDlgItemMessageW(dialog,passwordField,EM_EMPTYUNDOBUFFER,0,0); + }; + if(closeRequest(message,wp)) + { + clearPassword(); + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE; + auto &login=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER))->login; + auto user=trimFilesField(shortcutField(dialog,userField)); + if(user.empty()) + { + showFilesNotice(dialog,L"Enter the SMB account name.",L"SMB sign in"); + SetFocus(GetDlgItem(dialog,userField)); + return TRUE; + } + login.user=std::move(user); + const auto field=GetDlgItem(dialog,passwordField); + const auto length=GetWindowTextLengthW(field); + login.password.resize(static_cast(length)+1); + GetWindowTextW(field,login.password.data(),length+1); + login.remember=IsDlgButtonChecked(dialog,rememberField)==BST_CHECKED; + clearPassword(); + FilesModalDialog::finish(dialog,IDOK); + return TRUE; +} + +struct Browser +{ + std::vector profiles; + std::optional server; + std::vector shares; + fs::path chosen; + std::atomic_bool canceled{}; + bool busy{}; +}; + +void browserControls(HWND dialog,const Browser &browser) +{ + const auto selected=SendDlgItemMessageW(dialog,list,LB_GETCURSEL,0,0)!=LB_ERR; + EnableWindow(GetDlgItem(dialog,list),!browser.busy); + EnableWindow(GetDlgItem(dialog,IDOK),!browser.busy && selected); + EnableWindow(GetDlgItem(dialog,newProfile),!browser.busy); + for(const auto button:{editProfile,removeProfile,signIn}) + EnableWindow(GetDlgItem(dialog,button),!browser.busy && selected && !browser.server); +} + +void showRows(HWND dialog,const Browser &browser,LRESULT selection=0) +{ + const auto rows=GetDlgItem(dialog,list); + SendMessageW(rows,LB_RESETCONTENT,0,0); + const auto add=[&](const std::wstring &label){SendMessageW(rows,LB_ADDSTRING,0,reinterpret_cast(label.c_str()));}; + if(browser.server) + { + for(const auto &share:browser.shares) add(share); + SetDlgItemTextW(dialog,summary,(L"Shared folders on "+browser.server->target.server).c_str()); + SetDlgItemTextW(dialog,status,browser.shares.empty()?L"No visible disk shares. A known UNC share can be saved as a profile.":L""); + SetDlgItemTextW(dialog,newProfile,L"&Back"); + for(const auto button:{editProfile,removeProfile,signIn}) ShowWindow(GetDlgItem(dialog,button),SW_HIDE); + layoutDialogButtons(dialog,footer,{IDOK,newProfile,IDCANCEL}); + } + else + { + for(const auto &entry:browser.profiles) add(entry.name+L" · "+profileAddress(entry)); + SetDlgItemTextW(dialog,summary,L"Saved SMB connections"); + SetDlgItemTextW(dialog,status,browser.profiles.empty()?L"Choose New to add a server or UNC folder.":L""); + SetDlgItemTextW(dialog,newProfile,L"&New"); + for(const auto button:{editProfile,removeProfile,signIn}) ShowWindow(GetDlgItem(dialog,button),SW_SHOWNA); + layoutDialogButtons(dialog,footer,{IDOK,newProfile,editProfile,removeProfile,signIn,IDCANCEL}); + } + const auto count=SendMessageW(rows,LB_GETCOUNT,0,0); + if(count>0) SendMessageW(rows,LB_SETCURSEL,std::clamp(selection,0,count-1),0); + browserControls(dialog,browser); + SetFocus(count>0?rows:GetDlgItem(dialog,newProfile)); +} + +void openProfile(HWND dialog,Browser &browser,const Profile &profile,bool withLogin) +{ + Credentials login; + if(withLogin) + { + LoginPrompt prompt{profile,login}; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(123),dialog,loginDialog, + reinterpret_cast(&prompt))!=IDOK) return; + } + browser.busy=true; + browser.canceled=false; + browserControls(dialog,browser); + SetFocus(GetDlgItem(dialog,IDCANCEL)); + SetDlgItemTextW(dialog,status,(L"Connecting to "+profile.target.server+L"…").c_str()); + Connection result; + try + { + FileOperationUi worker; + worker.run(dialog,browser.canceled,[&]{result=connect(profile,withLogin?&login:nullptr,browser.canceled);}); + } + catch(const std::exception &) + { + result.error=ERROR_GEN_FAILURE; + } + browser.busy=false; + browserControls(dialog,browser); + if(browser.canceled) + { + SetDlgItemTextW(dialog,status,L"Connection canceled."); + SetFocus(GetDlgItem(dialog,list)); + return; + } + if(result.error) + { + auto detail=profileAddress(profile)+L"\r\n\r\n"+errorText(result.error); + if(result.error==ERROR_ACCESS_DENIED || result.error==ERROR_LOGON_FAILURE || + result.error==ERROR_INVALID_PASSWORD || result.error==ERROR_BAD_USERNAME) + detail+=L"\r\n\r\nUse Sign in to try a different account."; + showFilesNotice(dialog,detail.c_str(),L"Could not open SMB connection",{.tone=FilesNoticeTone::warning}); + SetDlgItemTextW(dialog,status,L"Connection failed. Open to retry or choose Sign in."); + SetFocus(GetDlgItem(dialog,list)); + return; + } + if(result.credentialError) + { + const auto detail=L"Connected, but Windows Credential Manager did not save the account.\r\n\r\n"+ + errorText(result.credentialError); + showFilesNotice(dialog,detail.c_str(),L"SMB sign in",{.tone=FilesNoticeTone::warning}); + } + if(!result.folder.empty()) + { + browser.chosen=std::move(result.folder); + FilesModalDialog::finish(dialog,IDOK); + return; + } + browser.server=profile; + browser.shares=std::move(result.shares); + showRows(dialog,browser); +} + +INT_PTR CALLBACK browserDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + auto *browser=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(message==WM_INITDIALOG) + { + browser=reinterpret_cast(lp); + SetWindowLongPtrW(dialog,DWLP_USER,lp); + prepareCopyDialog(dialog); + layoutDialogContent(dialog,summary); + for(const auto id:{summary,list,status}) + SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast(mono),FALSE); + SendDlgItemMessageW(dialog,list,LB_SETITEMHEIGHT,0,textHeight); + installScrollBar(GetDlgItem(dialog,list),dialog); + showRows(dialog,*browser); + return FALSE; + } + if(message==WM_DRAWITEM && wp==list) + { + const auto &item=*reinterpret_cast(lp); + if(item.itemID==UINT(-1)) return TRUE; + const auto length=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0); + if(length==LB_ERR) return TRUE; + std::wstring label(static_cast(length)+1,L'\0'); + SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast(label.data())); + const bool selected=(item.itemState&ODS_SELECTED)!=0; + paintDialogListRow(item.hDC,item.rcItem,label.c_str(),mono,colors[Text], + selected?colors[Selection]:colors[Dialog],dialogRowTextInset(cellWidth),DT_END_ELLIPSIS); + return TRUE; + } + if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" SMB ",false,{footer},true,GetDlgItem(dialog,list))) + return painted; + if(!browser) return FALSE; + if(closeRequest(message,wp)) + { + if(browser->busy) + { + browser->canceled=true; + SetDlgItemTextW(dialog,status,L"Stopping when Windows returns…"); + } + else FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND) return FALSE; + if(browser->busy) return TRUE; + const auto command=LOWORD(wp); + const auto row=SendDlgItemMessageW(dialog,list,LB_GETCURSEL,0,0); + if(command==list && HIWORD(wp)==LBN_SELCHANGE) + { + browserControls(dialog,*browser); + return TRUE; + } + const bool open=command==IDOK || (command==list && HIWORD(wp)==LBN_DBLCLK); + if(browser->server) + { + if(command==newProfile) + { + browser->server.reset(); + browser->shares.clear(); + showRows(dialog,*browser); + } + else if(open && row>=0 && static_cast(row)shares.size()) + { + browser->chosen=fs::path(browser->server->target.server+L"\\"+browser->shares[row]); + FilesModalDialog::finish(dialog,IDOK); + } + return TRUE; + } + const auto *selected=row>=0 && static_cast(row)profiles.size()?&browser->profiles[row]:nullptr; + if(command==newProfile || (command==editProfile && selected)) + { + EditProfile edit{command==newProfile?Profile{}:*selected}; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(122),dialog,editDialog, + reinterpret_cast(&edit))==IDOK) + { + browser->profiles=std::move(*edit.saved); + const auto profile=std::find_if(browser->profiles.begin(),browser->profiles.end(),[&](const auto &entry) { + return entry.id==edit.profile.id; + }); + showRows(dialog,*browser,profile-browser->profiles.begin()); + } + return TRUE; + } + if(selected && (open || command==signIn)) + { + openProfile(dialog,*browser,*selected,command==signIn); + return TRUE; + } + if(selected && command==removeProfile) + { + const auto detail=L"Remove "+selected->name+L" and its saved credentials?"; + if(showFilesNotice(dialog,detail.c_str(),L"Remove SMB connection",{.confirm=true})!=IDYES) return TRUE; + DWORD error=ERROR_SUCCESS; + auto updated=updateProfiles([&](auto &profiles) { + const auto row=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry){return entry.id==selected->id;}); + if(row==profiles.end()) return true; + if((error=deleteCredential(*row))) return false; + profiles.erase(row); + return true; + }); + if(updated) + { + browser->profiles=std::move(*updated); + showRows(dialog,*browser,row); + } + else + { + const auto failure=error?errorText(error):L"Could not remove the saved connection."; + showFilesNotice(dialog,failure.c_str(),L"Remove SMB connection"); + } + return TRUE; + } + return FALSE; +} +} + +void showSmbProfiles(Panel &panel) +{ + smb::Browser browser{smb::readProfiles()}; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(121),GetParent(panel.list), + smb::browserDialog,reinterpret_cast(&browser))==IDOK) + openOn(panel,browser.chosen,false,{}); +} diff --git a/tests/files_drive_shortcuts.ps1 b/tests/files_drive_shortcuts.ps1 index e02e975..8a66e44 100644 --- a/tests/files_drive_shortcuts.ps1 +++ b/tests/files_drive_shortcuts.ps1 @@ -6,6 +6,7 @@ param( ) $ErrorActionPreference = 'Stop' Add-Type -AssemblyName System.Drawing +. "$PSScriptRoot/files_commands_ui.ps1" Add-Type @' using System; using System.Text; @@ -44,7 +45,8 @@ $previousDpi = [FilesDriveShortcutTest]::SetThreadDpiAwarenessContext([IntPtr](- try { if ($FtpProfiles) { $preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files') - $preferenceNames = 'FtpProfiles', 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement' + $preferenceNames = 'FtpProfiles', 'LeftWide', 'RightWide', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', + 'LeftFtpLocation', 'RightFtpLocation', 'FontPoints', 'WindowPlacement' foreach ($name in $preferenceNames) { if ($name -in $preferences.GetValueNames()) { $savedPreferences[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name)) @@ -53,10 +55,22 @@ try { $profile = '[{"name":"Test FTP profile","host":"localhost","user":"","port":21,"secret":[]}]' $preferences.SetValue('FtpProfiles', [Text.Encoding]::UTF8.GetBytes($profile), 'Binary') foreach ($name in 'LeftWide', 'RightWide') { $preferences.SetValue($name, 1, 'DWord') } + $preferences.SetValue('FontPoints', 80, 'DWord') + foreach ($name in 'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement') { + $preferences.DeleteValue($name, $false) + } } - $process = Start-Process -FilePath (Resolve-Path $Executable) -PassThru - Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero } - $window = $process.MainWindowHandle + $process = Start-Process -FilePath (Resolve-Path $Executable) -WindowStyle Hidden -PassThru + $window = Wait-For 'the Files window' { + $candidate = [IntPtr]::Zero + while (($candidate = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $candidate, 'KSwitcher.Files', [NullString]::Value)) -ne [IntPtr]::Zero) { + [uint32]$owner = 0 + [void][FilesCommandsUi]::GetWindowThreadProcessId($candidate, [ref]$owner) + if ($owner -eq $process.Id) { return $candidate } + } + } + [void][FilesCommandsUi]::SetWindowPos($window, [IntPtr]::Zero, 65, 50, 1500, 900, 20) + [void][FilesCommandsUi]::ShowWindow($window, 4) $picker = [FilesDriveShortcutTest]::GetDlgItem($window, 121) $path = [FilesDriveShortcutTest]::GetDlgItem($window, 142) function Open-Picker([int]$Side = 0) { @@ -89,8 +103,8 @@ try { Open-Picker $side $rows = @(Read-Picker) $row = [Array]::IndexOf($rows, 'FTP') - if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'Recent folders' -or - $rows[$row + 2] -cne 'KSwitcher LAN') { + if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'SMB' -or + $rows[$row + 2] -cne 'Recent folders' -or $rows[$row + 3] -cne 'KSwitcher LAN') { throw "Source groups are missing separators in panel $side." } [void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$row, $null) @@ -101,12 +115,14 @@ try { [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero) Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 } [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero) + Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 2 } + [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero) Wait-Until { $selected = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() - $selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 2) + $selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 3) } [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero) - Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 1 } + Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 2 } [void][FilesDriveShortcutTest]::SendMessage($picker, 407, [IntPtr]($row - 2), $null) $bitmap = Render-Picker try { diff --git a/tests/files_smb_password.ps1 b/tests/files_smb_password.ps1 new file mode 100644 index 0000000..bef68ac --- /dev/null +++ b/tests/files_smb_password.ps1 @@ -0,0 +1,111 @@ +param( + [Parameter(Mandatory)][string]$Executable, + [string]$PreferenceKey = 'Software\KSwitcher\Files' +) + +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName System.Drawing +. "$PSScriptRoot/files_commands_ui.ps1" + +function Set-Password([IntPtr]$Field, [string]$Value) { + [void][FilesCommandsUi]::Read($Field, 12, [IntPtr]::Zero, [Text.StringBuilder]::new($Value)) + [void][FilesCommandsUi]::RedrawWindow($Field, [IntPtr]::Zero, [IntPtr]::Zero, 0x101) +} + +function Render-Password([IntPtr]$Field) { + $bounds = [FilesCommandsUi+Rect]::new() + [void][FilesCommandsUi]::GetClientRect($Field, [ref]$bounds) + $bitmap = [Drawing.Bitmap]::new($bounds.Right, $bounds.Bottom) + $data = [IO.MemoryStream]::new() + try { + $graphics = [Drawing.Graphics]::FromImage($bitmap) + try { + $dc = $graphics.GetHdc() + try { + if (![FilesCommandsUi]::PrintWindow($Field, $dc, 3)) { throw 'Could not render the password field.' } + } finally { $graphics.ReleaseHdc($dc) } + } finally { $graphics.Dispose() } + $bitmap.Save($data, [Drawing.Imaging.ImageFormat]::Png) + [Convert]::ToBase64String($data.ToArray()) + } finally { + $data.Dispose() + $bitmap.Dispose() + } +} + +$exe = (Resolve-Path -LiteralPath $Executable).Path +$local = Split-Path -Parent $exe +$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($PreferenceKey) +$saved = @{} +$names = 'SmbProfiles', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement' +foreach ($name in $names) { + if ($name -in $preferences.GetValueNames()) { + $saved[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name)) + } +} +$process = $null +try { + $profile = '[{"id":"e2932abf62404facb66fc8a98dfe47f4","name":"Render fixture","path":"\\\\masked-field.invalid"}]' + $preferences.SetValue('SmbProfiles', [Text.Encoding]::UTF8.GetBytes($profile), 'Binary') + foreach ($name in 'LeftPath', 'RightPath') { $preferences.SetValue($name, $local, 'String') } + foreach ($name in 'LeftCursor', 'RightCursor', 'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement') { + $preferences.DeleteValue($name, $false) + } + $process = Start-Process -FilePath $exe -WindowStyle Hidden -PassThru + $main = Wait-For 'the Files window' { + $window = [IntPtr]::Zero + while (($window = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $window, 'KSwitcher.Files', [NullString]::Value)) -ne [IntPtr]::Zero) { + [uint32]$owner = 0 + [void][FilesCommandsUi]::GetWindowThreadProcessId($window, [ref]$owner) + if ($owner -eq $process.Id) { return $window } + } + } + [void][FilesCommandsUi]::ShowWindow($main, 4) + $picker = [FilesCommandsUi]::GetDlgItem($main, 121) + [void][FilesCommandsUi]::Post($main, 0x104, [IntPtr]112, [IntPtr]::Zero) + [void](Wait-For 'Change drive' { [FilesCommandsUi]::IsWindowVisible($picker) }) + $count = [FilesCommandsUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() + $selection = -1 + for ($row = 0; $row -lt $count; ++$row) { + $label = [Text.StringBuilder]::new(256) + [void][FilesCommandsUi]::Read($picker, 393, [IntPtr]$row, $label) + if ($label.ToString() -ceq 'SMB') { $selection = $row; break } + } + if ($selection -lt 0) { throw 'SMB was missing from Change drive.' } + [void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$selection, [IntPtr]::Zero) + [void][FilesCommandsUi]::Post($picker, 0x100, [IntPtr]13, [IntPtr]::Zero) + function Find-DialogControl([int]$Id) { + $dialog = [IntPtr]::Zero + while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $dialog, '#32770', [NullString]::Value)) -ne [IntPtr]::Zero) { + [uint32]$owner = 0 + [void][FilesCommandsUi]::GetWindowThreadProcessId($dialog, [ref]$owner) + $control = [FilesCommandsUi]::GetDlgItem($dialog, $Id) + if ($owner -eq $process.Id -and [FilesCommandsUi]::IsWindowVisible($control)) { + return @($dialog, $control) + } + } + } + $browser, $signIn = Wait-For 'the SMB Sign in command' { Find-DialogControl 547 } + [void][FilesCommandsUi]::Post($browser, 0x111, [IntPtr]547, $signIn) + $dialog, $password = Wait-For 'the SMB password field' { Find-DialogControl 559 } + $empty = Render-Password $password + Set-Password $password 'WWWWWWWW' + $first = Render-Password $password + Set-Password $password 'iiiiiiii' + $second = Render-Password $password + if ($first -eq $empty -or $first -ne $second) { + throw 'Equal-length password inputs must render as the same visible mask.' + } + $remember = [FilesCommandsUi]::GetDlgItem($dialog, 560) + if ([FilesCommandsUi]::Send($remember, 0xf0, [IntPtr]::Zero, [IntPtr]::Zero) -ne [IntPtr]::Zero) { + throw 'Remember in Windows Credential Manager must be unchecked by default.' + } + 'Verified password masking and the default credential-saving choice.' +} finally { + if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() } + foreach ($name in $names) { + if ($saved.ContainsKey($name)) { $preferences.SetValue($name, $saved[$name][0], $saved[$name][1]) } + else { $preferences.DeleteValue($name, $false) } + } + $preferences.Dispose() +} From 94ccb488c1c0612883cd3bf5f9f053d349ca92db Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 18:23:38 +0200 Subject: [PATCH 26/61] Add SFTP profiles and shared Files operations Refs #110 --- CMakeLists.txt | 5 +- FILES-UI.md | 35 +++- cmake/FilesSshLibrary.cmake | 20 ++ package.ps1 | 3 +- resources/files-sftp-license.txt | 40 ++++ resources/files.rc | 25 +++ src/files_compare.inl | 6 +- src/files_ftp.inl | 92 ++++++--- src/files_ftp_copy.inl | 77 +++----- src/files_ftp_dialog.inl | 310 +++++++++++++++++++++++-------- src/files_main.cpp | 177 +++++++++++------- src/files_panel_recovery.inl | 21 ++- src/files_panel_rows.inl | 4 +- src/files_path_navigation.inl | 35 ++-- src/files_recent_folders.inl | 6 +- src/files_sftp.inl | 255 +++++++++++++++++++++++++ src/files_transfer.inl | 111 +++++++++++ tests/files_drive_shortcuts.ps1 | 10 +- 18 files changed, 966 insertions(+), 266 deletions(-) create mode 100644 cmake/FilesSshLibrary.cmake create mode 100644 resources/files-sftp-license.txt create mode 100644 src/files_sftp.inl create mode 100644 src/files_transfer.inl diff --git a/CMakeLists.txt b/CMakeLists.txt index a3502da..5e83806 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -14,6 +14,7 @@ set_property(SOURCE resources/files.rc APPEND PROPERTY OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/resources/kswitcher-files-compare.ico") include(cmake/FilesTextLibraries.cmake) include(cmake/FilesArchiveLibraries.cmake) +include(cmake/FilesSshLibrary.cmake) include(cmake/FilesImageLibraries.cmake) set_target_properties(KSwitcherFiles PROPERTIES OUTPUT_NAME "KSwitcher.Files") target_compile_definitions(KSwitcherFiles PRIVATE UNICODE _UNICODE NOMINMAX _WIN32_WINNT=0x0A00) @@ -34,7 +35,7 @@ add_custom_target(check-files-quick-view DEPENDS KSwitcherFiles VERBATIM) target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include") -target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr KSwitcherFilesImage) +target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr KSwitcherFilesImage libssh2::libssh2) if(MSVC) target_compile_options(KSwitcherFiles PRIVATE /utf-8) else() @@ -348,7 +349,7 @@ add_test(NAME screenshot-save-regressions COMMAND KSwitcherScreenshotUITests --s add_test(NAME updater-regressions COMMAND powershell.exe -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/update.ps1" -Executable "$") 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 resources/files-archive-license.txt resources/files-image-license.txt DESTINATION .) +install(FILES LICENSE vendor/json-LICENSE.txt resources/files-archive-license.txt resources/files-image-license.txt resources/files-sftp-license.txt DESTINATION .) add_custom_command(TARGET KSwitcher POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory "${CMAKE_CURRENT_SOURCE_DIR}/dictionaries" "$/dictionaries") install(DIRECTORY dictionaries DESTINATION .) diff --git a/FILES-UI.md b/FILES-UI.md index e7b3ead..9fdb245 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -64,6 +64,27 @@ Warning і початковий фокус на No. підтвердження й видаляє вибрані елементи з FTP-сервера без кошика. Для непорожньої папки Files окремо підтверджує видалення її вмісту. +- **SFTP** у меню джерел обох панелей відкриває збережені SSH-підключення. + Shift+F4 додає профіль, F4 редагує, Enter підключається. Укажи ім’я + користувача, хост, порт (типово 22) та пароль або повний шлях до ключа. + Поле пароля приймає кодову фразу для ключа. Windows DPAPI захищає + збережений пароль або кодову фразу. Для ключа користувача підходить + незашифрований RSA PEM або ECDSA OpenSSH із файлом .pub поруч. + ECDSA OpenSSH підтримує кодову фразу. Ключ залишається у вказаному файлі. +- У **Test connection** звір SHA‑256-відбиток ключа хоста з адміністратором + сервера та підтвердь довіру. Після цього Files перевіряє вхід. **Save** + зберігає профіль і підтверджений відбиток. Якщо відбиток змінюється, + Files блокує підключення до передачі пароля або підпису. + Для запланованої заміни ключа використовуй **Forget host key**, + а тоді **Test connection** зі звіркою нового відбитка. +- Для SFTP використовуються ключі хоста ECDSA або RSA з підписом SHA‑2. + F3 і F4 відкривають Viewer та Editor. F2 в Editor перевіряє розмір і час + зміни віддаленого файла перед збереженням. F5 копіює між локальною + та SFTP-панеллю в обидва боки зі спільним прогресом, скасуванням і + підтвердженням конфліктів. Для заміни існуючого файла сервер має + підтримувати атомарне перейменування OpenSSH. Якщо сервер відмовляє + в заміні, Files показує причину й зберігає попередній файл. + - **SMB** у меню джерел обох панелей відкриває збережені підключення. **New** додає назву й сервер або повний UNC-шлях. **Open** для сервера показує видимі дискові шари. Відомий прихований шар можна додати як @@ -82,7 +103,7 @@ Warning і початковий фокус на No. - **F9 → Commands → Compare files** порівнює два позначені текстові файли активної панелі або по одному файлу з кожної панелі. Якщо в панелі немає позначок, береться файл під курсором. Підтримуються локальні, LAN- та - FTP-файли. Файли показуються поруч із синхронною прокруткою, номерами + FTP- та SFTP-файли. Файли показуються поруч із синхронною прокруткою, номерами рядків і підсвічуванням вставок, видалень і замін. **Unified** перемикає на єдину колонку з номерами рядків обох файлів, видаленнями зі знаком − і вставками зі знаком +. Перемикання зберігає поточний блок. @@ -124,7 +145,7 @@ Warning і початковий фокус на No. - У меню Files і його списках, що випадають, стрілки вгору й вниз переходять між першим і останнім пунктами циклічно та оминають розділювачі. У меню джерел горизонтальна лінія відділяє FTP від локальних дисків, - а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP і SMB. + а заголовок KSwitcher LAN відділяє LAN-ресурси від FTP, SFTP і SMB. Літера відкриває локальний диск, цифра 1 відкриває FTP. Для LAN-дисків і Wake меню показує доступні цифри 2–9 і 0. Призначена цифра зберігається до закриття меню, навіть коли оновлюється список LAN. @@ -629,15 +650,15 @@ Warning і початковий фокус на No. показують перший кадр. Пошкоджені та надто великі файли показують повідомлення. - **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує - останні відвідані локальні, FTP та LAN-папки. Повторний візит підіймає + останні відвідані локальні, FTP, SFTP та LAN-папки. Повторний візит підіймає один запис угору, порядок зберігається після перезапуску. Enter або клік відкриває шлях у панелі, з якої викликали меню. Віддалені записи містять - шлях і ідентифікатор збереженого FTP-профілю або спареного ПК. Паролі - зберігаються лише в налаштуваннях FTP-профілів. Delete прибирає вибраний + шлях і ідентифікатор збереженого FTP- чи SFTP-профілю або спареного ПК. Паролі + зберігаються в захищених налаштуваннях профілів. Delete прибирає вибраний запис із недавніх. - Кнопки ← та → переходять назад і вперед в історії відповідної панелі, - зокрема між локальними, FTP та LAN-папками. Стрілка ↑, Alt+↑ та рядок `..` + зокрема між локальними, FTP, SFTP та LAN-папками. Стрілка ↑, Alt+↑ та рядок `..` відкривають безпосередню батьківську папку. На корені стрілка вимкнена, а рядка немає. Alt+← і Alt+→ працюють з історією активної панелі. - Сегменти шляху відкривають папки. Якщо шлях не вміщується, ліва @@ -646,7 +667,7 @@ Warning і початковий фокус на No. відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях, а Esc повертає до тих самих панелей і курсора. -- У заголовку FTP-папки клік по назві профілю відкриває збережені +- У заголовку FTP- чи SFTP-папки клік по назві профілю відкриває збережені підключення. У LAN-папці клік по назві ПК відкриває спарені комп’ютери та їхні диски. Поле шляху й доповнення працюють у поточному джерелі. Для FTP абсолютний шлях починається з /. diff --git a/cmake/FilesSshLibrary.cmake b/cmake/FilesSshLibrary.cmake new file mode 100644 index 0000000..e0c23ff --- /dev/null +++ b/cmake/FilesSshLibrary.cmake @@ -0,0 +1,20 @@ +include(FetchContent) + +# This revision includes the published SFTP security fixes after the 1.11.1 release. +FetchContent_Declare(kswitcher_libssh2 + URL https://codeload.github.com/libssh2/libssh2/tar.gz/dd1546700d0ed8ff7138bc1ccc288286fb3ab2b4 + URL_HASH SHA256=67d20d434055faef76439c6829ab253c892fcdd68d9a9c86cf5824bd8366e6eb + DOWNLOAD_EXTRACT_TIMESTAMP TRUE) + +function(kswitcher_add_ssh_library) + set(BUILD_STATIC_LIBS ON) + set(BUILD_SHARED_LIBS OFF) + set(BUILD_EXAMPLES OFF) + set(BUILD_TESTING OFF) + set(LIBSSH2_DISABLE_INSTALL ON) + set(LIBSSH2_BUILD_DOCS OFF) + set(CRYPTO_BACKEND WinCNG) + set(ENABLE_ECDSA_WINCNG ON) + FetchContent_MakeAvailable(kswitcher_libssh2) +endfunction() +kswitcher_add_ssh_library() diff --git a/package.ps1 b/package.ps1 index 4dc019a..7af53f7 100644 --- a/package.ps1 +++ b/package.ps1 @@ -14,6 +14,7 @@ Copy-Item -LiteralPath (Join-Path $root 'vendor\json-LICENSE.txt') -Destination Copy-Item -LiteralPath (Join-Path $root 'resources\files-text-license.txt') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'resources\files-archive-license.txt') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'resources\files-image-license.txt') -Destination $destination +Copy-Item -LiteralPath (Join-Path $root 'resources\files-sftp-license.txt') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'README.md') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'LAN-PREVIEW.md') -Destination $destination Copy-Item -LiteralPath (Join-Path $root 'dictionaries') -Destination $destination -Recurse -Force @@ -22,7 +23,7 @@ Copy-Item -LiteralPath (Join-Path $root 'resources\portable-tools-README.txt') - Copy-Item -LiteralPath (Join-Path $root 'build\release\tools\StayHere.exe') -Destination (Join-Path $destination 'tools\StayHere.exe') -Force Copy-Item -LiteralPath (Join-Path $root 'utilities\StayHere\README.md') -Destination (Join-Path $destination 'tools\StayHere-README.md') -Force # Enumerate the distributable files explicitly; do not include a user's data directory. -$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','files-archive-license.txt','files-image-license.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ } +$files = @('KSwitcher.exe','KSwitcher.Config.exe','KSwitcher.Screenshot.exe','KSwitcher.Files.exe','WebView2Loader.dll','terminal','LICENSE','json-LICENSE.txt','files-text-license.txt','files-archive-license.txt','files-image-license.txt','files-sftp-license.txt','README.md','LAN-PREVIEW.md','dictionaries','tools\README.txt','tools\StayHere.exe','tools\StayHere-README.md') | ForEach-Object { Join-Path $destination $_ } $entries = foreach ($path in $files) { foreach ($file in @(Get-ChildItem -LiteralPath $path -File -Recurse)) { @{path=$file.FullName.Substring($destination.Length+1).Replace('\','/'); size=$file.Length; sha256=(Get-FileHash -LiteralPath $file.FullName -Algorithm SHA256).Hash.ToLowerInvariant()} diff --git a/resources/files-sftp-license.txt b/resources/files-sftp-license.txt new file mode 100644 index 0000000..479d30a --- /dev/null +++ b/resources/files-sftp-license.txt @@ -0,0 +1,40 @@ +libssh2 +https://libssh2.org/ +Upstream revision dd1546700d0ed8ff7138bc1ccc288286fb3ab2b4 + +/* Copyright (C) 2004-2007 Sara Golemon + * Copyright (C) 2005,2006 Mikhail Gusarov + * Copyright (C) 2006-2007 The Written Word, Inc. + * Copyright (C) 2007 Eli Fant + * Copyright (C) 2009-2023 Daniel Stenberg + * Copyright (C) 2008, 2009 Simon Josefsson + * Copyright (C) 2000 Markus Friedl + * Copyright (C) 2015 Microsoft Corp. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ diff --git a/resources/files.rc b/resources/files.rc index 3c34e3e..08f36a5 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -559,3 +559,28 @@ BEGIN CONTROL "&Connect", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 92, 132, 80, 17 CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 182, 132, 80, 17 END + +124 DIALOGEX 0, 0, 420, 207 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP +CAPTION "SFTP connection" +FONT 10, "Consolas" +BEGIN + LTEXT "Connection &name", 381, 16, 15, 388, 12 + FAR_EDIT(382, 0, 16, 28, 388, 15) + LTEXT "Server &host", 383, 16, 49, 292, 12 + LTEXT "P&ort", 384, 328, 49, 76, 12 + FAR_EDIT(385, 0, 16, 62, 302, 15) + FAR_EDIT(386, ES_NUMBER, 328, 62, 76, 15) + LTEXT "&User name", 387, 16, 83, 182, 12 + FAR_EDIT(388, 0, 16, 96, 182, 15) + LTEXT "&Password or key passphrase", 389, 210, 83, 194, 12 + EDITTEXT 390, 210, 96, 194, 15, ES_LEFT | ES_PASSWORD | ES_AUTOHSCROLL + LTEXT "Private &key file (optional)", 562, 16, 117, 388, 12 + FAR_EDIT(563, 0, 16, 130, 388, 15) + LTEXT "", 566, 16, 153, 388, 14, SS_ENDELLIPSIS | SS_NOPREFIX + LTEXT "", 391, 10, 175, 1, 1, NOT WS_VISIBLE + CONTROL "&Test connection", 564, "Button", BS_OWNERDRAW | WS_TABSTOP, 20, 183, 128, 17 + CONTROL "&Forget host key", 565, "Button", BS_OWNERDRAW | WS_TABSTOP, 152, 183, 112, 17 + CONTROL "&Save", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 270, 183, 60, 17 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 336, 183, 67, 17 +END diff --git a/src/files_compare.inl b/src/files_compare.inl index 6a2dba3..9f028f5 100644 --- a/src/files_compare.inl +++ b/src/files_compare.inl @@ -66,7 +66,7 @@ struct CompareFile fs::path path; std::wstring label; std::optional peer; - std::optional ftp; + std::optional ftp; std::optional remote; ks::files::RemoteTextRevision revision; std::string originalBytes; @@ -276,7 +276,7 @@ ks::files::ComparisonText readComparisonLines(CompareFile &input,const std::atom { CompareCache temp; auto path=input.path; - if(input.ftp) input.remote=ftpTextSource(*input.ftp); + if(input.ftp) input.remote=transferTextSource(*input.ftp); else if(input.peer) { FilesConnection source(&*input.peer); @@ -1252,7 +1252,7 @@ void compareSelectedFiles(HWND owner) const auto pick=[](const Panel &panel,const fs::path &path,CompareFile &file) { const auto row=std::find(panel.rows.begin(),panel.rows.end(),path); - if(panel.archive || ftpProfileList(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder") + if(panel.archive || transferProfileList(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder") return false; const auto directory=path.parent_path(); const auto tail=(directory.filename()/path.filename()).native(); diff --git a/src/files_ftp.inl b/src/files_ftp.inl index eb8f75b..db3c04c 100644 --- a/src/files_ftp.inl +++ b/src/files_ftp.inl @@ -1,16 +1,37 @@ -struct FtpProfile +enum class TransferProtocol { ftp, sftp }; +constexpr unsigned defaultSftpPort=22; + +const wchar_t *transferProtocolName(TransferProtocol protocol) +{ + return protocol==TransferProtocol::sftp?L"SFTP":L"FTP"; +} + +struct TransferProfile { std::wstring name, host, user; INTERNET_PORT port=INTERNET_DEFAULT_FTP_PORT; ks::Bytes secret; bool legacyNames{}; std::string id; + TransferProtocol protocol{}; + fs::path privateKey; + std::string hostFingerprint; }; -std::vector ftpProfiles; -bool ftpProfilesLoaded{}; -constexpr wchar_t ftpProfilesValue[]=L"FtpProfiles"; -constexpr DWORD ftpProfilesMaxBytes=1024*1024; +struct TransferProfiles +{ + const wchar_t *preference; + std::vector rows; + bool loaded{}; +}; + +TransferProfiles &transferProfiles(TransferProtocol protocol) +{ + static TransferProfiles ftp{L"FtpProfiles"},sftp{L"SftpProfiles"}; + return protocol==TransferProtocol::sftp?sftp:ftp; +} + +constexpr DWORD transferProfilesMaxBytes=1024*1024; const fs::path ftpRoot=L"\\"; bool isFtpFolderPath(const fs::path &path) @@ -25,70 +46,85 @@ std::wstring ftpPath(const fs::path &path) return value; } -bool saveFtpProfiles(const std::vector &profiles) +bool saveTransferProfiles(TransferProtocol protocol,const std::vector &profiles) { auto rows=Json::array(); for(const auto &profile:profiles) - rows.push_back({{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)}, + { + Json row{{"name",ks::utf8(profile.name)},{"host",ks::utf8(profile.host)}, {"port",profile.port},{"user",ks::utf8(profile.user)},{"secret",profile.secret}, - {"legacyNames",profile.legacyNames},{"id",profile.id}}); + {"legacyNames",profile.legacyNames},{"id",profile.id}}; + if(protocol==TransferProtocol::sftp) + { + row["privateKey"]=ks::utf8(profile.privateKey.native()); + row["hostFingerprint"]=profile.hostFingerprint; + } + rows.push_back(std::move(row)); + } const auto data=rows.dump(); - return data.size()<=ftpProfilesMaxBytes && - RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,REG_BINARY,data.data(), + return data.size()<=transferProfilesMaxBytes && + RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,transferProfiles(protocol).preference,REG_BINARY,data.data(), static_cast(data.size()))==ERROR_SUCCESS; } -bool loadFtpProfiles() +bool loadTransferProfiles(TransferProtocol protocol=TransferProtocol::ftp) { - if(ftpProfilesLoaded) return true; + auto &settings=transferProfiles(protocol); + if(settings.loaded) return true; DWORD bytes{}; - const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue, + const auto query=RegGetValueW(HKEY_CURRENT_USER,schemeKey,settings.preference, RRF_RT_REG_BINARY,nullptr,nullptr,&bytes); if(query==ERROR_FILE_NOT_FOUND) { - ftpProfilesLoaded=true; + settings.loaded=true; return true; } - if(query!=ERROR_SUCCESS || !bytes || bytes>ftpProfilesMaxBytes) return false; + if(query!=ERROR_SUCCESS || !bytes || bytes>transferProfilesMaxBytes) return false; std::string data(bytes,'\0'); - if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,ftpProfilesValue,RRF_RT_REG_BINARY, + if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,settings.preference,RRF_RT_REG_BINARY, nullptr,data.data(),&bytes)!=ERROR_SUCCESS) return false; try { const auto rows=Json::parse(data.begin(),data.begin()+bytes); if(!rows.is_array()) return false; - std::vector profiles; + std::vector profiles; for(const auto &row:rows) { const auto port=row.at("port").get(); if(!port || port>65535) return false; - FtpProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")), + TransferProfile profile{ks::wide(row.at("name")),ks::wide(row.at("host")), ks::wide(row.at("user")),static_cast(port),row.at("secret").get(), - row.value("legacyNames",false),row.value("id",std::string{})}; + row.value("legacyNames",false),row.value("id",std::string{}),protocol}; if(profile.id.empty()) profile.id="legacy:"+ks::utf8(profile.name); if(profile.name.empty() || profile.host.empty()) return false; + if(protocol==TransferProtocol::sftp) + { + profile.privateKey=ks::wide(row.value("privateKey",std::string{})); + profile.hostFingerprint=row.value("hostFingerprint",std::string{}); + } profiles.push_back(std::move(profile)); } - ftpProfiles=std::move(profiles); - ftpProfilesLoaded=true; + settings.rows=std::move(profiles); + settings.loaded=true; return true; } catch(const std::exception &) {return false;} } -const FtpProfile *findFtpProfile(std::string_view id) +const TransferProfile *findTransferProfile(std::string_view id,TransferProtocol protocol=TransferProtocol::ftp) { - const auto profile=std::find_if(ftpProfiles.begin(),ftpProfiles.end(),[&](const auto &entry) { + const auto &profiles=transferProfiles(protocol).rows; + const auto profile=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry) { return entry.id==id; }); - return profile==ftpProfiles.end()?nullptr:&*profile; + return profile==profiles.end()?nullptr:&*profile; } -std::wstring ftpPassword(const FtpProfile &profile) +std::wstring transferPassword(const TransferProfile &profile) { if(profile.secret.empty()) return {}; auto bytes=ks::unprotect(profile.secret); - if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid FTP password"); + if(bytes.size()%sizeof(wchar_t)) throw std::runtime_error("Invalid saved transfer password"); std::wstring password(bytes.size()/sizeof(wchar_t),L'\0'); std::copy(bytes.begin(),bytes.end(),reinterpret_cast(password.data())); SecureZeroMemory(bytes.data(),bytes.size()); @@ -157,7 +193,7 @@ class FtpSession UINT nameCodePage_; public: - explicit FtpSession(const FtpProfile &profile):nameCodePage_(profile.legacyNames?GetACP():CP_UTF8) + explicit FtpSession(const TransferProfile &profile):nameCodePage_(profile.legacyNames?GetACP():CP_UTF8) { checkFileOperation(internet_.value!=nullptr); DWORD timeout=10000, retries=1; @@ -165,7 +201,7 @@ public: InternetSetOptionW(internet_.value,INTERNET_OPTION_CONNECT_RETRIES,&retries,sizeof(retries)); InternetSetOptionW(internet_.value,INTERNET_OPTION_RECEIVE_TIMEOUT,&timeout,sizeof(timeout)); InternetSetOptionW(internet_.value,INTERNET_OPTION_SEND_TIMEOUT,&timeout,sizeof(timeout)); - auto password=ftpPassword(profile); + auto password=transferPassword(profile); const auto user=profile.user.empty()?(password.empty()?nullptr:L"anonymous"):profile.user.c_str(); connection_.value=InternetConnectW(internet_.value,profile.host.c_str(),profile.port, user,password.empty()?nullptr:password.c_str(),INTERNET_SERVICE_FTP,INTERNET_FLAG_PASSIVE,0); diff --git a/src/files_ftp_copy.inl b/src/files_ftp_copy.inl index 6c9e6b9..c70218f 100644 --- a/src/files_ftp_copy.inl +++ b/src/files_ftp_copy.inl @@ -1,7 +1,7 @@ -FileEntries ftpChildren(FtpSession &session,const fs::path &directory,const std::atomic_bool *canceled=nullptr) +FileEntries transferChildren(TransferSession &session,const fs::path &directory,const std::atomic_bool *canceled=nullptr) { FileEntries entries; - const auto error=listFtpDirectory(session,directory,[&](const fs::path &path,const FileInfo &info) + const auto error=session.list(directory,[&](const fs::path &path,const FileInfo &info) { if(canceled && *canceled) return false; entries.emplace_back(path,info); @@ -11,30 +11,22 @@ FileEntries ftpChildren(FtpSession &session,const fs::path &directory,const std: return entries; } -std::optional ftpEntry(const FileEntries &entries,const fs::path &path) +std::optional transferEntry(const FileEntries &entries,const fs::path &path) { const auto entry=std::find_if(entries.begin(),entries.end(), [&](const auto &item){return item.first==path;}); return entry==entries.end()?std::nullopt:std::optional(entry->second); } -void renameFtpEntry(FtpSession &ftp,const fs::path &source,const fs::path &target) -{ - ftp.setDirectory(source.parent_path()); - const auto oldName=ftp.encodeName(source.filename()); - const auto newName=ftp.encodeName(target.filename()); - checkFileOperation(FtpRenameFileA(ftp.handle(),oldName.c_str(),newName.c_str())); -} - struct CopyHost { std::optional files; - std::optional ftp; + std::optional ftp; FileOperationElevation *elevation{}; fs::path listedDirectory; FileEntries listedEntries; - CopyHost(const FilesPeer *peer,const std::optional &profile,FileOperationElevation *admin=nullptr) + CopyHost(const FilesPeer *peer,const std::optional &profile,FileOperationElevation *admin=nullptr) { if(profile) ftp.emplace(*profile); else files.emplace(peer); @@ -50,7 +42,7 @@ struct CopyHost { if(path!=listedDirectory) { - listedEntries=ftpChildren(*ftp,path,&canceled); + listedEntries=transferChildren(*ftp,path,&canceled); listedDirectory=path; } return listedEntries; @@ -58,7 +50,7 @@ struct CopyHost std::optional stat(const fs::path &path,const std::atomic_bool &canceled) { - return ftp?ftpEntry(ftpListing(path.parent_path(),canceled),path):statFile(request(fileRequest("stat",path))); + return ftp?transferEntry(ftpListing(path.parent_path(),canceled),path):statFile(request(fileRequest("stat",path))); } FileEntries children(const fs::path &path,const std::atomic_bool &canceled) @@ -82,8 +74,7 @@ struct CopyHost checkFileReply(request(fileRequest("mkdir",path))); return; } - ftp->setDirectory(path.parent_path()); - checkFileOperation(FtpCreateDirectoryA(ftp->handle(),ftp->encodeName(path.filename()).c_str())); + ftp->makeDirectory(path); listedDirectory.clear(); } @@ -91,10 +82,7 @@ struct CopyHost { if(ftp) { - ftp->setDirectory(path.parent_path()); - const auto name=ftp->encodeName(path.filename()); - checkFileOperation(attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)? - FtpRemoveDirectoryA(ftp->handle(),name.c_str()):FtpDeleteFileA(ftp->handle(),name.c_str())); + ftp->remove(path,attributes!=INVALID_FILE_ATTRIBUTES && (attributes&FILE_ATTRIBUTE_DIRECTORY)); return; } auto message=fileRequest(permanent?"remove":"recycle",path); @@ -103,14 +91,10 @@ struct CopyHost } }; -constexpr DWORD ftpCopyFlags=INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE; - -void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &source,const fs::path &target, +void downloadTransferFile(TransferSession &ftp,FilesConnection &local,const fs::path &source,const fs::path &target, const FileInfo &info,bool replace,const ks::lan::FileProgress &progress) { - ftp.setDirectory(source.parent_path()); - const FtpHandle input{FtpOpenFileA(ftp.handle(),ftp.encodeName(source.filename()).c_str(),GENERIC_READ,ftpCopyFlags,0)}; - checkFileOperation(input.value!=nullptr); + auto input=ftp.open(source,false); auto upload=fileRequest("openWrite",target); upload["transfer"]=ks::lan::randomHex(32); upload["size"]=info.size; @@ -123,8 +107,7 @@ void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &sour ks::Bytes bytes(ks::lan::FileChunk); while(!progress || progress(done,info.size)) { - DWORD read{}; - checkFileOperation(InternetReadFile(input.value,bytes.data(),static_cast(bytes.size()),&read)); + const auto read=input.read(bytes.data(),bytes.size()); if(!read) { requireFileOperation(done==info.size,ERROR_FILE_INVALID); @@ -146,7 +129,7 @@ void downloadFtpFile(FtpSession &ftp,FilesConnection &local,const fs::path &sour } } -FileInfo uploadFtpFile(FilesConnection &local,FtpSession &ftp,const fs::path &source,const fs::path &target, +FileInfo uploadTransferFile(FilesConnection &local,TransferSession &ftp,const fs::path &source,const fs::path &target, const FileInfo &info,bool replace,const ks::lan::FileProgress &progress, const ks::files::RemoteTextRevision *expected=nullptr) { @@ -156,55 +139,51 @@ FileInfo uploadFtpFile(FilesConnection &local,FtpSession &ftp,const fs::path &so open["size"]=info.size; open["modified"]=info.modified; checkFileReply(local.call(open)); - ftp.setDirectory(directory); - const auto stage=ftp.encodeName(temporary.filename()); - bool staged=false; + bool staged=false,reading=true; try { uint64_t done=0; { - FtpHandle output{FtpOpenFileA(ftp.handle(),stage.c_str(),GENERIC_WRITE,ftpCopyFlags,0)}; - checkFileOperation(output.value!=nullptr); + auto output=ftp.open(temporary,true); staged=true; for(;;) { - requireFileOperation(progress(done,info.size),ERROR_CANCELLED); + requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED); const auto packet=local.call({{"action","read"}}); checkFileReply(packet); const auto &bytes=packet.at("data").get_binary(); if(bytes.empty()) break; requireFileOperation(bytes.size()<=info.size-done,ERROR_FILE_INVALID); - for(DWORD offset=0;offset(bytes.size()-offset),&written)); + const auto written=output.write(bytes.data()+offset,bytes.size()-offset); requireFileOperation(written!=0,ERROR_WRITE_FAULT); offset+=written; } done+=bytes.size(); } requireFileOperation(done==info.size,ERROR_FILE_INVALID); - checkFileOperation(InternetCloseHandle(output.value)); - output.value=nullptr; + output.close(); } checkFileReply(local.call({{"action","closeRead"}})); - const auto entries=ftpChildren(ftp,directory); - const auto uploaded=ftpEntry(entries,temporary); + reading=false; + const auto entries=transferChildren(ftp,directory); + const auto uploaded=transferEntry(entries,temporary); requireFileOperation(uploaded && uploaded->size==done,ERROR_WRITE_FAULT); - const auto existing=ftpEntry(entries,target); + const auto existing=transferEntry(entries,target); if(expected && (!existing || existing->size!=expected->size || existing->modified!=expected->modified)) - throw std::runtime_error("The FTP file changed since it was opened. Your edits are still in the editor."); + throw std::runtime_error("The "+ks::utf8(ftp.label())+" file changed since it was opened. Your edits are still in the editor."); if(existing) requireFileOperation(replace && !(existing->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)), ERROR_ALREADY_EXISTS); - requireFileOperation(progress(done,info.size),ERROR_CANCELLED); - renameFtpEntry(ftp,temporary,target); + requireFileOperation(!progress || progress(done,info.size),ERROR_CANCELLED); + ftp.rename(temporary,target,existing.has_value()); return *uploaded; } catch(...) { - if(staged) FtpDeleteFileA(ftp.handle(),stage.c_str()); + if(reading) try {local.call({{"action","closeRead"}});} catch(const std::exception &) {} + if(staged) try {ftp.remove(temporary,false);} catch(const std::exception &) {} throw; } } diff --git a/src/files_ftp_dialog.inl b/src/files_ftp_dialog.inl index 8e1e32c..3d6e272 100644 --- a/src/files_ftp_dialog.inl +++ b/src/files_ftp_dialog.inl @@ -1,67 +1,60 @@ -namespace ftpDialog +namespace transferDialog { constexpr int name=382, host=385, port=386, user=388, password=390, footer=391, legacy=392; +constexpr int keyLabel=562,keyFile=563,testConnection=564,forgetKey=565,hostStatus=566; struct Edit { - FtpProfile profile; + TransferProfile profile; std::optional index; + std::wstring pinnedHost; + INTERNET_PORT pinnedPort{}; + std::string pin; + bool testing{}; + std::atomic_bool canceled{}; }; -INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +bool sameEndpoint(const Edit &edit,const TransferProfile &profile) { - if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" FTP connection ",false,{footer})) - return painted; - if(message==WM_INITDIALOG) + return edit.pinnedPort==profile.port && CompareStringOrdinal(edit.pinnedHost.c_str(),-1, + profile.host.c_str(),-1,TRUE)==CSTR_EQUAL; +} + +std::wstring connectionTitle(TransferProtocol protocol) +{ + return std::wstring(transferProtocolName(protocol))+L" connection"; +} + +void showHostStatus(HWND dialog,const Edit &edit) +{ + TransferProfile current; + current.host=trimFilesField(shortcutField(dialog,host)); + BOOL valid{}; + current.port=static_cast(GetDlgItemInt(dialog,port,&valid,FALSE)); + const bool trusted=valid && !edit.pin.empty() && sameEndpoint(edit,current); + const auto message=trusted?L"Trusted "+ks::wide(edit.pin):std::wstring(L"Host key not verified"); + SetDlgItemTextW(dialog,hostStatus,message.c_str()); + EnableWindow(GetDlgItem(dialog,forgetKey),trusted && !edit.testing); +} + +std::optional readProfile(HWND dialog,const Edit &edit) +{ + TransferProfile profile; + profile.protocol=edit.profile.protocol; + const bool sftp=profile.protocol==TransferProtocol::sftp; + const auto invalid=[&](int field,const wchar_t *message)->std::optional { - SetWindowLongPtrW(dialog,DWLP_USER,lp); - auto &profile=reinterpret_cast(lp)->profile; - prepareCopyDialog(dialog); - layoutDialogContent(dialog,381); - for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL}) - SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast(mono),FALSE); - for(const auto id:{name,host,user,password}) - SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0); - SendDlgItemMessageW(dialog,port,EM_SETLIMITTEXT,5,0); - SetDlgItemTextW(dialog,name,profile.name.c_str()); - SetDlgItemTextW(dialog,host,profile.host.c_str()); - SetDlgItemTextW(dialog,port,std::to_wstring(profile.port).c_str()); - SetDlgItemTextW(dialog,user,profile.user.c_str()); - installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray); - CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED); - try - { - auto secret=ftpPassword(profile); - SetDlgItemTextW(dialog,password,secret.c_str()); - SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t)); - } - catch(const std::exception &) - { - SetWindowTextW(GetDlgItem(dialog,389),L"&Password (re-enter to replace saved password)"); - } - layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL}); - return TRUE; - } - if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) - { - FilesModalDialog::finish(dialog,IDCANCEL); - return TRUE; - } - if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE; - auto &edit=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); - const auto invalid=[&](int field,const wchar_t *message) - { - showFilesNotice(dialog,message,L"FTP connection"); + showFilesNotice(dialog,message,connectionTitle(profile.protocol).c_str()); SetFocus(GetDlgItem(dialog,field)); - return TRUE; + return {}; }; - FtpProfile profile; - profile.legacyNames=IsDlgButtonChecked(dialog,legacy)==BST_CHECKED; + profile.legacyNames=!sftp && IsDlgButtonChecked(dialog,legacy)==BST_CHECKED; profile.name=trimFilesField(shortcutField(dialog,name)); if(profile.name.empty() || profile.name==L".." || profile.name.find_first_of(L"\r\n\t")!=profile.name.npos) return invalid(name,L"Enter a name for this connection."); - for(size_t i=0;i65535) return invalid(port,L"Enter a port from 1 to 65535."); profile.port=static_cast(number); profile.user=shortcutField(dialog,user); - if(profile.user.find_first_of(L"\r\n")!=profile.user.npos) + if(profile.user.find_first_of(L"\r\n")!=profile.user.npos || (sftp && profile.user.empty())) return invalid(user,L"Enter the user name on one line."); + if(sftp) + { + profile.privateKey=trimFilesField(shortcutField(dialog,keyFile)); + if(!profile.privateKey.empty() && !profile.privateKey.is_absolute()) + return invalid(keyFile,L"Enter the full path of the private key file."); + if(sameEndpoint(edit,profile)) profile.hostFingerprint=edit.pin; + } + auto plain=shortcutField(dialog,password); + if(!plain.empty()) + { + const auto start=reinterpret_cast(plain.data()); + ks::Bytes bytes(start,start+plain.size()*sizeof(wchar_t)); + struct Erase + { + ks::Bytes &bytes; + std::wstring &text; + ~Erase() + { + SecureZeroMemory(bytes.data(),bytes.size()); + SecureZeroMemory(text.data(),text.size()*sizeof(wchar_t)); + } + } erase{bytes,plain}; + profile.secret=ks::protect(bytes); + } + profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16); + return profile; +} + +template +bool runTest(HWND dialog,Edit &edit,const wchar_t *status,Task task) +{ + constexpr int controls[]{name,host,port,user,password,keyFile,testConnection,forgetKey,IDOK}; + edit.testing=true; + edit.canceled=false; + for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),FALSE); + SetFocus(GetDlgItem(dialog,IDCANCEL)); + SetDlgItemTextW(dialog,hostStatus,status); + std::wstring error; try { - auto plain=shortcutField(dialog,password); - if(!plain.empty()) + FileOperationUi worker; + worker.run(dialog,edit.canceled,std::move(task)); + } + catch(const std::exception &exception) {error=ks::wide(exception.what());} + edit.testing=false; + for(const auto id:controls) EnableWindow(GetDlgItem(dialog,id),TRUE); + showHostStatus(dialog,edit); + if(edit.canceled) return false; + if(error.empty()) return true; + showFilesNotice(dialog,error.c_str(),L"SFTP connection test",{.tone=FilesNoticeTone::warning}); + return false; +} + +void testSftp(HWND dialog,Edit &edit,TransferProfile profile) +{ + if(profile.hostFingerprint.empty()) + { + std::string fingerprint; + if(!runTest(dialog,edit,L"Reading the SSH host key…",[&] { + const SftpSession probe(profile,true); + fingerprint=probe.fingerprint(); + })) return; + const auto prompt=profile.host+L":"+std::to_wstring(profile.port)+L"\r\n"+ks::wide(fingerprint)+ + L"\r\n\r\nVerify this fingerprint with the server administrator. Trust this SSH host key?"; + if(showFilesNotice(dialog,prompt.c_str(),L"Verify SFTP host key",{.confirm=true})!=IDYES) return; + edit.pinnedHost=profile.host; + edit.pinnedPort=profile.port; + profile.hostFingerprint=edit.pin=std::move(fingerprint); + } + fs::path initial; + if(runTest(dialog,edit,L"Testing the SFTP login…",[&] { + SftpSession session(profile); + initial=session.initialDirectory(); + })) + { + const auto details=L"Connected to "+profile.host+L".\r\n\r\nInitial folder "+ftpPath(initial)+L"."; + showFilesNotice(dialog,details.c_str(),L"SFTP connection test"); + } +} + +INT_PTR CALLBACK procedure(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + auto *edit=message==WM_INITDIALOG?reinterpret_cast(lp): + reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + const bool sftp=edit && edit->profile.protocol==TransferProtocol::sftp; + if(const auto painted=paintCopyDialog(dialog,message,wp,lp,sftp?L" SFTP connection ":L" FTP connection ",false,{footer})) + return painted; + if(message==WM_INITDIALOG) + { + SetWindowLongPtrW(dialog,DWLP_USER,lp); + const auto &profile=edit->profile; + prepareCopyDialog(dialog); + layoutDialogContent(dialog,381); + for(const auto id:{381,383,384,387,389,legacy,IDOK,IDCANCEL,keyLabel,hostStatus}) + if(const auto control=GetDlgItem(dialog,id)) SendMessageW(control,WM_SETFONT,reinterpret_cast(mono),FALSE); + for(const auto id:{name,host,user,password}) + SendDlgItemMessageW(dialog,id,EM_SETLIMITTEXT,255,0); + SendDlgItemMessageW(dialog,port,EM_SETLIMITTEXT,5,0); + SetDlgItemTextW(dialog,name,profile.name.c_str()); + SetDlgItemTextW(dialog,host,profile.host.c_str()); + SetDlgItemTextW(dialog,port,std::to_wstring(profile.port).c_str()); + SetDlgItemTextW(dialog,user,profile.user.c_str()); + if(sftp) { - const auto start=reinterpret_cast(plain.data()); - ks::Bytes bytes(start,start+plain.size()*sizeof(wchar_t)); - SecureZeroMemory(plain.data(),plain.size()*sizeof(wchar_t)); - profile.secret=ks::protect(bytes); - SecureZeroMemory(bytes.data(),bytes.size()); + SendDlgItemMessageW(dialog,keyFile,EM_SETLIMITTEXT,32767,0); + SetDlgItemTextW(dialog,keyFile,profile.privateKey.c_str()); + showHostStatus(dialog,*edit); + layoutDialogButtons(dialog,footer,{testConnection,forgetKey,IDOK,IDCANCEL}); } - profile.id=edit.index?edit.profile.id:ks::lan::randomHex(16); - auto updated=ftpProfiles; - if(edit.index) updated[*edit.index]=std::move(profile); - else updated.push_back(std::move(profile)); - if(saveFtpProfiles(updated)) + else { - ftpProfiles=std::move(updated); + installFarCheckbox(GetDlgItem(dialog,legacy),FarCheckboxSurface::gray); + CheckDlgButton(dialog,legacy,profile.legacyNames?BST_CHECKED:BST_UNCHECKED); + layoutDialogButtons(dialog,footer,{IDOK,IDCANCEL}); + } + try + { + auto secret=transferPassword(profile); + SetDlgItemTextW(dialog,password,secret.c_str()); + SecureZeroMemory(secret.data(),secret.size()*sizeof(wchar_t)); + } + catch(const std::exception &) + { + SetDlgItemTextW(dialog,389,L"&Secret (re-enter to replace the saved value)"); + } + return TRUE; + } + if(!edit) return FALSE; + if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) + { + if(edit->testing) + { + edit->canceled=true; + SetDlgItemTextW(dialog,hostStatus,L"Stopping when the current request returns…"); + } + else + { + SetDlgItemTextW(dialog,password,L""); + SendDlgItemMessageW(dialog,password,EM_EMPTYUNDOBUFFER,0,0); + FilesModalDialog::finish(dialog,IDCANCEL); + } + return TRUE; + } + if(message!=WM_COMMAND) return FALSE; + if(edit->testing) return TRUE; + const auto command=LOWORD(wp); + if(sftp && HIWORD(wp)==EN_CHANGE && (command==host || command==port)) + { + showHostStatus(dialog,*edit); + return TRUE; + } + if(sftp && command==forgetKey) + { + if(showFilesNotice(dialog,L"Forget the trusted key for this endpoint? A new key must be verified before signing in.", + L"SFTP host key",{.confirm=true})==IDYES) + { + edit->pin.clear(); + showHostStatus(dialog,*edit); + } + return TRUE; + } + if(command!=IDOK && (!sftp || command!=testConnection)) return FALSE; + try + { + auto profile=readProfile(dialog,*edit); + if(!profile) return TRUE; + if(command==testConnection) + { + testSftp(dialog,*edit,std::move(*profile)); + return TRUE; + } + auto &settings=transferProfiles(profile->protocol); + auto updated=settings.rows; + if(edit->index) updated[*edit->index]=std::move(*profile); + else updated.push_back(std::move(*profile)); + if(saveTransferProfiles(edit->profile.protocol,updated)) + { + settings.rows=std::move(updated); + SetDlgItemTextW(dialog,password,L""); + SendDlgItemMessageW(dialog,password,EM_EMPTYUNDOBUFFER,0,0); FilesModalDialog::finish(dialog,IDOK); return TRUE; } } catch(const std::exception &) {} - showFilesNotice(dialog,L"Could not save the FTP connection.",L"FTP connection"); + const auto title=connectionTitle(edit->profile.protocol); + showFilesNotice(dialog,(L"Could not save the "+title+L".").c_str(),title.c_str()); return TRUE; } } -void editFtpProfile(Panel &panel,bool create) +void editTransferProfile(Panel &panel,bool create) { - ftpDialog::Edit edit; + transferDialog::Edit edit; + const auto protocol=panel.ftp->protocol; + const auto &profiles=transferProfiles(protocol).rows; + edit.profile.protocol=protocol; + if(protocol==TransferProtocol::sftp) edit.profile.port=defaultSftpPort; if(!create) { const auto row=currentPanelRow(panel); - if(row<0 || static_cast(row)>=ftpProfiles.size()) return; + if(row<0 || static_cast(row)>=profiles.size()) return; edit.index=static_cast(row); - edit.profile=ftpProfiles[*edit.index]; + edit.profile=profiles[*edit.index]; + edit.pinnedHost=edit.profile.host; + edit.pinnedPort=edit.profile.port; + edit.pin=edit.profile.hostFingerprint; } const auto owner=GetParent(panel.list); - if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(112),owner, - ftpDialog::procedure,reinterpret_cast(&edit))!=IDOK) return; + const auto resource=protocol==TransferProtocol::sftp?124:112; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(resource),owner, + transferDialog::procedure,reinterpret_cast(&edit))!=IDOK) return; for(auto &other:panels) { - if(!ftpProfileList(other) || other.scan.valid()) continue; - const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(ftpProfiles.size()-1)):fs::path{}; - showFtpProfiles(other,selection); + if(!transferProfileList(other) || other.ftp->protocol!=protocol || other.scan.valid()) continue; + const auto selection=&other==&panel?ftpRoot/std::to_wstring(edit.index.value_or(profiles.size()-1)):fs::path{}; + showTransferProfiles(other,protocol,selection); } } diff --git a/src/files_main.cpp b/src/files_main.cpp index 7020fb8..14d96e6 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -1,3 +1,5 @@ +#include +#include #include #include #include @@ -29,6 +31,9 @@ #include #include #include +#include +#include +#include #include "files_terminal.h" #include "files_archive.h" #include "files_compare_text.h" @@ -46,6 +51,7 @@ #include "files_terminal_view.h" #include "files_lan_ipc.h" #include "lan_files.h" +#include "lan_network.h" #include "lan_wake.h" #include "platform.h" #include "../resources/resource.h" @@ -366,6 +372,8 @@ FolderSize measureFolder(const fs::path &root,std::stop_token stop,const ListDir constexpr auto schemeKey = L"Software\\KSwitcher\\Files"; #include "files_registry_json.inl" #include "files_ftp.inl" +#include "files_sftp.inl" +#include "files_transfer.inl" fs::path folderPathWithoutSeparator(fs::path path) @@ -384,7 +392,22 @@ fs::path panelParentPath(const fs::path &directory,bool local) return parent; } -enum class FolderProvider { local, ftp, lan }; +enum class FolderProvider { local, ftp, lan, sftp }; + +bool isTransferFolder(FolderProvider provider) +{ + return provider==FolderProvider::ftp || provider==FolderProvider::sftp; +} + +FolderProvider transferFolderProvider(TransferProtocol protocol) +{ + return protocol==TransferProtocol::sftp?FolderProvider::sftp:FolderProvider::ftp; +} + +TransferProtocol folderTransferProtocol(FolderProvider provider) +{ + return provider==FolderProvider::sftp?TransferProtocol::sftp:TransferProtocol::ftp; +} struct FolderLocation { @@ -398,7 +421,7 @@ struct FolderLocation bool sameFolderPath(const fs::path &a,const fs::path &b,FolderProvider provider) { - return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,provider==FolderProvider::ftp?FALSE:TRUE)==CSTR_EQUAL; + return CompareStringOrdinal(a.c_str(),-1,b.c_str(),-1,isTransferFolder(provider)?FALSE:TRUE)==CSTR_EQUAL; } bool sameFolderLocation(const FolderLocation &a,const FolderLocation &b) @@ -526,6 +549,7 @@ struct RemotePanelLocation std::string ftpProfile; std::optional peer; std::optional navigationPosition; + TransferProtocol protocol{}; }; struct Panel @@ -534,7 +558,7 @@ struct Panel fs::path directory; FolderNavigation navigation; std::optional peer; - std::optional ftp; + std::optional ftp; std::optional archive; struct DirectoryWatch { @@ -583,7 +607,7 @@ struct Panel bool offerElevation{}; uint64_t statusRevision{}; std::shared_ptr elevated; - std::optional ftp; + std::optional ftp; std::optional find; std::optional navigationPosition; std::optional archive; @@ -650,14 +674,14 @@ struct Panel std::array longestColumn{}; ColumnMetadataMap columnMetadata; }; -bool ftpProfileList(const Panel &panel) +bool transferProfileList(const Panel &panel) { return panel.ftp && panel.ftp->name.empty(); } FolderLocation folderLocation(const Panel &panel,const fs::path &directory) { - if(panel.ftp) return {directory,FolderProvider::ftp,panel.ftp->id,panel.ftp->name}; + if(panel.ftp) return {directory,transferFolderProvider(panel.ftp->protocol),panel.ftp->id,panel.ftp->name}; if(panel.peer) return {directory,FolderProvider::lan,panel.peer->id,panel.peer->name}; return {directory}; } @@ -665,7 +689,7 @@ FolderLocation folderLocation(const Panel &panel,const fs::path &directory) std::wstring panelLocation(const Panel &panel) { if(panel.ftp) - return ftpProfileList(panel)?L"FTP":panel.ftp->name+L" · "+ftpPath(panel.directory); + return transferProfileList(panel)?transferProtocolName(panel.ftp->protocol):panel.ftp->name+L" · "+ftpPath(panel.directory); return (panel.peer?panel.peer->name+L" · ":std::wstring{})+panel.directory.native(); } @@ -680,7 +704,7 @@ DWORD effectivePanelColumns(const Panel &panel) bool hasPanelColumns(const Panel &panel) { - return detailedPanel(panel) && !panel.findOrigin && !ftpProfileList(panel); + return detailedPanel(panel) && !panel.findOrigin && !transferProfileList(panel); } std::wstring panelCaption(const Panel &panel) @@ -2061,10 +2085,11 @@ void copyPanelNames(HWND owner) { const auto &panel=panels[active]; std::wstring names; - if(ftpProfileList(panel)) + if(transferProfileList(panel)) { const auto row=currentPanelRow(panel); - if(row>=0 && static_cast(row)protocol).rows; + if(row>=0 && static_cast(row)protocol)+L" panels."); return false; } if(remoteCommandRunning) @@ -2586,9 +2611,10 @@ void showFileDetails(const Panel &panel) L" · Enter: Go · Esc: Back"); return; } - if(ftpProfileList(panel)) + if(transferProfileList(panel)) { - setStatus(ftpProfiles.empty()?L"Shift+F4 New connection":L"Shift+F4 New F4 Edit Enter Connect"); + setStatus(transferProfiles(panel.ftp->protocol).rows.empty()?L"Shift+F4 New connection": + L"Shift+F4 New F4 Edit Enter Connect"); return; } auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0); @@ -2692,9 +2718,9 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque { try { - FtpSession ftp(*request.ftp); + TransferSession ftp(*request.ftp); if(directory.empty()) ftpInitialDirectory=ftp.initialDirectory(); - error=listFtpDirectory(ftp,directory.empty()?ftpInitialDirectory:directory,[&](const fs::path &path,const FileInfo &info) + error=ftp.list(directory.empty()?ftpInitialDirectory:directory,[&](const fs::path &path,const FileInfo &info) { if(!metadata.emplace(path,FolderEntryMetadata{info.attributes,info.size,info.modified}).second) return true; (info.attributes&FILE_ATTRIBUTE_DIRECTORY?folders:files).push_back(path); @@ -2707,7 +2733,7 @@ std::unique_ptr scanDirectory(const Panel::ScanRequest &reque catch(const std::system_error &e) { error=static_cast(e.code().value()); - failure=ftpFolderError(e)+L" ("+request.ftp->name+L")"; + failure=(request.ftp->protocol==TransferProtocol::sftp?fileError(e):ftpFolderError(e))+L" ("+request.ftp->name+L")"; } catch(const std::exception &e) { @@ -2801,10 +2827,10 @@ void refreshTreeBranches(Panel &panel); void replaceTreeRoot(Panel &panel,Panel::ScanResult &scan,bool sameDirectory,const std::set &marks); void appendTreeRows(Panel &panel,PanelRowsUpdate &rows); -bool samePanelSource(const Panel &panel,const std::optional &peer,const std::optional &ftp) +bool samePanelSource(const Panel &panel,const std::optional &peer,const std::optional &ftp) { return (panel.peer?panel.peer->id:std::string{})==(peer?peer->id:std::string{}) && - panel.ftp.has_value()==ftp.has_value() && (!panel.ftp || panel.ftp->id==ftp->id); + panel.ftp.has_value()==ftp.has_value() && (!panel.ftp || (panel.ftp->protocol==ftp->protocol && panel.ftp->id==ftp->id)); } bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResult &scan) @@ -2812,7 +2838,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul const auto &directory=scan.ftpInitialDirectory.empty()?request.directory:scan.ftpInitialDirectory; auto &peer=request.peer; const auto previousDirectory=samePanelSource(panel,peer,request.ftp)?panel.directory:fs::path{}; - const auto provider=peer?FolderProvider::lan:request.ftp?FolderProvider::ftp:FolderProvider::local; + const auto provider=peer?FolderProvider::lan:request.ftp?transferFolderProvider(request.ftp->protocol):FolderProvider::local; const bool sameDirectory=sameFolderPath(previousDirectory,directory,provider); auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=scan; const bool partial=error==ERROR_CANCELLED; @@ -2923,7 +2949,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul panel.watch.reset(); std::swap(panel.watch.handle,nextWatch.handle); } - const bool profiles=ftpProfileList(panel); + const bool profiles=transferProfileList(panel); if(!finding && !panel.archive && !profiles) { auto location=folderLocation(panel,directory); @@ -2947,7 +2973,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul const auto parent=finding?fs::path{}:panel.archive?directory.parent_path(): panelParentPath(directory,!panel.peer && !panel.ftp); const bool hasParent=!parent.empty(); - const auto rowCount=profiles?ftpProfiles.size():finding?files.size(): + const auto rowCount=profiles?transferProfiles(panel.ftp->protocol).rows.size():finding?files.size(): renderTree?panel.tree.branches.at(panel.tree.root).ordered.size()+hasParent:ordered.size()+hasParent; PanelRowsUpdate rows(panel,rowCount); const auto add=[&](const fs::path &path,const std::wstring &label,bool folder) @@ -2957,8 +2983,9 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul }; if(profiles) { - for(size_t i=0;iprotocol).rows; + for(size_t i=0;i peer, - fs::path selection={},fs::path fallback={},std::optional ftp={}, + fs::path selection={},fs::path fallback={},std::optional ftp={}, std::optional navigationPosition={},std::optional archive={}, unsigned reconnectAttempt=0,fs::path fallbackSelection={}) { @@ -3105,7 +3132,8 @@ void collectDirectoryScans() if(!result->failure.empty() && (request.peer || usesFtp) && !panel.scanStop.stop_requested()) { retry=Panel::RemoteRetry{{request.directory,request.selection,usesFtp?request.ftp->id:std::string{}, - request.peer,request.navigationPosition},result->failure,0,request.reconnectAttempt}; + request.peer,request.navigationPosition,usesFtp?request.ftp->protocol:TransferProtocol::ftp}, + result->failure,0,request.reconnectAttempt}; if(request.peer && transientLanError(result->error) && retry->reconnectAttemptretryAt=GetTickCount64()+lanRetryDelays[retry->reconnectAttempt]; } @@ -3150,7 +3178,7 @@ void parentArchive(Panel &panel) bool panelViewAvailable(const Panel &panel) { - return !panel.findOrigin && !ftpProfileList(panel) && !panel.directory.empty() && + return !panel.findOrigin && !transferProfileList(panel) && !panel.directory.empty() && (!panel.scanRequest || !panel.scanRequest->find); } @@ -3274,9 +3302,11 @@ void revealLocalFile(Panel &panel,const fs::path &path) openOn(panel,path.parent_path(),false,{},path); } -void showFtpProfiles(Panel &panel,fs::path selection={}) +void showTransferProfiles(Panel &panel,TransferProtocol protocol,fs::path selection={}) { - openOn(panel,ftpRoot,false,{},std::move(selection),{},FtpProfile{}); + TransferProfile root; + root.protocol=protocol; + openOn(panel,ftpRoot,false,{},std::move(selection),{},std::move(root)); } void selectPanelPath(Panel &panel,const fs::path &path) @@ -3398,10 +3428,10 @@ bool queueFolderMeasurements(Panel &panel,const std::vector &folders,b }; if(ftp) { - FtpSession host(*ftp); + TransferSession host(*ftp); measure([&](const fs::path &directory,const FileVisitor &visit) { - return listFtpDirectory(host,directory,visit,stop)==ERROR_NO_MORE_FILES; + return host.list(directory,visit,stop)==ERROR_NO_MORE_FILES; }); } else @@ -3436,7 +3466,7 @@ bool queueFolderMeasurements(Panel &panel,const std::vector &folders,b void queueAutomaticPanelSizes(Panel &panel,bool refresh) { - if(!panel.view.automaticSizes || panel.findOrigin || ftpProfileList(panel)) return; + if(!panel.view.automaticSizes || panel.findOrigin || transferProfileList(panel)) return; std::vector folders; for(size_t i=0;i(drivePaths.size())+1;} -LRESULT smbDriveRow() {return lanDrivePicker?-1:ftpDriveRow()+1;} +LRESULT sftpDriveRow() {return lanDrivePicker?-1:ftpDriveRow()+1;} +LRESULT smbDriveRow() {return lanDrivePicker?-1:sftpDriveRow()+1;} LRESULT recentDriveRow() {return lanDrivePicker?-1:smbDriveRow()+1;} LRESULT lanHeaderRow() {return recentDriveRow()+1;} void showRecentFolders(int side); @@ -3601,7 +3632,7 @@ void showSmbProfiles(Panel &panel); bool driveSourceRow(LRESULT row) { return row>=0 && (row(drivePaths.size()) || row==ftpDriveRow() || - row==smbDriveRow() || row==recentDriveRow()); + row==sftpDriveRow() || row==smbDriveRow() || row==recentDriveRow()); } bool selectablePickerRow(LRESULT row) @@ -3660,14 +3691,15 @@ void selectDrive() } if(row>=0 && static_cast(row)(label.c_str())); } - if(panels[index].ftp) selected=static_cast(ftpDriveRow()); + if(const auto &profile=panels[index].ftp) selected=static_cast( + profile->protocol==TransferProtocol::sftp?sftpDriveRow():ftpDriveRow()); if(dc) { if(oldFont) SelectObject(dc,oldFont); @@ -4286,7 +4320,7 @@ bool handleQuickViewKey(HWND window,const MSG &message) return true; } -ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile); +ks::files::RemoteTextSource transferTextSource(const TransferProfile &profile); void openPanelImage(const Panel &panel,const fs::path &path,const ks::files::RemoteTextSource *source=nullptr) { @@ -4324,7 +4358,7 @@ void openArchiveText(const Panel &panel,const fs::path &path,bool hex=false) void openSelectedText(const Panel &panel, bool edit, bool external,bool hex) { - if(ftpProfileList(panel)) return; + if(transferProfileList(panel)) return; const auto row=currentPanelRow(panel); if(row==LB_ERR || panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") return; if(panel.archive) @@ -4341,7 +4375,7 @@ void openSelectedText(const Panel &panel, bool edit, bool external,bool hex) const auto &path=panel.rows[row]; if(panel.ftp) { - const auto ftp=ftpTextSource(*panel.ftp); + const auto ftp=transferTextSource(*panel.ftp); if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path,&ftp); else ks::files::openRemoteTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(),ftp,{},false,{.hex=hex}); return; @@ -4359,10 +4393,10 @@ void enter(Panel &panel) const auto row=currentPanelRow(panel); if(row!=LB_ERR) { - if(ftpProfileList(panel)) + if(transferProfileList(panel)) { - if(static_cast(row)protocol).rows; + if(static_cast(row)(value.size()))); if(request.ftpRename) { - if(!validFtpCopyName(value,true)) showError(L"Enter a new name in the current FTP folder."); + if(!validFtpCopyName(value,true)) showError(L"Enter a new name in the current remote folder."); else if(value==request.sources.front().filename().native()) FilesModalDialog::finish(dialog,IDCANCEL); else { @@ -5979,24 +6013,25 @@ FileEntries childrenOf(FilesConnection &host,const fs::path &path) #include "files_ftp_copy.inl" #include "files_compare.inl" -ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile) +ks::files::RemoteTextSource transferTextSource(const TransferProfile &profile) { - auto identity=Json::array({"ftp",ks::utf8(ks::lower(profile.host)),profile.port,ks::utf8(profile.user)}).dump(); + auto identity=Json::array({ks::utf8(transferProtocolName(profile.protocol)),ks::utf8(ks::lower(profile.host)), + profile.port,ks::utf8(profile.user)}).dump(); return {std::move(identity),profile.name, [profile](const fs::path &path,const fs::path &cache,bool edit, const ks::files::RemoteTextSource::Progress &progress,uint64_t limit) { requireFileOperation(!progress || progress(0,0),ERROR_CANCELLED); - FtpSession ftp(profile); - const auto info=ftpEntry(ftpChildren(ftp,path.parent_path()),path); + TransferSession ftp(profile); + const auto info=transferEntry(transferChildren(ftp,path.parent_path()),path); requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND); requireFileOperation(!(info->attributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)), ERROR_NOT_SUPPORTED); const bool editable=!(info->attributes&FILE_ATTRIBUTE_READONLY); - if(edit && !editable) throw std::runtime_error("The FTP file is read-only."); + if(edit && !editable) throw std::runtime_error("The "+ks::utf8(transferProtocolName(profile.protocol))+" file is read-only."); if(info->size>limit) throw std::system_error(ERROR_FILE_TOO_LARGE,std::system_category()); FilesConnection local; - downloadFtpFile(ftp,local,path,cache,*info,false,progress); + downloadTransferFile(ftp,local,path,cache,*info,false,progress); return ks::files::RemoteTextRevision{info->size,info->modified,editable}; }, [profile](const fs::path &path,const fs::path &cache,const ks::files::RemoteTextRevision &expected) @@ -6004,8 +6039,8 @@ ks::files::RemoteTextSource ftpTextSource(const FtpProfile &profile) FilesConnection local; const auto info=statFile(local,cache); requireFileOperation(info.has_value(),ERROR_FILE_NOT_FOUND); - FtpSession ftp(profile); - const auto result=uploadFtpFile(local,ftp,cache,path,*info,true, + TransferSession ftp(profile); + const auto result=uploadTransferFile(local,ftp,cache,path,*info,true, [](uint64_t,uint64_t){return true;},&expected); return ks::files::RemoteTextRevision{result.size,result.modified,expected.editable}; }}; @@ -6050,12 +6085,12 @@ void transferFile(const CopyEndpoints &hosts,const fs::path &from,const fs::path }; if(hosts.source.ftp) { - downloadFtpFile(*hosts.source.ftp,*hosts.target.files,from,to,info,replace,update); + downloadTransferFile(*hosts.source.ftp,*hosts.target.files,from,to,info,replace,update); return; } if(hosts.target.ftp) { - uploadFtpFile(*hosts.source.files,*hosts.target.ftp,from,to,info,replace,update); + uploadTransferFile(*hosts.source.files,*hosts.target.ftp,from,to,info,replace,update); hosts.target.listedDirectory.clear(); return; } @@ -6264,7 +6299,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve fs::path targetFolder={}) { const auto sourceFtp=source.ftp; - const bool ftpRename=move && sourceFtp && !ftpProfileList(source); + const bool ftpRename=move && sourceFtp && !transferProfileList(source); const auto archive=source.archive?source.archive->file:fs::path{}; auto archiveDirectory=archive.empty()?fs::path{}:source.directory.lexically_relative(archive); if(archiveDirectory==L".") archiveDirectory.clear(); @@ -6299,9 +6334,9 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve const auto destinationFtp=ftpRename?sourceFtp:destination.ftp; const bool ftp=sourceFtp || destinationFtp; if(ftp && !ftpRename && (move || (sourceFtp && destinationFtp) || source.peer || destination.peer || - ftpProfileList(source) || ftpProfileList(destination))) + transferProfileList(source) || transferProfileList(destination))) { - setStatus(L"F5 copies between a local folder and a connected FTP folder."); + setStatus(L"F5 copies between a local folder and a connected FTP or SFTP folder."); return; } if(copyInProgress) @@ -6327,7 +6362,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve if(request.sources.empty()) return; if(ftpRename && request.sources.size()!=1) { - setStatus(L"Select one FTP file or folder to rename."); + setStatus(L"Select one remote file or folder to rename."); return; } const auto result=FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(ftpRename?113:102),owner,copyDialog, @@ -6401,7 +6436,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve })) throw std::system_error(ERROR_ALREADY_EXISTS,std::system_category()); if(progress.canceled) return; - renameFtpEntry(*sourceHost.ftp,path,target); + sourceHost.ftp->rename(path,target); ++copied; ++progress.files; ++progress.totalFiles; @@ -6690,7 +6725,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) setStatus(L"Wait for the search to finish."); return; } - if(ftpProfileList(panel)) return; + if(transferProfileList(panel)) return; if(copyInProgress) return; const auto ftp=panel.ftp; permanent=permanent || ftp.has_value(); @@ -7359,7 +7394,7 @@ void openOrCreateText(HWND owner,const Panel &panel) {prompt.format.encoding,draft}); } -void editFtpProfile(Panel &panel,bool create); +void editTransferProfile(Panel &panel,bool create); #include "files_drag_drop.inl" @@ -7510,9 +7545,9 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT if (wp == VK_F3 || wp == VK_F4) { auto &panel=panels[index]; - if(ftpProfileList(panel)) + if(transferProfileList(panel)) { - if(wp==VK_F4) editFtpProfile(panel,false); + if(wp==VK_F4) editTransferProfile(panel,false); return 0; } const auto row=currentPanelRow(panel); @@ -7771,8 +7806,8 @@ void searchPanelByPrefix(HWND window,wchar_t character) for(size_t row=0;length && rowprotocol).rows:nullptr; + const auto name=profiles && rowsize()?(*profiles)[row].name:panel.rows[row].filename().native(); if(name.size() savedFtpPanelLocation(int index) void saveFtpPanelLocation(const Panel &panel,int index) { RemotePanelLocation location; - if(panel.ftp && !panel.ftp->id.empty()) + if(panel.ftp && panel.ftp->protocol==TransferProtocol::ftp && !panel.ftp->id.empty()) { const auto row=currentPanelRow(panel); location={panel.directory,row<0?fs::path{}:panel.rows[row],panel.ftp->id}; } - else if(panel.remoteRetry && !panel.remoteRetry->location.ftpProfile.empty()) + else if(panel.remoteRetry && panel.remoteRetry->location.protocol==TransferProtocol::ftp && + !panel.remoteRetry->location.ftpProfile.empty()) location=panel.remoteRetry->location; - else if(panel.scanRequest && panel.scanRequest->ftp) + else if(panel.scanRequest && panel.scanRequest->ftp && panel.scanRequest->ftp->protocol==TransferProtocol::ftp) location={panel.scanRequest->directory,panel.scanRequest->selection,panel.scanRequest->ftp->id}; const auto key=ftpPanelLocationKeys[index]; diff --git a/src/files_panel_rows.inl b/src/files_panel_rows.inl index 5ef9c2b..b067c65 100644 --- a/src/files_panel_rows.inl +++ b/src/files_panel_rows.inl @@ -2,7 +2,7 @@ class PanelRowsUpdate { public: PanelRowsUpdate(Panel &panel,size_t count) : panel(panel),visible(IsWindowVisible(panel.list)), - profiles(ftpProfileList(panel)) + profiles(transferProfileList(panel)) { if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0); panel.rows.clear(); @@ -120,7 +120,7 @@ void visitPanelMarks(const Panel &panel,const Visitor &visit) } return; } - if(ftpProfileList(panel)) return; + if(transferProfileList(panel)) return; for(size_t i=0;i peer; - std::optional ftp; + std::optional ftp; std::wstring completionInput; std::future completion; }; @@ -167,7 +167,7 @@ fs::path enteredPanelPath(const fs::path &base,std::wstring text,bool ftp) } std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text, - const std::optional &peer,const std::optional &ftp) + const std::optional &peer,const std::optional &ftp) { const auto path=enteredPanelPath(base,text,ftp.has_value()); if(path.empty()) return {}; @@ -194,8 +194,8 @@ std::wstring panelPathCompletion(const fs::path &base,const std::wstring &text, } else if(ftp) { - FtpSession host(*ftp); - listFtpDirectory(host,directory,visit); + TransferSession host(*ftp); + host.list(directory,visit); } else { @@ -329,11 +329,11 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vectorlocations) { - auto label=location.provider==FolderProvider::ftp?ftpPath(location.directory):location.directory.native(); + auto label=isTransferFolder(location.provider)?ftpPath(location.directory):location.directory.native(); if(recent && location.provider!=FolderProvider::local) { const auto &source=location.label; - const auto kind=location.provider==FolderProvider::ftp?L"FTP":L"LAN"; + const auto kind=isTransferFolder(location.provider)?transferProtocolName(folderTransferProtocol(location.provider)):L"LAN"; label=std::wstring(kind)+L" · "+(source.empty()?std::wstring{}:source+L" · ")+label; } longest=std::max(longest,label.size()); @@ -368,12 +368,13 @@ void showRecentFolders(int side) RECT anchor{}; GetWindowRect(panels[side].path,&anchor); MapWindowPoints(nullptr,owner,reinterpret_cast(&anchor),2); - if(loadFtpProfiles()) - for(auto &location:locations) - { - if(location.provider!=FolderProvider::ftp) continue; - if(const auto *profile=findFtpProfile(location.id)) location.label=profile->name; - } + for(auto &location:locations) + { + if(!isTransferFolder(location.provider)) continue; + const auto protocol=folderTransferProtocol(location.provider); + if(loadTransferProfiles(protocol)) + if(const auto *profile=findTransferProfile(location.id,protocol)) location.label=profile->name; + } showFolderPicker(owner,side,L"Recent folders",std::move(locations),anchor,true); } @@ -426,8 +427,10 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_ if(panel.peer) chooseDrive(index,false,true); else { - const auto *profile=findFtpProfile(panel.ftp->id); - showFtpProfiles(panel,profile?ftpRoot/std::to_wstring(profile-ftpProfiles.data()):fs::path{}); + const auto protocol=panel.ftp->protocol; + const auto *profile=findTransferProfile(panel.ftp->id,protocol); + showTransferProfiles(panel,protocol,profile? + ftpRoot/std::to_wstring(profile-transferProfiles(protocol).rows.data()):fs::path{}); } break; case PathAction::ancestors: case PathAction::previous: showHiddenPathParts(window,index,part); break; diff --git a/src/files_recent_folders.inl b/src/files_recent_folders.inl index f6bef21..ff70d58 100644 --- a/src/files_recent_folders.inl +++ b/src/files_recent_folders.inl @@ -9,6 +9,7 @@ std::optional readRecentFolder(const Json &entry) { const auto source=entry.value("source",std::string{}); if(source=="ftp") location.provider=FolderProvider::ftp; + else if(source=="sftp") location.provider=FolderProvider::sftp; else if(source=="lan") location.provider=FolderProvider::lan; else return {}; location.id=entry.at("id").get(); @@ -19,7 +20,7 @@ std::optional readRecentFolder(const Json &entry) else return {}; const auto &path=location.directory; if(path.native().find(L'\0')!=std::wstring::npos) return {}; - if(location.provider==FolderProvider::ftp) + if(isTransferFolder(location.provider)) { if(!isFtpFolderPath(path)) return {}; } @@ -65,7 +66,8 @@ bool updateRecentFolders(const FolderLocation &location,bool remember) { const auto path=ks::utf8(folder.directory.native()); if(folder.provider==FolderProvider::local) data.push_back(path); - else data.push_back({{"source",folder.provider==FolderProvider::ftp?"ftp":"lan"},{"id",folder.id}, + else data.push_back({{"source",folder.provider==FolderProvider::ftp?"ftp": + folder.provider==FolderProvider::sftp?"sftp":"lan"},{"id",folder.id}, {"label",ks::utf8(folder.label)},{"path",path}}); } saved=writeFilesJsonPreference(recentFoldersKey,data); diff --git a/src/files_sftp.inl b/src/files_sftp.inl new file mode 100644 index 0000000..d7557d3 --- /dev/null +++ b/src/files_sftp.inl @@ -0,0 +1,255 @@ +constexpr long sftpTimeoutMs=10000; + +void initializeSsh() +{ + static const auto initialized=libssh2_init(0); + if(initialized) throw std::runtime_error("Could not initialize the SSH client."); +} + +void connectSftpSocket(ks::lan::WinSocket &connection,const TransferProfile &profile) +{ + ADDRINFOW query{}; + query.ai_socktype=SOCK_STREAM; + query.ai_protocol=IPPROTO_TCP; + ADDRINFOW *addresses{}; + const auto service=std::to_wstring(profile.port); + if(const auto error=GetAddrInfoW(profile.host.c_str(),service.c_str(),&query,&addresses)) + throw std::system_error(error,std::system_category()); + const std::unique_ptr resolved(addresses,FreeAddrInfoW); + DWORD lastError=WSAEHOSTUNREACH; + const auto deadline=GetTickCount64()+sftpTimeoutMs; + for(auto *address=addresses;address;address=address->ai_next) + { + ks::lan::WinSocket socket{::socket(address->ai_family,address->ai_socktype,address->ai_protocol)}; + if(socket.value==INVALID_SOCKET) {lastError=WSAGetLastError();continue;} + u_long nonblocking=1; + if(ioctlsocket(socket.value,FIONBIO,&nonblocking)==SOCKET_ERROR) + {lastError=WSAGetLastError();continue;} + if(::connect(socket.value,address->ai_addr,static_cast(address->ai_addrlen))==SOCKET_ERROR) + { + lastError=WSAGetLastError(); + if(lastError!=WSAEWOULDBLOCK) continue; + const auto now=GetTickCount64(); + if(now>=deadline) {lastError=WSAETIMEDOUT;break;} + const auto left=deadline-now; + timeval timeout{static_cast(left/1000),static_cast(left%1000)*1000}; + fd_set writable{},failed{}; + FD_SET(socket.value,&writable); + FD_SET(socket.value,&failed); + const auto ready=select(0,nullptr,&writable,&failed,&timeout); + if(ready==SOCKET_ERROR) {lastError=WSAGetLastError();continue;} + if(!ready) {lastError=WSAETIMEDOUT;break;} + int error{},length=sizeof(error); + if(getsockopt(socket.value,SOL_SOCKET,SO_ERROR,reinterpret_cast(&error),&length)==SOCKET_ERROR) + {lastError=WSAGetLastError();continue;} + if(error) {lastError=error;continue;} + } + nonblocking=0; + if(ioctlsocket(socket.value,FIONBIO,&nonblocking)==SOCKET_ERROR) + {lastError=WSAGetLastError();continue;} + connection.value=std::exchange(socket.value,INVALID_SOCKET); + return; + } + throw std::system_error(lastError,std::system_category()); +} + +struct SftpFile +{ + LIBSSH2_SFTP_HANDLE *handle{}; + explicit SftpFile(LIBSSH2_SFTP_HANDLE *value):handle(value){} + SftpFile(const SftpFile &)=delete; + SftpFile(SftpFile &&other) noexcept:handle(std::exchange(other.handle,nullptr)){} + ~SftpFile(){if(handle) libssh2_sftp_close_handle(handle);} +}; + +class SftpSession +{ + ks::lan::Network network_; + ks::lan::WinSocket socket_; + std::unique_ptr session_{nullptr,libssh2_session_free}; + std::unique_ptr sftp_{nullptr,libssh2_sftp_shutdown}; + std::string fingerprint_; + + [[noreturn]] void sshError(const char *operation) const + { + char *message{}; + int length{}; + libssh2_session_last_error(session_.get(),&message,&length,0); + throw std::runtime_error(std::string(operation)+(message && length>0?": "+std::string(message,length):"")); + } + + void authenticate(const TransferProfile &profile) + { + auto wideSecret=transferPassword(profile); + struct EraseWide + { + std::wstring &text; + ~EraseWide(){if(!text.empty()) SecureZeroMemory(text.data(),text.size()*sizeof(wchar_t));} + } eraseWide{wideSecret}; + auto secret=ks::utf8(wideSecret); + struct EraseText + { + std::string &text; + ~EraseText(){if(!text.empty()) SecureZeroMemory(text.data(),text.size());} + } eraseSecret{secret}; + const auto user=ks::utf8(profile.user); + int result{}; + if(profile.privateKey.empty()) + result=libssh2_userauth_password_ex(session_.get(),user.c_str(),static_cast(user.size()), + secret.c_str(),static_cast(secret.size()),nullptr); + else + { + auto key=ks::readFile(profile.privateKey,1024*1024); + struct EraseKey + { + ks::Bytes &bytes; + ~EraseKey(){if(!bytes.empty()) SecureZeroMemory(bytes.data(),bytes.size());} + } eraseKey{key}; + if(key.empty()) throw std::runtime_error("Could not read the SFTP private key file."); + auto publicPath=profile.privateKey; + publicPath+=L".pub"; + ks::Bytes publicKey; + std::error_code error; + if(fs::exists(publicPath,error)) publicKey=ks::readFile(publicPath,64*1024); + result=libssh2_userauth_publickey_frommemory(session_.get(),user.c_str(),user.size(), + publicKey.empty()?nullptr:reinterpret_cast(publicKey.data()),publicKey.size(), + reinterpret_cast(key.data()),key.size(),secret.c_str()); + } + if(result) sshError(profile.privateKey.empty()?"SFTP password authentication failed": + "SFTP key authentication failed (use RSA PEM without a passphrase, or ECDSA OpenSSH with its .pub file)"); + } + + static std::string encode(const fs::path &path) {return ks::utf8(ftpPath(path));} + +public: + explicit SftpSession(const TransferProfile &profile,bool probeOnly=false) + { + if(!probeOnly && profile.hostFingerprint.empty()) + throw std::runtime_error("The SFTP host key is untrusted. Edit the profile and use Test connection to verify it."); + initializeSsh(); + connectSftpSocket(socket_,profile); + session_.reset(libssh2_session_init()); + if(!session_) throw std::runtime_error("Could not create an SSH session."); + libssh2_session_set_timeout(session_.get(),sftpTimeoutMs); + libssh2_session_set_read_timeout(session_.get(),sftpTimeoutMs/1000); + if(libssh2_session_method_pref(session_.get(),LIBSSH2_METHOD_HOSTKEY, + "ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,rsa-sha2-512,rsa-sha2-256") || + libssh2_session_handshake(session_.get(),socket_.value)) + sshError("Could not negotiate an SSH connection"); + const auto digest=reinterpret_cast(libssh2_hostkey_hash(session_.get(),LIBSSH2_HOSTKEY_HASH_SHA256)); + if(!digest) throw std::runtime_error("The server did not provide a verifiable SSH host key."); + char fingerprint[64]{}; + DWORD length=static_cast(std::size(fingerprint)); + checkFileOperation(CryptBinaryToStringA(digest,32,CRYPT_STRING_BASE64|CRYPT_STRING_NOCRLF,fingerprint,&length)); + auto encoded=std::string(fingerprint); + while(encoded.ends_with('=')) encoded.pop_back(); + fingerprint_="SHA256:"+encoded; + if(probeOnly) return; + if(!ks::lan::equal(fingerprint_,profile.hostFingerprint)) + throw std::runtime_error("The SFTP host key changed. Connection blocked before authentication. Received "+fingerprint_+"."); + authenticate(profile); + sftp_.reset(libssh2_sftp_init(session_.get())); + if(!sftp_) sshError("Could not start the SFTP subsystem"); + } + + const std::string &fingerprint() const {return fingerprint_;} + + [[noreturn]] void operationError(const char *operation) const + { + if(libssh2_session_last_errno(session_.get())==LIBSSH2_ERROR_SFTP_PROTOCOL) + { + const auto status=libssh2_sftp_last_error(sftp_.get()); + if(status==LIBSSH2_FX_PERMISSION_DENIED) + throw std::system_error(ERROR_ACCESS_DENIED,std::system_category(),operation); + if(status==LIBSSH2_FX_NO_SUCH_FILE || status==LIBSSH2_FX_NO_SUCH_PATH) + throw std::system_error(ERROR_FILE_NOT_FOUND,std::system_category(),operation); + if(status==LIBSSH2_FX_FILE_ALREADY_EXISTS) + throw std::system_error(ERROR_ALREADY_EXISTS,std::system_category(),operation); + if(status==LIBSSH2_FX_OP_UNSUPPORTED) + throw std::system_error(ERROR_NOT_SUPPORTED,std::system_category(),operation); + } + sshError(operation); + } + + fs::path initialDirectory() const + { + std::array path{}; + const auto length=libssh2_sftp_realpath(sftp_.get(),".",path.data(),path.size()); + if(length<=0) operationError("Could not resolve the initial SFTP folder"); + auto value=fs::path(ks::wide(std::string(path.data(),length))).lexically_normal(); + if(!isFtpFolderPath(value)) throw std::runtime_error("The server returned an invalid SFTP folder path."); + return value; + } + + DWORD list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop={}) const + { + if(stop.stop_requested()) return ERROR_CANCELLED; + const auto path=encode(directory); + const SftpFile folder(libssh2_sftp_open_ex(sftp_.get(),path.c_str(),static_cast(path.size()), + 0,0,LIBSSH2_SFTP_OPENDIR)); + if(!folder.handle) operationError("Could not open the SFTP folder"); + std::array name{}; + while(!stop.stop_requested()) + { + LIBSSH2_SFTP_ATTRIBUTES attrs{}; + const auto length=libssh2_sftp_readdir_ex(folder.handle,name.data(),name.size(),nullptr,0,&attrs); + if(length==0) return ERROR_NO_MORE_FILES; + if(length<0) operationError("Could not read the SFTP folder"); + const auto child=ks::wide(std::string(name.data(),length)); + if(child.empty() || child==L"." || child==L".." || child.find_first_of(L"/\\:\r\n")!=child.npos || + child.find(L'\0')!=child.npos) continue; + DWORD attributes=FILE_ATTRIBUTE_NORMAL; + if((attrs.flags&LIBSSH2_SFTP_ATTR_PERMISSIONS)!=0) + { + if(LIBSSH2_SFTP_S_ISDIR(attrs.permissions)) attributes=FILE_ATTRIBUTE_DIRECTORY; + else if(!LIBSSH2_SFTP_S_ISREG(attrs.permissions)) attributes=FILE_ATTRIBUTE_REPARSE_POINT; + if(!(attrs.permissions&0222)) attributes|=FILE_ATTRIBUTE_READONLY; + } + const auto modified=(attrs.flags&LIBSSH2_SFTP_ATTR_ACMODTIME)? + (uint64_t(attrs.mtime)+11644473600ULL)*10000000ULL:0; + if(!visit(directory/child,{attributes,attrs.filesize,modified})) return ERROR_CANCELLED; + } + return ERROR_CANCELLED; + } + + SftpFile open(const fs::path &path,bool write) const + { + const auto name=encode(path); + const auto flags=write?LIBSSH2_FXF_WRITE|LIBSSH2_FXF_CREAT|LIBSSH2_FXF_EXCL:LIBSSH2_FXF_READ; + SftpFile file(libssh2_sftp_open_ex(sftp_.get(),name.c_str(),static_cast(name.size()), + flags,0600,LIBSSH2_SFTP_OPENFILE)); + if(!file.handle) operationError(write?"Could not create the staged SFTP file":"Could not open the SFTP file"); + return file; + } + + void makeDirectory(const fs::path &path) const + { + const auto name=encode(path); + if(libssh2_sftp_mkdir(sftp_.get(),name.c_str(),0755)) operationError("Could not create the SFTP folder"); + } + + void remove(const fs::path &path,bool directory) const + { + const auto name=encode(path); + const auto result=directory?libssh2_sftp_rmdir(sftp_.get(),name.c_str()):libssh2_sftp_unlink(sftp_.get(),name.c_str()); + if(result) operationError("Could not remove the SFTP entry"); + } + + void rename(const fs::path &from,const fs::path &to,bool replace) const + { + const auto source=encode(from),target=encode(to); + if(replace) + { + const auto result=libssh2_sftp_posix_rename_ex(sftp_.get(),source.c_str(),source.size(), + target.c_str(),target.size()); + if(result && (result==LIBSSH2_ERROR_METHOD_NOT_SUPPORTED || + libssh2_sftp_last_error(sftp_.get())==LIBSSH2_FX_OP_UNSUPPORTED)) + throw std::runtime_error("The SFTP server does not support atomic replacement. The original file was kept."); + if(result) operationError("Could not replace the SFTP file"); + return; + } + if(libssh2_sftp_rename_ex(sftp_.get(),source.c_str(),static_cast(source.size()), + target.c_str(),static_cast(target.size()),0)) + operationError("Could not rename the SFTP entry"); + } +}; diff --git a/src/files_transfer.inl b/src/files_transfer.inl new file mode 100644 index 0000000..6df9853 --- /dev/null +++ b/src/files_transfer.inl @@ -0,0 +1,111 @@ +constexpr DWORD ftpCopyFlags=INTERNET_FLAG_TRANSFER_BINARY|INTERNET_FLAG_RELOAD|INTERNET_FLAG_NO_CACHE_WRITE; + +class TransferFile +{ + FtpHandle ftp_; + std::optional sftp_; + const SftpSession *session_{}; + +public: + explicit TransferFile(HINTERNET handle):ftp_(handle) + { + checkFileOperation(handle!=nullptr); + } + + TransferFile(SftpFile file,const SftpSession &session):sftp_(std::move(file)),session_(&session){} + + size_t read(unsigned char *data,size_t bytes) + { + if(sftp_) + { + const auto result=libssh2_sftp_read(sftp_->handle,reinterpret_cast(data),bytes); + if(result<0) session_->operationError("Could not read the SFTP file"); + return static_cast(result); + } + DWORD result{}; + checkFileOperation(InternetReadFile(ftp_.value,data,static_cast(bytes),&result)); + return result; + } + + size_t write(const unsigned char *data,size_t bytes) + { + if(sftp_) + { + const auto result=libssh2_sftp_write(sftp_->handle,reinterpret_cast(data),bytes); + if(result<0) session_->operationError("Could not write the staged SFTP file"); + return static_cast(result); + } + DWORD result{}; + checkFileOperation(InternetWriteFile(ftp_.value,data,static_cast(bytes),&result)); + return result; + } + + void close() + { + if(sftp_) + { + auto *handle=std::exchange(sftp_->handle,nullptr); + if(libssh2_sftp_close_handle(handle)) session_->operationError("Could not close the staged SFTP file"); + return; + } + checkFileOperation(InternetCloseHandle(ftp_.value)); + ftp_.value=nullptr; + } +}; + +class TransferSession +{ + std::optional ftp_; + std::optional sftp_; + +public: + explicit TransferSession(const TransferProfile &profile) + { + if(profile.protocol==TransferProtocol::sftp) sftp_.emplace(profile); + else ftp_.emplace(profile); + } + + const wchar_t *label() const {return transferProtocolName(sftp_?TransferProtocol::sftp:TransferProtocol::ftp);} + + fs::path initialDirectory() + { + return sftp_?sftp_->initialDirectory():ftp_->initialDirectory(); + } + + DWORD list(const fs::path &directory,const FileVisitor &visit,std::stop_token stop={}) + { + return sftp_?sftp_->list(directory,visit,stop):listFtpDirectory(*ftp_,directory,visit,stop); + } + + TransferFile open(const fs::path &path,bool write) + { + if(sftp_) return TransferFile(sftp_->open(path,write),*sftp_); + ftp_->setDirectory(path.parent_path()); + const auto name=ftp_->encodeName(path.filename()); + return TransferFile(FtpOpenFileA(ftp_->handle(),name.c_str(),write?GENERIC_WRITE:GENERIC_READ,ftpCopyFlags,0)); + } + + void makeDirectory(const fs::path &path) + { + if(sftp_) {sftp_->makeDirectory(path);return;} + ftp_->setDirectory(path.parent_path()); + checkFileOperation(FtpCreateDirectoryA(ftp_->handle(),ftp_->encodeName(path.filename()).c_str())); + } + + void remove(const fs::path &path,bool directory) + { + if(sftp_) {sftp_->remove(path,directory);return;} + ftp_->setDirectory(path.parent_path()); + const auto name=ftp_->encodeName(path.filename()); + checkFileOperation(directory?FtpRemoveDirectoryA(ftp_->handle(),name.c_str()): + FtpDeleteFileA(ftp_->handle(),name.c_str())); + } + + void rename(const fs::path &from,const fs::path &to,bool replace=false) + { + if(sftp_) {sftp_->rename(from,to,replace);return;} + ftp_->setDirectory(from.parent_path()); + const auto source=ftp_->encodeName(from.filename()),target=ftp_->encodeName(to.filename()); + checkFileOperation(FtpRenameFileA(ftp_->handle(),source.c_str(),target.c_str())); + } +}; diff --git a/tests/files_drive_shortcuts.ps1 b/tests/files_drive_shortcuts.ps1 index 8a66e44..30a0a1e 100644 --- a/tests/files_drive_shortcuts.ps1 +++ b/tests/files_drive_shortcuts.ps1 @@ -103,8 +103,8 @@ try { Open-Picker $side $rows = @(Read-Picker) $row = [Array]::IndexOf($rows, 'FTP') - if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'SMB' -or - $rows[$row + 2] -cne 'Recent folders' -or $rows[$row + 3] -cne 'KSwitcher LAN') { + if ($row -lt 2 -or $rows[$row - 1] -cne '' -or $rows[$row + 1] -cne 'SFTP' -or $rows[$row + 2] -cne 'SMB' -or + $rows[$row + 3] -cne 'Recent folders' -or $rows[$row + 4] -cne 'KSwitcher LAN') { throw "Source groups are missing separators in panel $side." } [void][FilesDriveShortcutTest]::SendMessage($picker, 390, [IntPtr]$row, $null) @@ -117,12 +117,14 @@ try { [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero) Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 2 } [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero) + Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 3 } + [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]40, [IntPtr]::Zero) Wait-Until { $selected = [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() - $selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 3) + $selected -ge 0 -and ($selected -lt $row -or $selected -gt $row + 4) } [void][FilesDriveShortcutTest]::PostMessage($picker, 256, [IntPtr]38, [IntPtr]::Zero) - Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 2 } + Wait-Until { [FilesDriveShortcutTest]::SendMessage($picker, 392, [IntPtr]::Zero, $null).ToInt32() -eq $row + 3 } [void][FilesDriveShortcutTest]::SendMessage($picker, 407, [IntPtr]($row - 2), $null) $bitmap = Render-Picker try { From e11e19293f0d2fce230c1c13e43d3a718148cdf1 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 18:31:36 +0200 Subject: [PATCH 27/61] Support interactive editing in the Files terminal prompt Refs #111 --- FILES-UI.md | 8 ++- resources/terminal/terminal.js | 20 +++++- src/files_command_history.inl | 12 +++- src/files_main.cpp | 109 +++++++++++++++++++++++-------- tests/files_activation.ps1 | 83 ++++++++++++++++++++++- tests/files_markdown_browser.mjs | 6 ++ 6 files changed, 202 insertions(+), 36 deletions(-) diff --git a/FILES-UI.md b/FILES-UI.md index 9fdb245..c61ef22 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -182,8 +182,12 @@ Warning і початковий фокус на No. виконує команду одразу. Коли рядок порожній, Enter відкриває поточний елемент. Якщо панелі приховано, Enter передає порожній рядок у термінал. - Якщо фокус у виводі термінала, Enter і Shift+Enter повертають його до - командного рядка й виконують відповідну дію за тими самими правилами. + У повноекранному терміналі (Ctrl+O) команда редагується в промпті + під виводом. Клік у терміналі повертає курсор у промпт. Стрілки вгору й + вниз без відкритого списку підказок переглядають спільну історію, а після + останньої команди вниз повертає чернетку. Підказки відкриваються біля + курсора. Ctrl+C перериває поточну команду, а за виділеного тексту виводу + копіює виділення. Escape з порожнім промптом також перериває команду. Локальна команда запускається в папці активної панелі, яку показано перед командним рядком. Після перемикання панелі або переходу до іншої папки наступна команда використовує нову папку навіть у вже відкритому diff --git a/resources/terminal/terminal.js b/resources/terminal/terminal.js index 3b32687..d20e4bc 100644 --- a/resources/terminal/terminal.js +++ b/resources/terminal/terminal.js @@ -4,7 +4,6 @@ const terminal = new Terminal({ fontSize: 16, cursorBlink: false, cursorInactiveStyle: 'none', - disableStdin: true, theme: { background: '#181818', foreground: '#e8e8e8' }, }); const fit = new FitAddon.FitAddon(); @@ -22,7 +21,11 @@ terminal.loadAddon(fit); const host = document.getElementById('terminal'); terminal.open(host); terminal.onSelectionChange(() => bridge.postMessage('selection:' + terminal.getSelection())); -host.addEventListener('pointerup', () => bridge.postMessage('focus-input'), true); +const prompt = message => bridge.postMessage('prompt:' + message); +host.addEventListener('pointerup', () => prompt('focus-input'), true); +terminal.onData(text => { + if (!/[\x00-\x1f\x7f]/u.test(text)) prompt('text:' + text); +}); const screen = host.querySelector('.xterm-screen'); let traceEnabled = false; let traceBudget = 4096; @@ -52,9 +55,20 @@ function anchorOutput() { currentOffset = offset; trace(2); } +const promptKeys = new Set([ + 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', + 'Tab', 'Escape', 'Delete', 'Backspace', 'F1', +]); terminal.attachCustomKeyEventHandler(event => { + if (event.isComposing) return true; + if (event.type === 'keydown' && promptKeys.has(event.key) && + !event.ctrlKey && !event.altKey && !event.shiftKey && !event.metaKey) { + prompt(event.key); + event.preventDefault(); + return false; + } if (event.type === 'keydown' && event.key === 'Enter' && !event.ctrlKey && !event.altKey && !event.metaKey) { - if (!event.repeat) bridge.postMessage(event.shiftKey ? 'shift-enter' : 'enter'); + if (!event.repeat) prompt(event.shiftKey ? 'shift-enter' : 'enter'); event.preventDefault(); return false; } diff --git a/src/files_command_history.inl b/src/files_command_history.inl index cffca7d..44f073d 100644 --- a/src/files_command_history.inl +++ b/src/files_command_history.inl @@ -95,9 +95,17 @@ void rememberCommand(const std::wstring &command) void recallCommand(size_t index) { terminalHistoryIndex=index; - SetWindowTextW(terminalInput,index terminalHistory; size_t terminalHistoryIndex{}; +std::wstring terminalHistoryDraft; constexpr UINT_PTR transferHighlightTimer=1; unsigned transferHighlightPhase{}; constexpr struct KeyBarCommand { int id; WPARAM key; const wchar_t *label; } keyBar[]{ @@ -916,6 +917,8 @@ FileRowStyle panelRowStyle(const Panel &panel,size_t row,bool cursor,bool active } void setStatus(const std::wstring &message,bool retryAction=false); void refreshCommandHistory(); +std::wstring terminalInputText(); +void suppressCurrentCompletion(); #include "files_command_history.inl" constexpr const wchar_t *panelPathKeys[]{L"LeftPath",L"RightPath"}; @@ -1618,7 +1621,7 @@ void layout(HWND window,bool activeOnly) const int detailsRight=active?width:middle-2; place(status,detailsLeft+8,panelBottom+4+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight); const auto ¤t=panels[active]; - const auto prompt=panelLocation(current)+L">"; + const auto prompt=panelLocation(current)+(terminalVisible?L"> ":L">"); SetWindowTextW(terminalPrompt,prompt.c_str()); SIZE promptExtent{static_cast(prompt.size())*cellWidth,0}; if(const auto dc=GetDC(window)) @@ -1719,7 +1722,7 @@ void showTerminal(HWND owner,bool show) void open(Panel &panel,const fs::path &directory,bool offerElevation); void restoreCommandFocus(); -void submitTerminalReturn(HWND owner,bool shift); +void handleFilesReturn(bool shift); void invalidatePanelRow(HWND list,LRESULT row) { @@ -1837,6 +1840,12 @@ std::optional currentCompletionQuery() return CompletionQuery{std::move(line),std::move(directory),first}; } +void suppressCurrentCompletion() +{ + hideCompletion(); + completionQuery=currentCompletionQuery(); +} + void showFramedList(HWND list,HWND frame,int x,int y,int width,int height,int inset) { constexpr UINT flags=SWP_NOACTIVATE|SWP_SHOWWINDOW; @@ -1915,7 +1924,10 @@ void showCompletion(HWND owner,const CompletionQuery &query,const Json &reply={} SendMessageW(completionList,LB_ADDSTRING,0,reinterpret_cast(item.label.c_str())); const int height=rows*textHeight; const int y=edit.top-height-inset; - showFramedList(completionList,completionFrame,edit.left+inset,y,width,height,inset); + POINT caret{}; + const int start=terminalVisible && GetCaretPos(&caret)? + std::clamp(edit.left+caret.x,edit.left+inset,edit.right-width-inset):edit.left+inset; + showFramedList(completionList,completionFrame,start,y,width,height,inset); } bool openCompletionHelp(HWND owner) @@ -1992,8 +2004,7 @@ bool acceptCompletion(size_t row) const auto caret=item.index+item.text.size()-1; SendMessageW(terminalInput,EM_SETSEL,caret,caret); } - hideCompletion(); - completionQuery=currentCompletionQuery(); + suppressCurrentCompletion(); return true; } @@ -2043,6 +2054,25 @@ bool copyFilesText(HWND owner,const std::wstring &value,const wchar_t *failure) return true; } +bool interruptTerminal() +{ + if(remoteCommandRunning) + { + remoteCommandThread.request_stop(); + return true; + } + if(!std::any_of(terminalCommands.begin(),terminalCommands.end(), + [](const auto &command){ return command.panel>=0; })) return false; + return terminal.write(L"\x03"); +} + +void copyOrInterruptTerminal() +{ + if(terminalSelection.empty() && (terminalVisible || !GetWindowTextLengthW(terminalInput)) && + interruptTerminal()) return; + SendMessageW(terminalInput,WM_COPY,0,0); +} + void copyTerminalText(HWND owner) { const auto value=terminalSelection.empty()?terminalInputText():terminalSelection; @@ -2200,6 +2230,36 @@ void insertCurrentPanelPath(bool nameOnly = false) reinterpret_cast(quoted.empty()?path.c_str():quoted.c_str())); } +void handleTerminalPromptInput(HWND owner,std::wstring_view action) +{ + if(GetForegroundWindow()!=owner || !commandLineAvailable(owner)) return; + SetFocus(terminalInput); + if(action==L"focus-input") return; + + if(action==L"enter" || action==L"shift-enter") + { + const bool shift=action==L"shift-enter"; + if(shift || !handleCompletionKey(VK_RETURN,0)) handleFilesReturn(shift); + return; + } + if(action.starts_with(L"text:")) + { + auto text=std::wstring(action.substr(5)); + std::erase_if(text,[](wchar_t character){ return character<32 || character==127; }); + if(!text.empty()) SendMessageW(terminalInput,EM_REPLACESEL,TRUE,reinterpret_cast(text.c_str())); + return; + } + constexpr std::pair keys[]{ + {L"ArrowLeft",VK_LEFT}, {L"ArrowRight",VK_RIGHT}, {L"ArrowUp",VK_UP}, {L"ArrowDown",VK_DOWN}, + {L"Home",VK_HOME}, {L"End",VK_END}, {L"Tab",VK_TAB}, {L"Escape",VK_ESCAPE}, + {L"Delete",VK_DELETE}, {L"Backspace",VK_BACK}, {L"F1",VK_F1}}; + const auto key=std::find_if(std::begin(keys),std::end(keys), + [action](const auto &binding){ return binding.first==action; }); + if(key==std::end(keys) || handleCompletionKey(key->second,0)) return; + const auto character=key->second==VK_BACK || key->second==VK_ESCAPE; + SendMessageW(terminalInput,character?WM_CHAR:WM_KEYDOWN,key->second,0); +} + bool ensureTerminalView(HWND owner) { if(!terminalViewRequested) @@ -2242,16 +2302,12 @@ bool ensureTerminalView(HWND owner) } terminalDirectory=directory; } - else if(message==L"focus-input") - { - if(GetForegroundWindow()==owner) SetFocus(terminalInput); - } else if(message.starts_with(L"selection:")) terminalSelection=message.substr(10); - else if(message==L"enter" || message==L"shift-enter") - submitTerminalReturn(owner,message==L"shift-enter"); + else if(message.starts_with(L"prompt:")) handleTerminalPromptInput(owner,std::wstring_view(message).substr(7)); else if(message==L"insert-path") insertCurrentPanelPath(); else if(message==L"insert-name") insertCurrentPanelPath(true); - else if(message==L"copy-command-line") SendMessageW(terminalInput,WM_COPY,0,0); + else if(message==L"copy-command-line" && GetForegroundWindow()==owner && commandLineAvailable(owner)) + copyOrInterruptTerminal(); else if(message==L"copy-command-line-or-panel-names") copyCommandLineOrPanelNames(owner); else if(message==L"refresh-panel") refreshPanel(panels[active]); else if(message==L"toggle") showTerminal(owner,!terminalVisible); @@ -2431,6 +2487,7 @@ void runCommandLine() } } terminalHistoryIndex=terminalHistory.size(); + terminalHistoryDraft.clear(); SetWindowTextW(terminalInput,L""); } @@ -2452,11 +2509,9 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U if(message==WM_CHAR && wp==VK_ESCAPE) { if(stopDirectoryScan()) return 0; - if(remoteCommandRunning && !GetWindowTextLengthW(input)) - { - remoteCommandThread.request_stop(); - return 0; - } + if(!GetWindowTextLengthW(input) && (terminalVisible || remoteCommandRunning) && + interruptTerminal()) return 0; + terminalHistoryDraft.clear(); recallCommand(terminalHistory.size()); return 0; } @@ -2501,7 +2556,7 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U } if(message==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN)) { - if(wp==VK_UP && terminalHistoryIndex) recallCommand(terminalHistoryIndex-1); + if(wp==VK_UP) recallPreviousCommand(); if(wp==VK_DOWN && terminalHistoryIndex(148),instance,nullptr); terminalInput=CreateWindowW(L"EDIT",L"",WS_CHILD|WS_VISIBLE|ES_AUTOHSCROLL, 0,0,0,0,window,nullptr,instance,nullptr); - terminalPrompt=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_VISIBLE|SS_PATHELLIPSIS, + terminalPrompt=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_VISIBLE|SS_PATHELLIPSIS|SS_NOTIFY, 0,0,0,0,window,nullptr,instance,nullptr); terminalOutput=CreateWindowW(L"STATIC",L"",WS_CHILD|WS_CLIPCHILDREN|WS_CLIPSIBLINGS, 0,0,0,0,window,reinterpret_cast(145),instance,nullptr); @@ -8155,7 +8203,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) { PAINTSTRUCT paint{}; auto dc=BeginPaint(window,&paint); - FillRect(dc,&paint.rcPaint,blue); + FillRect(dc,&paint.rcPaint,terminalVisible?terminalBackground:blue); auto border=CreateSolidBrush(colors[Frame]); for(const auto &panel:panels) { @@ -8617,6 +8665,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) resetCompletion(); } if(copyInProgress || commandHistoryWindow || FilesModalDialog::activeFor(window)) return 0; + if(reinterpret_cast(lp)==terminalPrompt && HIWORD(wp)==STN_CLICKED) + { + handleTerminalPromptInput(window,L"focus-input"); + return 0; + } if(reinterpret_cast(lp)==status && HIWORD(wp)==STN_CLICKED) { auto &panel=panels[active]; @@ -8995,7 +9048,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) else if(message.wParam=='U') swapPanels(window); else if(message.wParam==VK_RETURN) insertCurrentPanelPath(true); else if(message.wParam==VK_INSERT) copyCommandLineOrPanelNames(window); - else SendMessageW(terminalInput,WM_COPY,0,0); + else copyOrInterruptTerminal(); } continue; } diff --git a/tests/files_activation.ps1 b/tests/files_activation.ps1 index 4959033..17e76b9 100644 --- a/tests/files_activation.ps1 +++ b/tests/files_activation.ps1 @@ -34,6 +34,20 @@ public static class FilesActivationUi { [DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr dc, int x, int y); [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr window, out Rect rect); [DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); + [DllImport("user32.dll")] static extern int GetSystemMetrics(int index); + [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr window, IntPtr after, + int x, int y, int width, int height, uint flags); + + public static void SizeTerminalWindow(IntPtr window) { + var previous = SetThreadDpiAwarenessContext(new IntPtr(-4)); + try { + if (!SetWindowPos(window, IntPtr.Zero, 20, 20, GetSystemMetrics(0) - 40, + GetSystemMetrics(1) - 100, 0x14)) + throw new InvalidOperationException("Could not size the terminal test window."); + } finally { + if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous); + } + } public static uint ReadScreenCenter(IntPtr window) { var previous = SetThreadDpiAwarenessContext(new IntPtr(-4)); @@ -68,6 +82,21 @@ public static class FilesActivationUi { [DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] public static extern IntPtr Write(IntPtr window, uint msg, IntPtr w, string text); [DllImport("shell32.dll")] public static extern void SHChangeNotify(int eventId, uint flags, IntPtr first, IntPtr second); + public static bool CompletionFollowsCaret(IntPtr input, IntPtr suggestions) { + var info = new GuiInfo { Size = Marshal.SizeOf(typeof(GuiInfo)) }; + var previous = SetThreadDpiAwarenessContext(new IntPtr(-4)); + try { + Rect inputBounds, popup; + return GetGUIThreadInfo(GetWindowThreadProcessId(input, IntPtr.Zero), ref info) && + info.Caret == input && GetWindowRect(input, out inputBounds) && + GetWindowRect(suggestions, out popup) && popup.Bottom <= inputBounds.Top && + info.CaretRect.Left > 0 && + Math.Abs(inputBounds.Left + info.CaretRect.Left - popup.Left) <= 4; + } finally { + if (previous != IntPtr.Zero) SetThreadDpiAwarenessContext(previous); + } + } + public static IntPtr Focus(IntPtr window) { var info = new GuiInfo { Size = Marshal.SizeOf(typeof(GuiInfo)) }; if (!GetGUIThreadInfo(GetWindowThreadProcessId(window, IntPtr.Zero), ref info)) @@ -207,7 +236,7 @@ $extension = ".ksfiles$unique" $progId = "KSwitcher.Files.Test.$unique" $saved = @{} $profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide', - 'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement' + 'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement', 'FontPoints' $process = $null $trace = $null $webviewFlags=$env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS @@ -249,6 +278,7 @@ try { $profile.SetValue('StatusFields', 3) if($TerminalOnly){ + $profile.SetValue('FontPoints',80,'DWord') $terminalPage = Join-Path $app 'terminal/index.html' $page = Get-Content -Raw -LiteralPath $terminalPage $page = $page.Replace(' + +
+

Offline HTML fixture

+
Formatted table
+External link +Image description +
+
+"@) + $data = [byte[]]::new(5000) + [byte[]]$header = 0,1,9,10,13,27,31,32,65,127,128,255 + $header.CopyTo($data,0) + for ($i=$header.Length; $i -lt $data.Length; ++$i) { $data[$i] = 66 } + [IO.File]::WriteAllBytes((Join-Path $left.FullName 'symbols.bin'), $data) + $expectedSymbols = -join ([char[]]@(0xe000,0xe001,0xe009,0xe00a,0xe00d,0xe01b,0xe01f, + 0x20,0x41,0xe07f,0xC7,0xe0ff)) + $key.SetValue('LeftPanelMode', 1, 'DWord') + $key.SetValue('RightPanelMode', 1, 'DWord') $key.SetValue('LeftPath', $left.FullName, 'String') $key.SetValue('RightPath', $right.FullName, 'String') $key.SetValue('LeftCursor', $document, 'String') $key.DeleteValue('RightCursor', $false) $key.DeleteValue('WindowPlacement', $false) - $process = Start-Process -FilePath $exe -PassThru - Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero } - $window = $process.MainWindowHandle - Wait-Until { [FilesQuickViewProbe]::Activate($window) } - $keyboard = New-Object -ComObject WScript.Shell + $process = Start-Process -FilePath (Join-Path $app.FullName (Split-Path -Leaf $exe)) -PassThru -WindowStyle Normal + $window = Wait-Until 'the Files window' { + $process.Refresh() + if ($process.MainWindowHandle -ne [IntPtr]::Zero) { $process.MainWindowHandle } + } + [void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,1500,920,20) $leftList = [FilesQuickViewProbe]::GetDlgItem($window, 102) $rightList = [FilesQuickViewProbe]::GetDlgItem($window, 103) $rightHeading = [FilesQuickViewProbe]::GetDlgItem($window, 141) @@ -62,12 +135,16 @@ try { if (!($leftList -and $rightList -and $rightHeading -and $rightPath)) { throw 'Expected both file panels in the test window.' } - Wait-Until { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) } - $keyboard.SendKeys('^q') - Wait-Until { + [void](Wait-Until 'both panels' { [FilesQuickViewProbe]::IsWindowVisible($rightHeading) }) + Invoke-FilesCommand $window 'Quick View*' + $preview = Wait-Until 'Quick View' { $hostWindow = [FilesQuickViewProbe]::GetDlgItem($window, 158) - $hostWindow -ne [IntPtr]::Zero -and [FilesQuickViewProbe]::IsWindowVisible($hostWindow) + if ([FilesQuickViewProbe]::IsWindowVisible($hostWindow)) { $hostWindow } } + $editor = [FilesQuickViewProbe]::FindWindowEx($preview,0,'Scintilla',[NullString]::Value) + [void](Wait-Until 'the text preview' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 }) + $initialWrap = [FilesQuickViewProbe]::Send($editor,2269,0,0) + $initialScrollbar = [FilesQuickViewProbe]::Send($editor,2131,0,0) foreach ($control in $rightList, $rightHeading, $rightPath) { if ([FilesQuickViewProbe]::IsWindowVisible($control)) { throw 'A file panel control can draw over the Quick View content.' @@ -75,19 +152,75 @@ try { } if (![FilesQuickViewProbe]::IsWindowVisible($leftList)) { throw 'Quick View hid the source panel.' } - $keyboard.SendKeys('^q') - Wait-Until { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero } + Select-File 'preview.html' + $mode = [FilesQuickViewProbe]::GetDlgItem($preview,159) + [void](Wait-Until 'the HTML mode switch' { [FilesQuickViewProbe]::IsWindowVisible($mode) -and (Text $mode) -eq 'Show Source' }) + if ($browserProbe) { Browser } + [void][FilesQuickViewProbe]::Post($preview,273,159,$mode) + [void](Wait-Until 'the HTML source' { + [FilesQuickViewProbe]::IsWindowVisible($editor) -and (Text $mode) -eq 'Show Rendered' -and + (Preview-Bytes 15) -eq '' + }) + [void][FilesQuickViewProbe]::Post($editor,0x100,117,0) + [void](Wait-Until 'keyboard switch back to Rendered' { (Text $mode) -eq 'Show Source' }) + if ($browserProbe) { Browser } + if ($network.Pending()) { throw 'Rendering HTML attempted an outbound resource request' } + + Select-File 'symbols.bin' + [void](Wait-Until 'binary glyphs in the embedded view' { + [FilesQuickViewProbe]::IsWindowVisible($editor) -and [FilesQuickViewProbe]::Send($editor,2269,0,0).ToInt32() -eq 2 + }) + if ((Preview-Bytes ([Text.Encoding]::UTF8.GetByteCount($expectedSymbols))) -cne $expectedSymbols) { + throw 'Binary control bytes were lost or decoded as text' + } + $expectedLength = [Text.Encoding]::UTF8.GetByteCount($expectedSymbols) + 4096 - $header.Length + if ([FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -ne $expectedLength -or + [FilesQuickViewProbe]::Send($editor,2131,0,0).ToInt32() -ne 0) { + throw 'Binary preview exceeded its byte limit or enabled horizontal scrolling' + } + $escapeWidth = [FilesQuickViewProbe]::Send($editor,2164,0,3).ToInt32() - + [FilesQuickViewProbe]::Send($editor,2164,0,0).ToInt32() + if($escapeWidth -le [FilesQuickViewProbe]::Send($editor,2279,0,0).ToInt32()){ + throw 'The control byte did not render as a full visible escape' + } + if($BinaryImage){ + Add-Type -AssemblyName System.Drawing + $bounds = [FilesCommandsUi+Rect]::new() + [void][FilesCommandsUi]::GetClientRect($preview,[ref]$bounds) + $bitmap = [Drawing.Bitmap]::new($bounds.Right,$bounds.Bottom) + $graphics = [Drawing.Graphics]::FromImage($bitmap) + try { + $dc = $graphics.GetHdc() + try { if(![FilesCommandsUi]::PrintWindow($preview,$dc,3)){throw 'Could not render binary preview'} } + finally { $graphics.ReleaseHdc($dc) } + $bitmap.Save($BinaryImage,[Drawing.Imaging.ImageFormat]::Png) + } finally { $graphics.Dispose(); $bitmap.Dispose() } + } + $wideRows = [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32() + [void][FilesQuickViewProbe]::SetWindowPos($window,0,40,50,840,920,20) + [void](Wait-Until 'binary rows wrap in a narrower pane' { [FilesQuickViewProbe]::Send($editor,2235,0,0).ToInt32() -gt $wideRows }) + + Select-File 'preview.txt' + [void](Wait-Until 'ordinary text preview restored' { [FilesQuickViewProbe]::Send($editor,2006,0,0).ToInt32() -eq 18 }) + if ([FilesQuickViewProbe]::IsWindowVisible($mode) -or [FilesQuickViewProbe]::Send($editor,2269,0,0) -ne $initialWrap -or + [FilesQuickViewProbe]::Send($editor,2131,0,0) -ne $initialScrollbar) { throw 'Preview mode leaked into a text file' } + [void][FilesQuickViewProbe]::Post($window,0x801F,0,0) + [void](Wait-Until 'Quick View closed' { [FilesQuickViewProbe]::GetDlgItem($window, 158) -eq [IntPtr]::Zero }) foreach ($control in $rightList, $rightHeading, $rightPath) { if (![FilesQuickViewProbe]::IsWindowVisible($control)) { throw 'A file panel control remained hidden after closing Quick View.' } } - 'Quick View hides the covered list and chrome, then restores the same controls.' + 'Quick View verified with offline HTML, source switching, bounded binary glyphs and restored file panels.' } finally { if ($process -and !$process.HasExited) { [void]$process.CloseMainWindow() if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() } } + if ($network) { $network.Stop() } + if ($dpi) { [void][FilesCommandsUi]::SetThreadDpiAwarenessContext($dpi) } + $env:WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS = $flags + $env:WEBVIEW2_USER_DATA_FOLDER = $profile foreach ($name in $names) { if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) } else { $key.DeleteValue($name, $false) } @@ -96,6 +229,14 @@ try { $path = [IO.Path]::GetFullPath($fixture.FullName) if ([IO.Path]::GetDirectoryName($path) -eq [IO.Path]::TrimEndingDirectorySeparator([IO.Path]::GetTempPath()) -and [IO.Path]::GetFileName($path).StartsWith('ks-files-quick-view-')) { - [IO.Directory]::Delete($path, $true) + for($attempt=0; $attempt -lt 50; ++$attempt){ + try { + [IO.Directory]::Delete($path, $true) + break + } catch [System.IO.IOException] { + if($attempt -eq 49){throw} + Start-Sleep -Milliseconds 100 + } + } } } diff --git a/tests/files_text_document.cpp b/tests/files_text_document.cpp index 0340d9b..7c834a3 100644 --- a/tests/files_text_document.cpp +++ b/tests/files_text_document.cpp @@ -160,6 +160,12 @@ void hexBytes(const fs::path &file) const auto text=ks::files::formatHexPage(bytes,0); check(text.starts_with("0000000000000000 EF BB BF 00 41 FF 7F 0D 0A") && text.ends_with("|....A.... |"),"Hex and ASCII columns retain unprintable bytes and alignment"); + const std::string controls("\x00\x01\x09\x0A\x0D\x1B\x1F A\x7F\x80\xFF",12); + const std::string symbols(reinterpret_cast(u8"\ue000\ue001\ue009\ue00a\ue00d\ue01b\ue01f A\ue07f\u00c7\ue0ff")); + check(ks::files::formatBinarySymbols(controls)==symbols,"Quick View displays all control and high bytes as glyphs"); + const std::string slash(reinterpret_cast(u8"\ue05c")); + check(ks::files::formatBinarySymbols("\\x00")==slash+"x00","Binary preview distinguishes literal escapes"); + check(ks::files::formatBinarySymbols({}).empty(),"An empty symbol preview stays empty"); const std::string twoRows(17,'a'); check(ks::files::formatHexPage(twoRows,0).find("\r\n0000000000000010 61")!=std::string::npos, "Hex offsets advance by the row width"); From f2dc1f0c789e7a43b01479eba2937139613d95b4 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 22:25:47 +0200 Subject: [PATCH 42/61] Add image rotation crop and undo to Files Refs #126 --- FILES-UI.md | 2 + cmake/FilesImageLibraries.cmake | 2 +- resources/files.rc | 19 +++ src/files_image_decode.cpp | 84 ++++++++++++- src/files_image_decode.h | 4 +- src/files_image_edit.cpp | 137 +++++++++++++++++++++ src/files_image_edit.h | 32 +++++ src/files_image_edit_options.inl | 109 ++++++++++++++++ src/files_image_view.cpp | 205 +++++++++++++++++++++++++++---- src/files_image_view.h | 15 ++- src/files_main.cpp | 9 +- src/files_text_document.cpp | 9 -- src/files_text_window.cpp | 11 +- src/files_text_window.h | 4 +- src/files_win32_replace.h | 10 ++ tests/files_image.cpp | 57 ++++++++- 16 files changed, 656 insertions(+), 53 deletions(-) create mode 100644 src/files_image_edit.cpp create mode 100644 src/files_image_edit.h create mode 100644 src/files_image_edit_options.inl diff --git a/FILES-UI.md b/FILES-UI.md index 53dbe84..9bb6b39 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -695,6 +695,8 @@ Warning і початковий фокус на No. - **F3** відкриває PNG, JPEG, GIF, WebP і BMP у Viewer. Стрілки вліво й вправо, Page Up і Page Down та кнопки Previous і Next гортають видимі зображення в порядку вихідної панелі на момент відкриття Viewer. +- **F4** на локальному PNG або JPEG відкриває редактор зображень. Rotate left і Rotate right повертають зображення на 90°. Crop приймає цілі координати X і Y від нуля, ширину й висоту в пікселях поточного зображення. Undo або Ctrl+Z послідовно скасовує зміни. +- **Save copy** або Ctrl+Shift+S створює окремий PNG чи JPEG. PNG зберігає прозорість, а JPEG використовує біле тло. **Replace** або Ctrl+S просить підтвердження й звіряє версію оригіналу. Якщо зовнішня зміна або помилка заважає запису, редактор зберігає чернетку. Закриття незбереженої чернетки просить підтвердження. - У Viewer і Quick View коліщатко та кнопки − і + змінюють масштаб, перетягування мишею панорамує збільшене зображення, Fit підганяє його під область перегляду, а 100% повертає вихідний масштаб. Клавіші 0 і 1 diff --git a/cmake/FilesImageLibraries.cmake b/cmake/FilesImageLibraries.cmake index 6ce820d..0c17d28 100644 --- a/cmake/FilesImageLibraries.cmake +++ b/cmake/FilesImageLibraries.cmake @@ -16,7 +16,7 @@ function(build_files_webp) endfunction() build_files_webp() -add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_view.cpp) +add_library(KSwitcherFilesImage STATIC src/files_image_decode.cpp src/files_image_edit.cpp src/files_image_view.cpp) target_compile_definitions(KSwitcherFilesImage PRIVATE NOMINMAX UNICODE _UNICODE _WIN32_WINNT=0x0A00) target_link_libraries(KSwitcherFilesImage PRIVATE webpdemux windowscodecs msimg32 ole32) if(MSVC) diff --git a/resources/files.rc b/resources/files.rc index 5b8166e..2a5973b 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -693,3 +693,22 @@ BEGIN CONTROL "&OK", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 102, 161, 86, 16 CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 200, 161, 86, 16 END + +130 DIALOGEX 0, 0, 329, 119 +STYLE DS_SETFONT | DS_CENTER | WS_POPUP | WS_CLIPCHILDREN +CAPTION "Crop image" +FONT 10, "Consolas" +BEGIN + LTEXT "", 650, 14, 15, 301, 12 + LTEXT "&X", 656, 14, 35, 58, 14, SS_CENTERIMAGE + FAR_EDIT(651, ES_NUMBER, 75, 33, 70, 18) + LTEXT "&Y", 657, 173, 35, 58, 14, SS_CENTERIMAGE + FAR_EDIT(652, ES_NUMBER, 244, 33, 70, 18) + LTEXT "&Width", 658, 14, 60, 58, 14, SS_CENTERIMAGE + FAR_EDIT(653, ES_NUMBER, 75, 58, 70, 18) + LTEXT "&Height", 659, 173, 60, 62, 14, SS_CENTERIMAGE + FAR_EDIT(654, ES_NUMBER, 244, 58, 70, 18) + LTEXT "", 655, 10, 86, 1, 1, NOT WS_VISIBLE + CONTROL "&Crop", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 78, 94, 83, 17 + CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 168, 94, 83, 17 +END diff --git a/src/files_image_decode.cpp b/src/files_image_decode.cpp index 53cc38f..53562d8 100644 --- a/src/files_image_decode.cpp +++ b/src/files_image_decode.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -58,13 +59,14 @@ struct ImagingObject T *operator->() const {return value;} }; +struct Apartment +{ + const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED); + ~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();} +}; + ImageRaster decodeNativeImage(const fs::path &file,ImageFormat format,std::stop_token stop) { - struct Apartment - { - const HRESULT initialized=CoInitializeEx(nullptr,COINIT_MULTITHREADED); - ~Apartment() {if(SUCCEEDED(initialized)) CoUninitialize();} - }; const Apartment apartment; if(apartment.initialized!=RPC_E_CHANGED_MODE) checkImage(apartment.initialized); ImagingObject factory; @@ -141,6 +143,78 @@ bool isImagePath(const std::filesystem::path &path) return imageFormat(path)!=ImageFormat::unknown; } +bool isEditableImagePath(const std::filesystem::path &path) +{ + const auto format=imageFormat(path); + return format==ImageFormat::png || format==ImageFormat::jpeg; +} + +void encodeImage(const ImageRaster &raster,const fs::path &contents,const fs::path &name) +{ + const auto format=imageFormat(name); + if(format!=ImageFormat::png && format!=ImageFormat::jpeg) + throw std::runtime_error("Choose a PNG or JPEG file."); + checkImageDimensions(raster.width,raster.height); + if(raster.pixels.size()!=size_t(raster.width)*raster.height) throw std::runtime_error(invalidImage); + const auto check=[](HRESULT result) { + if(FAILED(result)) throw std::system_error(static_cast(result),std::system_category(),"Encode image"); + }; + const Apartment apartment; + if(apartment.initialized!=RPC_E_CHANGED_MODE) check(apartment.initialized); + ImagingObject factory; + check(CoCreateInstance(CLSID_WICImagingFactory,nullptr,CLSCTX_INPROC_SERVER,IID_PPV_ARGS(&factory.value))); + const bool png=format==ImageFormat::png; + ImagingObject stream; + check(factory->CreateStream(&stream.value)); + check(stream->InitializeFromFilename(contents.c_str(),GENERIC_WRITE)); + ImagingObject encoder; + check(factory->CreateEncoder(png?GUID_ContainerFormatPng:GUID_ContainerFormatJpeg,nullptr,&encoder.value)); + check(encoder->Initialize(stream.value,WICBitmapEncoderNoCache)); + ImagingObject frame; + ImagingObject options; + check(encoder->CreateNewFrame(&frame.value,&options.value)); + if(!png) + { + wchar_t qualityName[]=L"ImageQuality"; + PROPBAG2 property{}; + property.pstrName=qualityName; + VARIANT quality{}; + quality.vt=VT_R4; + quality.fltVal=0.95f; + check(options->Write(1,&property,&quality)); + } + check(frame->Initialize(options.value)); + check(frame->SetSize(raster.width,raster.height)); + auto pixelFormat=png?GUID_WICPixelFormat32bppBGRA:GUID_WICPixelFormat24bppBGR; + check(frame->SetPixelFormat(&pixelFormat)); + + auto *pixels=raster.pixels.data(); + std::vector opaque; + if(!png && std::any_of(raster.pixels.begin(),raster.pixels.end(),[](uint32_t pixel){return (pixel>>24)!=255;})) + { + opaque=raster.pixels; + for(auto &pixel:opaque) + { + const auto white=255-(pixel>>24); + const auto gray=white|(white<<8)|(white<<16); + pixel=0xff000000|((pixel&0x00ffffff)+gray); + } + pixels=opaque.data(); + } + const auto stride=static_cast(raster.width*sizeof(uint32_t)); + ImagingObject source; + check(factory->CreateBitmapFromMemory(raster.width,raster.height,GUID_WICPixelFormat32bppPBGRA,stride, + static_cast(raster.pixels.size()*sizeof(uint32_t)), + reinterpret_cast(const_cast(pixels)),&source.value)); + ImagingObject converter; + check(factory->CreateFormatConverter(&converter.value)); + check(converter->Initialize(source.value,pixelFormat,WICBitmapDitherTypeNone,nullptr,0,WICBitmapPaletteTypeCustom)); + check(frame->WriteSource(converter.value,nullptr)); + check(frame->Commit()); + check(encoder->Commit()); + check(stream->Commit(STGC_DEFAULT)); +} + ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop) { const auto format=imageFormat(name); diff --git a/src/files_image_decode.h b/src/files_image_decode.h index dd3edb7..055489f 100644 --- a/src/files_image_decode.h +++ b/src/files_image_decode.h @@ -10,10 +10,12 @@ namespace ks::files struct ImageRaster { unsigned width{}, height{}; - std::vector pixels; + std::vector pixels; // Premultiplied BGRA. }; inline constexpr uint64_t imageSourceLimit=96ULL*1024*1024; bool isImagePath(const std::filesystem::path &path); +bool isEditableImagePath(const std::filesystem::path &path); +void encodeImage(const ImageRaster &raster,const std::filesystem::path &contents,const std::filesystem::path &name); ImageRaster decodeImage(const std::filesystem::path &contents,const std::filesystem::path &name,std::stop_token stop={}); } diff --git a/src/files_image_edit.cpp b/src/files_image_edit.cpp new file mode 100644 index 0000000..2e8d4c4 --- /dev/null +++ b/src/files_image_edit.cpp @@ -0,0 +1,137 @@ +#include "files_image_edit.h" +#include "files_win32_replace.h" +#include + +namespace ks::files +{ +namespace +{ +struct ImageFile +{ + HANDLE handle=INVALID_HANDLE_VALUE; + ~ImageFile() {if(handle!=INVALID_HANDLE_VALUE) CloseHandle(handle);} +}; + +struct StagedImage +{ + std::filesystem::path path; + ~StagedImage() {if(!path.empty()) DeleteFileW(path.c_str());} +}; + +[[noreturn]] void fail(const char *message,DWORD error=GetLastError()) +{ + throw std::system_error(static_cast(error),std::system_category(),message); +} + +ImageRevision readRevision(HANDLE handle) +{ + ImageRevision revision; + FILE_BASIC_INFO basics{}; + if(!GetFileInformationByHandle(handle,&revision.identity) || + !GetFileInformationByHandleEx(handle,FileBasicInfo,&basics,sizeof(basics))) fail("Read image revision"); + if(basics.FileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)) + throw std::runtime_error("Choose a regular local image."); + revision.changeTime=basics.ChangeTime.QuadPart; + return revision; +} + +bool contains(unsigned width,unsigned height,const ImageRegion &area) +{ + return area.width && area.height && area.x=4 || !contains(sideways?region.height:region.width,sideways?region.width:region.height,area)) + throw std::runtime_error("The crop rectangle must fit inside the image."); + const auto width=region.width, height=region.height; + switch(geometry.turns) + { + case 0: region.x+=area.x; region.y+=area.y; break; + case 1: region.x+=area.y; region.y+=height-area.x-area.width; break; + case 2: region.x+=width-area.x-area.width; region.y+=height-area.y-area.height; break; + case 3: region.x+=width-area.y-area.height; region.y+=area.x; break; + } + region.width=sideways?area.height:area.width; + region.height=sideways?area.width:area.height; + return geometry; +} + +ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry) +{ + const auto ®ion=geometry.region; + if(geometry.turns>=4 || !contains(original.width,original.height,region) || + original.pixels.size()!=size_t(original.width)*original.height) + throw std::runtime_error("The image edit exceeds the original bounds."); + const bool sideways=geometry.turns&1; + ImageRaster output{sideways?region.height:region.width,sideways?region.width:region.height,{}}; + output.pixels.resize(size_t(output.width)*output.height); + for(unsigned y=0;y + +namespace ks::files +{ +struct ImageRegion +{ + unsigned x{}, y{}, width{}, height{}; + bool operator==(const ImageRegion &) const = default; +}; + +struct ImageGeometry +{ + ImageRegion region; + unsigned turns{}; + bool operator==(const ImageGeometry &) const = default; +}; + +struct ImageRevision +{ + BY_HANDLE_FILE_INFORMATION identity{}; + LONGLONG changeTime{}; +}; + +ImageGeometry cropImage(ImageGeometry geometry,const ImageRegion &area); +ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry); +ImageRevision imageRevision(const std::filesystem::path &path); +bool sameImageRevision(const ImageRevision &first,const ImageRevision &second); +ImageRevision saveImage(const ImageRaster &raster,const std::filesystem::path &path,const ImageRevision *expected=nullptr); +} diff --git a/src/files_image_edit_options.inl b/src/files_image_edit_options.inl new file mode 100644 index 0000000..d13ab24 --- /dev/null +++ b/src/files_image_edit_options.inl @@ -0,0 +1,109 @@ +struct ImageCropPrompt +{ + unsigned width,height; + ks::files::ImageRegion result; +}; + +INT_PTR CALLBACK imageCropDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) +{ + constexpr int hint=650, x=651, y=652, width=653, height=654, footer=655; + if(message==WM_DRAWITEM) + { + paintDialogButton(*reinterpret_cast(lp),RGB(192,192,192),RGB(0,0,0),true); + return TRUE; + } + if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Crop image ",false,{footer})) + return painted; + if(message==WM_INITDIALOG) + { + auto &prompt=*reinterpret_cast(lp); + SetWindowLongPtrW(window,DWLP_USER,lp); + prepareCopyDialog(window); + layoutDialogContent(window,hint); + layoutDialogButtons(window,footer,{IDOK,IDCANCEL}); + const auto description=L"Image: "+std::to_wstring(prompt.width)+L" × "+std::to_wstring(prompt.height)+ + L" pixels. X and Y start at zero."; + SetDlgItemTextW(window,hint,description.c_str()); + for(const auto id:{x,y,width,height}) + { + fitFarEditToLine(GetDlgItem(window,id)); + const auto value=id==width?prompt.width:id==height?prompt.height:0; + SetDlgItemInt(window,id,value,FALSE); + } + SetFocus(GetDlgItem(window,x)); + SendDlgItemMessageW(window,x,EM_SETSEL,0,-1); + return FALSE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) + { + FilesModalDialog::finish(window,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE; + auto &prompt=*reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); + std::array fields{}; + for(size_t i=0;i(i); + BOOL valid{}; + fields[i]=GetDlgItemInt(window,id,&valid,FALSE); + if(!valid) + { + showFilesNotice(window,L"Enter a whole number of pixels.",L"Crop image"); + SetFocus(GetDlgItem(window,id)); + return TRUE; + } + } + const auto [left,top,wide,high]=fields; + if(!wide || !high || left>=prompt.width || top>=prompt.height || + wide>prompt.width-left || high>prompt.height-top) + { + showFilesNotice(window,L"The crop rectangle must fit inside the image.",L"Crop image"); + return TRUE; + } + prompt.result={left,top,wide,high}; + FilesModalDialog::finish(window,IDOK); + return TRUE; +} + +ks::files::ImageEditDialogs imageEditDialogs() +{ + return { + [](HWND owner,unsigned width,unsigned height) -> std::optional + { + ImageCropPrompt crop{width,height,{}}; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(130),owner, + imageCropDialog,reinterpret_cast(&crop))==IDOK) return crop.result; + return {}; + }, + [](HWND owner,const fs::path &original) -> fs::path + { + const auto name=original.stem().native()+L" copy"+original.extension().native(); + std::array file{}; + wcsncpy_s(file.data(),file.size(),name.c_str(),_TRUNCATE); + auto initial=original.parent_path().native(); + OPENFILENAMEW dialog{sizeof(dialog)}; + dialog.hwndOwner=owner; + dialog.lpstrTitle=L"Save an image copy"; + dialog.lpstrFilter=L"PNG (*.png)\0*.png\0JPEG (*.jpg, *.jpeg)\0*.jpg;*.jpeg\0"; + dialog.nFilterIndex=ks::lower(original.extension().native())==L".png"?1:2; + dialog.lpstrFile=file.data(); + dialog.nMaxFile=static_cast(file.size()); + dialog.lpstrInitialDir=initial.c_str(); + dialog.lpstrDefExt=dialog.nFilterIndex==1?L"png":L"jpg"; + dialog.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST; + if(GetSaveFileNameW(&dialog)) return file.data(); + if(CommDlgExtendedError()) throw std::runtime_error("Could not open the image save dialog."); + return {}; + }, + [](HWND owner,const std::wstring &text,const wchar_t *title) + { + return showFilesNotice(owner,text.c_str(),title,{.confirm=true,.tone=FilesNoticeTone::warning})==IDYES; + }, + [](HWND owner,const wchar_t *text) + { + showFilesNotice(owner,text,L"Image editor",{.tone=FilesNoticeTone::warning}); + }, + FilesModalDialog::dismissOwned + }; +} diff --git a/src/files_image_view.cpp b/src/files_image_view.cpp index f99c472..2c24943 100644 --- a/src/files_image_view.cpp +++ b/src/files_image_view.cpp @@ -18,7 +18,8 @@ namespace namespace fs=std::filesystem; constexpr wchar_t imageWindowClass[]=L"KSwitcherFilesImageViewer"; constexpr UINT_PTR imageTimer=1; -enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize }; +enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize, + rotateLeft, rotateRight, crop, undoEdit, saveCopy, replaceOriginal }; void fillImageView(HDC dc,const RECT &rect,COLORREF color) { @@ -37,14 +38,31 @@ struct ImageView ImageLoadRetry retry; bool retried{}; std::function onClose; - std::array buttons{}; + std::array buttons{}; + struct Draft + { + ImageEditDialogs dialogs; + ImageRaster original; + std::optional version; + ImageGeometry geometry{}, saved{}; + std::vector undo; + bool dirty() const {return geometry!=saved;} + }; + std::optional draft; + struct Loaded + { + ImageRaster raster; + std::optional revision; + }; + bool confirmingClose{}; HFONT font{}; UINT fontDpi{}; + int toolbarHeight{}; HBITMAP bitmap{}; unsigned width{},height{}; fs::path requested; std::wstring error; - std::future reading; + std::future reading; std::stop_source stop; uint64_t revision{}, started{}; double zoom=1, x{}, y{}; @@ -64,7 +82,7 @@ struct ImageView { RECT area{}; GetClientRect(window,&area); - area.top=std::min(area.bottom,static_cast(scale(35))); + area.top=std::min(area.bottom,static_cast(toolbarHeight)); area.bottom=std::max(area.top,area.bottom-scale(27)); return area; } @@ -86,28 +104,62 @@ struct ImageView RECT bounds{}; GetClientRect(window,&bounds); const int left=scale(4), gap=scale(3), height=scale(27); - const int count=embedded?4:6; - const int available=std::max(0,static_cast(bounds.right)-left*2-gap*(count-1)); - const int unit=std::min(scale(80),available/count); - int x=left; - for(auto button:buttons) + const auto place=[&](unsigned first,unsigned last,int y,int preferred) { + const auto count=static_cast(last-first+1); + const auto available=std::max(0,static_cast(bounds.right)-left*2-gap*(count-1)); + const auto unit=std::min(scale(preferred),available/count); + int x=left; + for(unsigned id=first;id<=last;++id) + { + SetWindowPos(buttons[id-1],nullptr,x,scale(y),unit,height,SWP_NOZORDER|SWP_NOACTIVATE); + x+=unit+gap; + } + }; + place(embedded || draft?zoomOut:previous,actualSize,4,80); + int rows=0; + if(draft) { - if(!button) continue; - SetWindowPos(button,nullptr,x,scale(4),unit,height,SWP_NOZORDER|SWP_NOACTIVATE); - x+=unit+gap; + int buttonWidth=scale(80); + if(const auto dc=GetDC(window)) + { + const auto previousFont=font?SelectObject(dc,font):nullptr; + for(unsigned id=rotateLeft;id<=replaceOriginal;++id) + { + wchar_t label[32]{}; + const auto length=GetWindowTextW(buttons[id-1],label,static_cast(std::size(label))); + SIZE extent{}; + if(GetTextExtentPoint32W(dc,label,length,&extent)) + buttonWidth=std::max(buttonWidth,static_cast(extent.cx)+scale(8)); + } + if(previousFont) SelectObject(dc,previousFont); + ReleaseDC(window,dc); + } + const auto perRow=static_cast(std::max(1,(static_cast(bounds.right)-left*2+gap)/(buttonWidth+gap))); + for(unsigned first=rotateLeft;first<=replaceOriginal;first+=perRow) + place(first,std::min(replaceOriginal,first+perRow-1),35+31*rows++,130); } + toolbarHeight=scale(35+31*rows); clampOffset(); InvalidateRect(window,nullptr,FALSE); } void updateButtons() const { - if(!embedded) + if(!embedded && !draft) { EnableWindow(buttons[previous-1],position>0); EnableWindow(buttons[following-1],position+1undo.empty()); + EnableWindow(buttons[saveCopy-1],bitmap!=nullptr); + EnableWindow(buttons[replaceOriginal-1],draft->version && draft->dirty()); + const auto title=L"Editor — "+requested.filename().wstring()+(draft->dirty()?L" *":L""); + SetWindowTextW(window,title.c_str()); + } for(auto button:buttons) if(button) InvalidateRect(button,nullptr,FALSE); } @@ -124,7 +176,7 @@ struct ImageView width=height=0; fit=true; x=y=0; - if(!embedded) + if(!embedded && !draft) { const auto label=L"Viewer — "+path.filename().wstring(); SetWindowTextW(window,label.c_str()); @@ -134,7 +186,7 @@ struct ImageView InvalidateRect(window,nullptr,FALSE); } - void show(ImageRaster image) + void show(const ImageRaster &image) { BITMAPINFO info{}; info.bmiHeader.biSize=sizeof(BITMAPINFOHEADER); @@ -144,12 +196,16 @@ struct ImageView info.bmiHeader.biBitCount=32; info.bmiHeader.biCompression=BI_RGB; void *bits=nullptr; - bitmap=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0); - if(!bitmap || !bits) throw std::runtime_error("Could not display this image."); + const auto next=CreateDIBSection(nullptr,&info,DIB_RGB_COLORS,&bits,nullptr,0); + if(!next || !bits) + { + if(next) DeleteObject(next); + throw std::runtime_error("Could not display this image."); + } std::memcpy(bits,image.pixels.data(),image.pixels.size()*sizeof(uint32_t)); + if(const auto old=std::exchange(bitmap,next)) DeleteObject(old); width=image.width; height=image.height; - updateButtons(); } void poll() @@ -163,7 +219,17 @@ struct ImageView try { auto image=reading.get(); - if(current) show(std::move(image)); + if(current) + { + show(image.raster); + if(draft) + { + draft->version=image.revision; + draft->original=std::move(image.raster); + draft->geometry=draft->saved={{0,0,width,height},0}; + } + updateButtons(); + } } catch(const std::exception &failure) { @@ -191,9 +257,15 @@ struct ImageView } stop=std::stop_source{}; started=revision; - std::packaged_task task([path=requested,decoder=retried?retry.load:load,token=stop.get_token()] + std::packaged_task task([path=requested,decoder=retried?retry.load:load, + token=stop.get_token(),editing=draft.has_value()] { - return decoder?decoder(path,token):decodeImage(path,path,token); + if(!editing) return Loaded{decoder?decoder(path,token):decodeImage(path,path,token),{}}; + const auto before=imageRevision(path); + auto raster=decodeImage(path,path,token); + if(!sameImageRevision(before,imageRevision(path))) + throw std::runtime_error("The image changed while it was opening. Open it again."); + return Loaded{std::move(raster),before}; }); reading=task.get_future(); try {std::thread(std::move(task)).detach();} @@ -242,9 +314,69 @@ struct ImageView InvalidateRect(window,nullptr,FALSE); } + void applyEdit(ImageGeometry next,bool undo) + { + if(next==draft->geometry) return; + auto raster=transformImage(draft->original,next); + if(!undo) draft->undo.push_back(draft->geometry); + try {show(raster);} + catch(...) + { + if(!undo) draft->undo.pop_back(); + throw; + } + if(undo) draft->undo.pop_back(); + draft->geometry=next; + fit=true; + zoom=1; + x=y=0; + updateButtons(); + InvalidateRect(window,nullptr,FALSE); + } + + void editAction(UINT id) + { + if(!draft || !bitmap) return; + try + { + if(id==rotateLeft || id==rotateRight) + { + auto next=draft->geometry; + next.turns=(next.turns+(id==rotateLeft?3:1))%4; + applyEdit(next,false); + } + else if(id==crop) + { + if(const auto area=draft->dialogs.crop(window,width,height)) + applyEdit(cropImage(draft->geometry,*area),false); + } + else if(id==undoEdit && !draft->undo.empty()) + applyEdit(draft->undo.back(),true); + else if(id==saveCopy) + { + const auto destination=draft->dialogs.copyPath(window,requested); + if(destination.empty()) return; + saveImage(transformImage(draft->original,draft->geometry),destination); + } + else if(id==replaceOriginal && draft->dirty() && draft->version && + draft->dialogs.confirm(window,L"Replace the original image?\r\n\r\n"+requested.native(),L"Replace original")) + { + draft->version=saveImage(transformImage(draft->original,draft->geometry),requested,&*draft->version); + draft->saved=draft->geometry; + updateButtons(); + } + } + catch(const std::exception &failure) + { + updateButtons(); + draft->dialogs.report(window,wide(failure.what()).c_str()); + } + } + void action(UINT id) { - if(id==previous && position>0) request(images[--position]); + if(id>=rotateLeft && id<=replaceOriginal) editAction(id); + else if(id==previous && position>0) request(images[--position]); else if(id==following && position+1(static_cast(id)),GetModuleHandleW(nullptr),nullptr); + if(!view.buttons[id-1]) return -1; + } view.layout(); view.updateButtons(); return 0; @@ -416,15 +554,26 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp) return 0; } case WM_KEYDOWN: - if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn); + if(view.draft && (GetKeyState(VK_CONTROL)&0x8000) && wp=='Z') view.action(undoEdit); + else if(view.draft && (GetKeyState(VK_CONTROL)&0x8000) && wp=='S') + view.action((GetKeyState(VK_SHIFT)&0x8000)?saveCopy:replaceOriginal); + else if(wp==VK_ADD || wp==VK_OEM_PLUS) view.action(zoomIn); else if(wp==VK_SUBTRACT || wp==VK_OEM_MINUS) view.action(zoomOut); else if(wp=='0') view.action(fitImage); else if(wp=='1') view.action(actualSize); else if(!view.embedded && (wp==VK_LEFT || wp==VK_PRIOR)) view.action(previous); else if(!view.embedded && (wp==VK_RIGHT || wp==VK_NEXT)) view.action(following); - else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) DestroyWindow(window); + else if(!view.embedded && (wp==VK_ESCAPE || wp==VK_F10)) SendMessageW(window,WM_CLOSE,0,0); else break; return 0; + case WM_CLOSE: + if(view.confirmingClose || (view.draft && view.draft->dialogs.dismissOwned(window))) return 0; + view.confirmingClose=true; + if(!view.draft || !view.draft->dirty() || + view.draft->dialogs.confirm(window,L"Discard unsaved image edits?",L"Image editor")) + DestroyWindow(window); + view.confirmingClose=false; + return 0; case WM_NCDESTROY: imageViews.erase(found); if(view.onClose) view.onClose(window); @@ -435,7 +584,8 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp) } HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector images, - const std::filesystem::path &initial,ImageLoad load,std::function onClose,ImageLoadRetry retry) + const std::filesystem::path &initial,ImageLoad load,std::function onClose,ImageLoadRetry retry, + const ImageEditDialogs *editor) { const auto instance=GetModuleHandleW(nullptr); static const bool registered=[instance] @@ -450,6 +600,7 @@ HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector(); state->embedded=embedded; + if(editor) state->draft.emplace(ImageView::Draft{*editor}); state->style=style; state->images=std::move(images); state->load=std::move(load); diff --git a/src/files_image_view.h b/src/files_image_view.h index 6c8d66a..f4f6972 100644 --- a/src/files_image_view.h +++ b/src/files_image_view.h @@ -1,6 +1,7 @@ #pragma once -#include "files_image_decode.h" +#include "files_image_edit.h" +#include #include #include #include @@ -22,7 +23,17 @@ struct ImageViewStyle COLORREF background{}, text{}, toolbar{}, toolbarText{}, selection{}; }; +struct ImageEditDialogs +{ + std::function(HWND,unsigned,unsigned)> crop; + std::function copyPath; + std::function confirm; + std::function report; + std::function dismissOwned; +}; + HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector images, - const std::filesystem::path &initial,ImageLoad load={},std::function onClose={},ImageLoadRetry retry={}); + const std::filesystem::path &initial,ImageLoad load={},std::function onClose={},ImageLoadRetry retry={}, + const ImageEditDialogs *editor=nullptr); void showImageViewFile(HWND window,const std::filesystem::path &path); } diff --git a/src/files_main.cpp b/src/files_main.cpp index 62295d3..810064e 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -41,7 +41,7 @@ #include "files_archive.h" #include "files_git_changes.h" #include "files_compare_text.h" -#include "files_image_decode.h" +#include "files_image_view.h" #include "files_win32_directory.h" #include "files_win32_replace.h" #include "files_command_completion.h" @@ -3760,6 +3760,7 @@ void collectFolderSizes(Panel &panel) } void openSelectedText(const Panel &panel, bool edit, bool external,bool hex=false); +ks::files::ImageEditDialogs imageEditDialogs(); ks::files::TextDialogs textWindowDialogs(); void findPanelFiles(HWND owner,Panel &panel); void compareSelectedFiles(HWND owner); @@ -4645,6 +4646,11 @@ void openSelectedText(const Panel &panel, bool edit, bool external,bool hex) openPanelFile(panel,path,edit?L"edit":L"open", edit?L"No editor is registered for this file.":L"Cannot open the selected file."); else if(!edit && !hex && ks::files::isImagePath(path)) openPanelImage(panel,path); + else if(edit && !hex && !panel.peer && !windowsNetworkPath(path) && ks::files::isEditableImagePath(path)) + { + const auto dialogs=imageEditDialogs(); + ks::files::openImageWindow(GetParent(panel.list),{path},path,textWindowDialogs(),nullptr,nullptr,&dialogs); + } else ks::files::openTextWindow(GetParent(panel.list),path,edit,textWindowDialogs(), panel.peer?&*panel.peer:nullptr,{},false,{.hex=hex}); } @@ -5341,6 +5347,7 @@ CopyDestination validateCopyDestination(CopyRequest request,const std::wstring & } #include "files_copy_options.inl" +#include "files_image_edit_options.inl" INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) { diff --git a/src/files_text_document.cpp b/src/files_text_document.cpp index dfcf7c8..36a02b5 100644 --- a/src/files_text_document.cpp +++ b/src/files_text_document.cpp @@ -90,15 +90,6 @@ bool sameFile(HANDLE a, HANDLE b) return sameFileIdentity(first,second); } -std::filesystem::path temporaryPath(const std::filesystem::path &directory) -{ - GUID id{}; - wchar_t name[40]{}; - if (FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id, name, 40)) - throw std::runtime_error("Cannot create a temporary file name."); - return directory / (std::wstring(L".kswitcher-") + name + L".tmp"); -} - std::filesystem::path createTemporary(const std::filesystem::path &directory, File &file, DWORD flags) { auto path = temporaryPath(directory); diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index e869700..19d5639 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -3427,7 +3427,7 @@ void previewImageQuickViewFile(HWND window,const std::filesystem::path &path) } void openImageWindow(HWND owner,std::vector images,const std::filesystem::path &path, - TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source) + TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source,const ImageEditDialogs *editor) { try { @@ -3461,13 +3461,14 @@ void openImageWindow(HWND owner,std::vector images,const [](HWND closed) { std::erase(textWindowOrder,closed); quitWhenFilesWindowsClose(); - },std::move(retry)); - if(!window) throw std::runtime_error("Could not open the image viewer."); + },std::move(retry),editor); + if(!window) throw std::runtime_error(editor?"Could not open the image editor.":"Could not open the image viewer."); textWindowOrder.push_back(window); const auto instance=GetModuleHandleW(nullptr); - const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(IDI_FILES_VIEWER),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE); + const int iconId=editor?IDI_FILES_EDITOR:IDI_FILES_VIEWER; + const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(iconId),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE); if(icon) SendMessageW(window,WM_SETICON,ICON_BIG,reinterpret_cast(icon)); - setFileWindowTaskbar(window,IDI_FILES_VIEWER,L"HrynCo.KSwitcher.Files.Viewer"); + setFileWindowTaskbar(window,iconId,editor?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer"); ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW); SetFocus(window); } diff --git a/src/files_text_window.h b/src/files_text_window.h index 45461d6..d0c9d26 100644 --- a/src/files_text_window.h +++ b/src/files_text_window.h @@ -109,8 +109,10 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path); void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff=false); HWND createImageQuickView(HWND owner,TextDialogs dialogs); void previewImageQuickViewFile(HWND window,const std::filesystem::path &path); +struct ImageEditDialogs; void openImageWindow(HWND owner,std::vector images,const std::filesystem::path &path, - TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr); + TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr, + const ImageEditDialogs *editor=nullptr); void showAllViewerBookmarks(HWND owner,TextDialogs dialogs); void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, diff --git a/src/files_win32_replace.h b/src/files_win32_replace.h index fcdc362..ed23ada 100644 --- a/src/files_win32_replace.h +++ b/src/files_win32_replace.h @@ -1,12 +1,22 @@ #pragma once #include +#include #include #include #include namespace ks::files { +inline std::filesystem::path temporaryPath(const std::filesystem::path &directory) +{ + GUID id{}; + wchar_t name[40]{}; + if(FAILED(CoCreateGuid(&id)) || !StringFromGUID2(id,name,40)) + throw std::runtime_error("Cannot create a temporary file name."); + return directory/(std::wstring(L".kswitcher-")+name+L".tmp"); +} + inline bool sameFileIdentity(const BY_HANDLE_FILE_INFORMATION &left,const BY_HANDLE_FILE_INFORMATION &right) { return left.dwVolumeSerialNumber==right.dwVolumeSerialNumber && left.nFileIndexHigh==right.nFileIndexHigh && diff --git a/tests/files_image.cpp b/tests/files_image.cpp index b0c692b..3ea9b04 100644 --- a/tests/files_image.cpp +++ b/tests/files_image.cpp @@ -1,4 +1,4 @@ -#include "files_image_decode.h" +#include "files_image_edit.h" #include #include #include @@ -84,6 +84,60 @@ void expectDecodeFailure(const fs::path &file,std::string_view text) throw std::runtime_error("invalid image was decoded"); } +void verifyImageEdits(const fs::path &root) +{ + ImageRaster original{4,3,{0xff110001,0xff110002,0xff110003,0xff110004, + 0xff110005,0x80402010,0xff110007,0xff110008,0xff110009,0xff11000a,0xff11000b,0xff11000c}}; + const ImageGeometry initial{{0,0,4,3},0}; + const ImageGeometry clockwise{initial.region,1}; + const auto rotated=transformImage(original,clockwise); + expect(rotated.width==3 && rotated.height==4 && rotated.pixels[0]==original.pixels[8] && + rotated.pixels[11]==original.pixels[3],"clockwise rotation changed pixel order"); + const auto reversed=transformImage(original,{initial.region,3}); + expect(reversed.pixels.front()==original.pixels[3] && reversed.pixels.back()==original.pixels[8], + "counterclockwise rotation changed pixel order"); + const auto cropped=transformImage(original,cropImage(clockwise,{1,1,2,2})); + expect(cropped.width==2 && cropped.height==2 && cropped.pixels==std::vector{ + original.pixels[5],original.pixels[1],original.pixels[6],original.pixels[2]}, + "crop used coordinates before rotation"); + bool outside=false; + try {cropImage(clockwise,{2,1,2,2});} + catch(const std::runtime_error &) {outside=true;} + expect(outside,"out-of-bounds crop was accepted"); + + const auto png=root/L"Редагування.png"; + saveImage(cropped,png); + const auto saved=decodeImage(png,png); + expect(saved.width==2 && saved.height==2 && saved.pixels==cropped.pixels,"PNG copy lost alpha or pixels"); + const auto before=imageRevision(png); + bool collision=false; + try {saveImage(rotated,png);} + catch(const std::system_error &) {collision=true;} + expect(collision && sameImageRevision(before,imageRevision(png)), "Save Copy overwrote an existing image"); + + const auto incoming=root/L"external.png"; + saveImage(original,incoming); + fs::rename(png,root/L"first.png"); + fs::rename(incoming,png); + bool stale=false; + try {saveImage(cropped,png,&before);} + catch(const std::runtime_error &) {stale=true;} + expect(stale && decodeImage(png,png).pixels==original.pixels,"Replace overwrote an external revision"); + const auto current=imageRevision(png); + const auto written=saveImage(cropped,png,¤t); + expect(sameImageRevision(written,imageRevision(png)), "returned revision did not track the installed image"); + expect(decodeImage(png,png).pixels==cropped.pixels,"confirmed replacement lost image data"); + + const auto jpeg=root/L"copy.jpg"; + const ImageRaster transparent{8,8,std::vector(64,0)}; + saveImage(transparent,jpeg); + const auto lossy=decodeImage(jpeg,jpeg); + expect(lossy.width==8 && lossy.height==8 && lossy.pixels.front()>=0xfffefefe, + "JPEG copy failed to composite transparency on white"); + for(const auto &entry:fs::directory_iterator(root)) + expect(entry.path().extension()!=L".tmp","image operation left a staging file"); +} + std::vector animatedWebp(const uint8_t *encoded,size_t size) { expect(size>12,"WebP fixture RIFF body"); @@ -109,6 +163,7 @@ int main() { expect(SUCCEEDED(apartment),"initialize COM"); Temp temp; + verifyImageEdits(temp.path); for(const auto &[name,container]:std::array{ std::pair{L"знімок.PNG",&GUID_ContainerFormatPng}, std::pair{L"picture.jpeg",&GUID_ContainerFormatJpeg}, From 175745083352a99eb41c224ea97468fdf439bad4 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 22:41:48 +0200 Subject: [PATCH 43/61] Restore local Files documents and guard external edits Refs #127 --- FILES-UI.md | 2 + resources/files.rc | 1 + resources/terminal/markdown.js | 11 ++ src/files_image_edit.cpp | 12 +- src/files_image_edit.h | 8 +- src/files_image_edit_options.inl | 2 +- src/files_image_view.cpp | 71 +++++++-- src/files_image_view.h | 12 ++ src/files_main.cpp | 18 ++- src/files_options.inl | 12 +- src/files_text_document.cpp | 58 ++++++-- src/files_text_document.h | 8 +- src/files_text_window.cpp | 247 +++++++++++++++++++++++++++---- src/files_text_window.h | 6 +- src/files_win32_replace.h | 36 +++++ tests/files_text_document.cpp | 24 +++ 16 files changed, 455 insertions(+), 73 deletions(-) diff --git a/FILES-UI.md b/FILES-UI.md index 9bb6b39..b18561d 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -695,6 +695,8 @@ Warning і початковий фокус на No. - **F3** відкриває PNG, JPEG, GIF, WebP і BMP у Viewer. Стрілки вліво й вправо, Page Up і Page Down та кнопки Previous і Next гортають видимі зображення в порядку вихідної панелі на момент відкриття Viewer. +- **Options → Viewer → Restore local Viewer and Editor windows after restart** зберігає відкриті локальні вікна під час закриття Files. Під час наступного запуску наявні документи відкриваються в попередньому режимі й положенні. Текст відновлює сторінку, курсор і прокручування, а зображення — масштаб. Відновлення читає збережені файли з диска. +- Локальний Viewer оновлює вміст після зміни файла. Активний Editor пропонує **Reload** або **Keep buffer**. Reload відкриває актуальну версію з диска, Keep buffer залишає відкриті редагування. Збереження після Keep buffer перевіряє початкову версію й зберігає чернетку, якщо файл уже змінився. - **F4** на локальному PNG або JPEG відкриває редактор зображень. Rotate left і Rotate right повертають зображення на 90°. Crop приймає цілі координати X і Y від нуля, ширину й висоту в пікселях поточного зображення. Undo або Ctrl+Z послідовно скасовує зміни. - **Save copy** або Ctrl+Shift+S створює окремий PNG чи JPEG. PNG зберігає прозорість, а JPEG використовує біле тло. **Replace** або Ctrl+S просить підтвердження й звіряє версію оригіналу. Якщо зовнішня зміна або помилка заважає запису, редактор зберігає чернетку. Закриття незбереженої чернетки просить підтвердження. - У Viewer і Quick View коліщатко та кнопки − і + змінюють масштаб, diff --git a/resources/files.rc b/resources/files.rc index 2a5973b..a0cbb4c 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -236,6 +236,7 @@ BEGIN PUSHBUTTON "Change color…", 366, 257, 181, 82, 15 LTEXT "", 367, 345, 184, 45, 12 PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15 + AUTOCHECKBOX "Restore local Viewer and Editor windows after restart", 524, 131, 210, 250, 13 LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12 EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL LTEXT "Font &family (blank = system default)", 375, 131, 54, 250, 12 diff --git a/resources/terminal/markdown.js b/resources/terminal/markdown.js index b9f11ee..368ef88 100644 --- a/resources/terminal/markdown.js +++ b/resources/terminal/markdown.js @@ -355,6 +355,17 @@ document.addEventListener('keydown', event => { } }); +let scrollTimer; +window.addEventListener('scroll', () => { + if (document.documentElement.classList.contains('quick-view')) return; + clearTimeout(scrollTimer); + const revision = previewRevision; + scrollTimer = setTimeout(() => { + if (revision === previewRevision && document.documentElement.classList.contains('rendered')) + send('scroll', { revision, top: Math.round(window.scrollY) }); + }, 120); +}, { passive: true }); + bridge.addEventListener('message', ({ data }) => { const message = JSON.parse(data); if (message.action === 'clear') { diff --git a/src/files_image_edit.cpp b/src/files_image_edit.cpp index 2e8d4c4..c0986eb 100644 --- a/src/files_image_edit.cpp +++ b/src/files_image_edit.cpp @@ -25,13 +25,9 @@ struct StagedImage ImageRevision readRevision(HANDLE handle) { - ImageRevision revision; - FILE_BASIC_INFO basics{}; - if(!GetFileInformationByHandle(handle,&revision.identity) || - !GetFileInformationByHandleEx(handle,FileBasicInfo,&basics,sizeof(basics))) fail("Read image revision"); - if(basics.FileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)) + const auto revision=fileVersion(handle); + if(revision.info.dwFileAttributes&(FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_REPARSE_POINT)) throw std::runtime_error("Choose a regular local image."); - revision.changeTime=basics.ChangeTime.QuadPart; return revision; } @@ -98,9 +94,7 @@ ImageRevision imageRevision(const std::filesystem::path &path) bool sameImageRevision(const ImageRevision &first,const ImageRevision &second) { - return sameFileIdentity(first.identity,second.identity) && first.changeTime==second.changeTime && - first.identity.nFileSizeHigh==second.identity.nFileSizeHigh && first.identity.nFileSizeLow==second.identity.nFileSizeLow && - CompareFileTime(&first.identity.ftLastWriteTime,&second.identity.ftLastWriteTime)==0; + return first==second; } ImageRevision saveImage(const ImageRaster &raster,const std::filesystem::path &path,const ImageRevision *expected) diff --git a/src/files_image_edit.h b/src/files_image_edit.h index ac80dec..d22cef4 100644 --- a/src/files_image_edit.h +++ b/src/files_image_edit.h @@ -1,7 +1,7 @@ #pragma once #include "files_image_decode.h" -#include +#include "files_win32_replace.h" namespace ks::files { @@ -18,11 +18,7 @@ struct ImageGeometry bool operator==(const ImageGeometry &) const = default; }; -struct ImageRevision -{ - BY_HANDLE_FILE_INFORMATION identity{}; - LONGLONG changeTime{}; -}; +using ImageRevision=LocalFileVersion; ImageGeometry cropImage(ImageGeometry geometry,const ImageRegion &area); ImageRaster transformImage(const ImageRaster &original,const ImageGeometry &geometry); diff --git a/src/files_image_edit_options.inl b/src/files_image_edit_options.inl index d13ab24..a694bb8 100644 --- a/src/files_image_edit_options.inl +++ b/src/files_image_edit_options.inl @@ -104,6 +104,6 @@ ks::files::ImageEditDialogs imageEditDialogs() { showFilesNotice(owner,text,L"Image editor",{.tone=FilesNoticeTone::warning}); }, - FilesModalDialog::dismissOwned + FilesModalDialog::dismissOwned,textWindowDialogs().reloadChanged }; } diff --git a/src/files_image_view.cpp b/src/files_image_view.cpp index 2c24943..7b2878c 100644 --- a/src/files_image_view.cpp +++ b/src/files_image_view.cpp @@ -17,7 +17,7 @@ namespace { namespace fs=std::filesystem; constexpr wchar_t imageWindowClass[]=L"KSwitcherFilesImageViewer"; -constexpr UINT_PTR imageTimer=1; +constexpr UINT_PTR imageTimer=1, externalImageTimer=2; enum Action { previous=1, following, zoomOut, zoomIn, fitImage, actualSize, rotateLeft, rotateRight, crop, undoEdit, saveCopy, replaceOriginal }; @@ -55,6 +55,7 @@ struct ImageView std::optional revision; }; bool confirmingClose{}; + std::optional observedVersion; HFONT font{}; UINT fontDpi{}; int toolbarHeight{}; @@ -164,18 +165,22 @@ struct ImageView if(button) InvalidateRect(button,nullptr,FALSE); } - void request(const fs::path &path) + void request(const fs::path &path,bool reload=false) { - if(requested==path) return; + if(requested==path && !reload) return; requested=path; ++revision; stop.request_stop(); retried=false; error.clear(); - if(bitmap) DeleteObject(std::exchange(bitmap,nullptr)); - width=height=0; - fit=true; - x=y=0; + if(!reload) + { + observedVersion.reset(); + if(bitmap) DeleteObject(std::exchange(bitmap,nullptr)); + width=height=0; + fit=true; + x=y=0; + } if(!embedded && !draft) { const auto label=L"Viewer — "+path.filename().wstring(); @@ -222,12 +227,15 @@ struct ImageView if(current) { show(image.raster); + observedVersion=image.revision; if(draft) { + draft->undo.clear(); draft->version=image.revision; draft->original=std::move(image.raster); draft->geometry=draft->saved={{0,0,width,height},0}; } + clampOffset(); updateButtons(); } } @@ -258,12 +266,14 @@ struct ImageView stop=std::stop_source{}; started=revision; std::packaged_task task([path=requested,decoder=retried?retry.load:load, - token=stop.get_token(),editing=draft.has_value()] + token=stop.get_token(),watch=!embedded && !load && isLocalDocumentPath(requested),editing=draft.has_value()] { - if(!editing) return Loaded{decoder?decoder(path,token):decodeImage(path,path,token),{}}; - const auto before=imageRevision(path); + if(!watch) return Loaded{decoder?decoder(path,token):decodeImage(path,path,token),{}}; + std::optional before; + try {before=imageRevision(path);} + catch(const std::exception &) {if(editing) throw;} auto raster=decodeImage(path,path,token); - if(!sameImageRevision(before,imageRevision(path))) + if(before && *before!=imageRevision(path)) throw std::runtime_error("The image changed while it was opening. Open it again."); return Loaded{std::move(raster),before}; }); @@ -278,6 +288,18 @@ struct ImageView } } + void pollExternal() + { + if(!observedVersion || requested.empty() || reading.valid()) return; + std::optional revision; + try {revision=imageRevision(requested);} + catch(const std::exception &) {return;} + if(revision==observedVersion) return; + if(draft && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !draft->dialogs.reloadChanged)) return; + observedVersion=revision; + if(!draft || draft->dialogs.reloadChanged(window)) request(requested,true); + } + double factor() const { if(!fit || !width || !height) return zoom; @@ -362,6 +384,7 @@ struct ImageView draft->dialogs.confirm(window,L"Replace the original image?\r\n\r\n"+requested.native(),L"Replace original")) { draft->version=saveImage(transformImage(draft->original,draft->geometry),requested,&*draft->version); + observedVersion=draft->version; draft->saved=draft->geometry; updateButtons(); } @@ -498,6 +521,7 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp) } view.layout(); view.updateButtons(); + if(!view.embedded && !view.load) SetTimer(window,externalImageTimer,500,nullptr); return 0; } case WM_SIZE: view.layout(); return 0; @@ -514,7 +538,10 @@ LRESULT CALLBACK imageProcedure(HWND window,UINT message,WPARAM wp,LPARAM lp) case WM_ERASEBKGND: return 1; case WM_PAINT: view.paint(); return 0; case WM_DRAWITEM: view.paintButton(*reinterpret_cast(lp)); return TRUE; - case WM_TIMER: if(wp==imageTimer) view.poll(); return 0; + case WM_TIMER: + if(wp==imageTimer) view.poll(); + if(wp==externalImageTimer) view.pollExternal(); + return 0; case WM_COMMAND: if(HIWORD(wp)==BN_CLICKED) {view.action(LOWORD(wp)); SetFocus(window);} return 0; @@ -622,4 +649,24 @@ void showImageViewFile(HWND window,const std::filesystem::path &path) { if(const auto found=imageViews.find(window);found!=imageViews.end()) found->second->request(path); } + +std::optional imageWindowSession(HWND window) +{ + const auto found=imageViews.find(window); + if(found==imageViews.end()) return {}; + const auto &view=*found->second; + if(view.embedded || view.load || !isLocalDocumentPath(view.requested)) return {}; + return ImageWindowSession{view.requested,view.draft.has_value(),view.fit,view.zoom,view.x,view.y}; +} + +void restoreImageWindowSession(HWND window,const ImageWindowSession &state) +{ + const auto found=imageViews.find(window); + if(found==imageViews.end()) return; + auto &view=*found->second; + view.fit=state.fit; + view.zoom=std::isfinite(state.zoom)?std::clamp(state.zoom,0.05,32.0):1.0; + view.x=std::isfinite(state.x)?state.x:0; + view.y=std::isfinite(state.y)?state.y:0; +} } diff --git a/src/files_image_view.h b/src/files_image_view.h index f4f6972..9bcabfb 100644 --- a/src/files_image_view.h +++ b/src/files_image_view.h @@ -30,10 +30,22 @@ struct ImageEditDialogs std::function confirm; std::function report; std::function dismissOwned; + std::function reloadChanged; }; HWND createImageView(HWND owner,bool embedded,ImageViewStyle style,std::vector images, const std::filesystem::path &initial,ImageLoad load={},std::function onClose={},ImageLoadRetry retry={}, const ImageEditDialogs *editor=nullptr); void showImageViewFile(HWND window,const std::filesystem::path &path); + +struct ImageWindowSession +{ + std::filesystem::path path; + bool editor{}, fit=true; + double zoom=1, x{}, y{}; + RECT bounds{}; + bool maximized{}; +}; +std::optional imageWindowSession(HWND window); +void restoreImageWindowSession(HWND window,const ImageWindowSession &state); } diff --git a/src/files_main.cpp b/src/files_main.cpp index 810064e..aa565a5 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -834,9 +834,9 @@ constexpr DWORD defaultStatusFields=15; int sizeWidth=defaultSizeWidth; bool alignExtensions=defaultAlignExtensions, showDetails=defaultShowDetails; bool alignFolders=defaultAlignFolders; -bool rightClickMarks{}, showDriveButtons{}, compactLayout{}; +bool rightClickMarks{}, showDriveButtons{}, compactLayout{}, restoreDocuments{}; constexpr wchar_t rightClickMarksKey[]=L"RightClickMarks", driveButtonsKey[]=L"ShowDriveButtons", - compactLayoutKey[]=L"CompactPanelLayout"; + compactLayoutKey[]=L"CompactPanelLayout",restoreDocumentsKey[]=L"RestoreLocalDocuments"; constexpr int firstDriveButton=660, moreDriveButton=firstDriveButton+26; std::array driveButtons{}; DWORD statusFields=defaultStatusFields; @@ -920,6 +920,7 @@ struct FilesNoticeOptions FilesNoticeTone tone{FilesNoticeTone::dialog}; bool processes{}; bool saveChanges{}, chooseTransfer{}; + const wchar_t *accept{}, *decline{}; }; INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={}); void openMenu(HWND window, int index); @@ -4516,7 +4517,13 @@ ks::files::TextDialogs textWindowDialogs() { return showFilesNotice(owner,L"This file is already open. Switch to its window?",L"Files", {.confirm=true})==IDYES; - },chooseTextSaveOptions}; + },chooseTextSaveOptions, + [](HWND owner) + { + return showFilesNotice(owner,L"The file changed outside Files. Reload the disk version?", + L"File changed on disk",{.confirm=true,.tone=FilesNoticeTone::warning, + .accept=L"&Reload",.decline=L"&Keep buffer"})==IDYES; + }}; } void refreshQuickView(const Panel &panel) @@ -5995,6 +6002,8 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) ShowWindow(GetDlgItem(window,IDYES),SW_SHOW); ShowWindow(GetDlgItem(window,IDNO),SW_SHOW); } + if(notice.options.accept) SetDlgItemTextW(window,IDYES,notice.options.accept); + if(notice.options.decline) SetDlgItemTextW(window,IDNO,notice.options.decline); if(notice.options.saveChanges) { SetDlgItemTextW(window,IDYES,L"&Save"); @@ -8169,6 +8178,7 @@ bool loadFilesPreferences(HWND window) rightClickMarks=preference(rightClickMarksKey,0)!=0; showDriveButtons=preference(driveButtonsKey,0)!=0; compactLayout=preference(compactLayoutKey,0)!=0; + restoreDocuments=preference(restoreDocumentsKey,0)!=0; statusFields=preference(L"StatusFields",defaultStatusFields)&15; loadCommandHistoryKeys(); loadComparisonShortcut(); @@ -9299,6 +9309,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) return 0; } savePlacement(window); + ks::files::saveLocalDocumentSession(schemeKey,restoreDocuments); for(int i=0;i<2;++i) { saveFtpPanelLocation(panels[i],i); @@ -9407,6 +9418,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) } if(!restorePlacement(window)) ShowWindow(window, show); SetFocus(terminalInput); + if(restoreDocuments) ks::files::restoreLocalDocumentSession(window,textWindowDialogs(),schemeKey,imageEditDialogs()); MSG message{}; for(;;) { diff --git a/src/files_options.inl b/src/files_options.inl index b13ccba..7b73352 100644 --- a/src/files_options.inl +++ b/src/files_options.inl @@ -20,6 +20,7 @@ constexpr int appearanceControls[]{281,282}; enum AppearanceSection { Font, DialogFrame }; constexpr int outerFramePadding=303,innerFramePadding=305,rowTextPadding=307; constexpr int dialogFrameControls[]{302,outerFramePadding,304,innerFramePadding,306,rowTextPadding}; +constexpr int restoreDocumentsControl=524; constexpr int textTabWidth=357,textLineEnding=359, textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368; constexpr int textControls[]{350,351,352,353,356,textTabWidth, @@ -112,6 +113,7 @@ struct OptionsBaseline DWORD width=static_cast(sizeWidth), fields=statusFields; bool extensions=alignExtensions, folders=alignFolders, details=showDetails; bool mouseMarks=rightClickMarks, drives=showDriveButtons, compact=compactLayout; + bool restoreLocal=restoreDocuments; std::array modes{panels[0].mode,panels[1].mode}; ks::files::TextSettings text=ks::files::loadTextPreferences(); ComparisonAppearance comparison=readComparisonAppearance(); @@ -187,7 +189,7 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft) panelModeOption(dialog,0)!=base.modes[0] || panelModeOption(dialog,1)!=base.modes[1] || checked(202)!=base.extensions || checked(204)!=base.folders || checked(203)!=base.details || checked(rightClickMarksControl)!=base.mouseMarks || checked(driveButtonsControl)!=base.drives || - checked(compactLayoutControl)!=base.compact || + checked(compactLayoutControl)!=base.compact || checked(restoreDocumentsControl)!=base.restoreLocal || fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles || draft.framePadding!=base.padding || optionsFontChanged(draft) || optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal || @@ -508,6 +510,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) show(commandLineControls,page==CommandLine && section==0); show(markdownControls,markdown); show(textControls,textOptionsPage(page) && !markdown); + ShowWindow(GetDlgItem(dialog,restoreDocumentsControl),page==TextViewer && !markdown?SW_SHOW:SW_HIDE); show(editingControls,page==TextEditor); if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]); const bool fileTypes=page==PanelColors && section==fileStyleSection; @@ -618,6 +621,7 @@ void filterOptions(HWND dialog,OptionsDraft &draft) const bool propertyMatches=matches(L"Tab width") || matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Customize colors") || (page==TextEditor && matches(L"Line endings for new lines")) || + (page==TextViewer && matches(L"Restore local Viewer and Editor windows after restart")) || std::any_of(std::begin(textChecks),std::end(textChecks),[&](const auto &check) {return (page==TextEditor || check.id<354) && matches(check.name);}) || std::any_of(std::begin(ks::files::textColorNames),std::end(ks::files::textColorNames),matches); @@ -689,6 +693,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks); CheckDlgButton(dialog,driveButtonsControl,showDriveButtons); CheckDlgButton(dialog,compactLayoutControl,compactLayout); + CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments); showPanelModeOptions(dialog); for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u); setOptionHistoryKeys(dialog,commandHistoryKeys); @@ -885,6 +890,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font)) draft->framePadding=defaultDialogFramePadding; + if(draft->page==allOptions || (draft->page==TextViewer && draft->section!=markdownSection)) + CheckDlgButton(dialog,restoreDocumentsControl,BST_UNCHECKED); if(draft->page==allOptions || textOptionsPage(draft->page)) for(int page=TextViewer;page<=TextEditor;++page) if(draft->page==allOptions || (draft->page==page && draft->section!=markdownSection)) @@ -909,6 +916,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) case 201: case 202: case 203: case 204: case 205: case 206: case 207: case 208: case 273: case 274: case rightClickMarksControl: case driveButtonsControl: case compactLayoutControl: + case restoreDocumentsControl: case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate: updateOptionsApply(dialog,*draft); return TRUE; @@ -1064,6 +1072,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) saveChanged(rightClickMarksKey,checked(rightClickMarksControl),base.mouseMarks); saveChanged(driveButtonsKey,checked(driveButtonsControl),base.drives); saveChanged(compactLayoutKey,checked(compactLayoutControl),base.compact); + saveChanged(restoreDocumentsKey,checked(restoreDocumentsControl),base.restoreLocal); DWORD fields=preference(L"StatusFields",defaultStatusFields)&15; const auto initialFields=fields; for(int i=0;i<4;++i) @@ -1109,6 +1118,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) CheckDlgButton(dialog,rightClickMarksControl,rightClickMarks); CheckDlgButton(dialog,driveButtonsControl,showDriveButtons); CheckDlgButton(dialog,compactLayoutControl,compactLayout); + CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments); showPanelModeOptions(dialog); for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,(statusFields>>i)&1u); setOptionHistoryKeys(dialog,commandHistoryKeys); diff --git a/src/files_text_document.cpp b/src/files_text_document.cpp index 36a02b5..64c76e8 100644 --- a/src/files_text_document.cpp +++ b/src/files_text_document.cpp @@ -42,7 +42,7 @@ HANDLE openSource(const std::filesystem::path &path, bool editable) HANDLE trackReplacement(const std::filesystem::path &path) { // A metadata-only handle survives the rename without blocking ReplaceFile. - const auto handle=CreateFileW(path.c_str(),0,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, + const auto handle=CreateFileW(path.c_str(),FILE_READ_ATTRIBUTES,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr); if(handle==INVALID_HANDLE_VALUE) fail("Track replacement file"); return handle; @@ -98,6 +98,11 @@ std::filesystem::path createTemporary(const std::filesystem::path &directory, Fi return path; } +void createEditorSnapshot(File &file) +{ + createTemporary(std::filesystem::temp_directory_path(),file,FILE_ATTRIBUTE_TEMPORARY|FILE_FLAG_DELETE_ON_CLOSE); +} + bool isUtf16(TextEncoding encoding) { return encoding==TextEncoding::utf16le || encoding==TextEncoding::utf16be; @@ -182,8 +187,8 @@ std::string convertLineEndings(std::string_view text,TextLineEnding ending) } } -TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding) - : path_(std::move(path)), editable_(editable) +TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding,bool snapshotEdits) + : path_(std::move(path)), editable_(editable),snapshotEdits_(snapshotEdits && editable) { if(path_.empty()) { @@ -213,7 +218,20 @@ TextDocument::TextDocument(std::filesystem::path path,bool editable,TextEncoding encoding_=encoding; if(prefix.starts_with(signature(encoding_))) bom_=signature(encoding_).size(); if(isUtf16(encoding_) && size_%2) throw std::runtime_error("The UTF-16 file has an incomplete code unit."); - source_ = source.release(); + if(snapshotEdits_) + { + version_=fileVersion(source.handle); + File snapshot; + createEditorSnapshot(snapshot); + for(uint64_t offset=0;offset(std::min(pageBytes,size_-offset))); + write(snapshot.handle,block); + offset+=block.size(); + } + source_=snapshot.release(); + } + else source_ = source.release(); } TextDocument::~TextDocument() @@ -467,13 +485,26 @@ void TextDocument::stage(uint64_t page, std::string_view utf8) bool TextDocument::save() { if (!modified()) return true; + const auto verify=[&](HANDLE current) { + if(version_ && *version_!=fileVersion(current)) + throw std::runtime_error("The file changed outside Files. Your editor buffer was kept."); + if(!version_ && !sameFile(source_,current)) + throw std::runtime_error("The file was replaced outside KSwitcher."); + }; + if(version_) + { + File current{openSource(path_,true)}; + verify(current.handle); + } PendingSave pending; - File output; + File output,snapshot; + if(snapshotEdits_) createEditorSnapshot(snapshot); pending.path = createTemporary(path_.parent_path(), output, FILE_ATTRIBUTE_NORMAL); uint64_t written{}; const auto append = [&](std::string_view bytes) { write(output.handle, bytes); + if(snapshotEdits_) write(snapshot.handle,bytes); written += bytes.size(); }; const auto copyUntil = [&](uint64_t &offset, uint64_t end) { @@ -497,7 +528,7 @@ bool TextDocument::save() File replacement{trackReplacement(pending.path)}; File current{openSource(path_, true)}; - if (!sameFile(source_, current.handle)) throw std::runtime_error("The file was replaced outside KSwitcher."); + verify(current.handle); const auto backup = temporaryPath(path_.parent_path()); if (const auto error=replaceFileWithBackup(path_,pending.path,backup)) { @@ -505,7 +536,9 @@ bool TextDocument::save() fail("Replace original file"); } pending.path.clear(); - const auto newSource = ReOpenFile(replacement.handle, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, 0); + if(snapshotEdits_) version_=fileVersion(replacement.handle); + const auto newSource=snapshotEdits_?snapshot.release(): + ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0); DeleteFileW(backup.c_str()); CloseHandle(source_); source_ = newSource; @@ -523,10 +556,16 @@ bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format) const auto bytes=encode(convertLineEndings(readPage(0),format.lineEnding),format.encoding); const auto bom=format.bom?signature(format.encoding):std::string_view{}; PendingSave pending; - File output; + File output,snapshot; pending.path=createTemporary(path.parent_path(),output,FILE_ATTRIBUTE_NORMAL); write(output.handle,bom); write(output.handle,bytes); + if(snapshotEdits_) + { + createEditorSnapshot(snapshot); + write(snapshot.handle,bom); + write(snapshot.handle,bytes); + } if(!FlushFileBuffers(output.handle)) fail("Flush saved file"); CloseHandle(output.release()); File replacement{trackReplacement(pending.path)}; @@ -539,7 +578,8 @@ bool TextDocument::saveNew(std::filesystem::path path,TextSaveFormat format) changes_.clear(); if(spool_!=INVALID_HANDLE_VALUE) CloseHandle(std::exchange(spool_,INVALID_HANDLE_VALUE)); spoolSize_=0; - source_=ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0); + if(snapshotEdits_) version_=fileVersion(replacement.handle); + source_=snapshotEdits_?snapshot.release():ReOpenFile(replacement.handle,GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_DELETE,0); return source_!=INVALID_HANDLE_VALUE; } } diff --git a/src/files_text_document.h b/src/files_text_document.h index c45c59d..f482d4e 100644 --- a/src/files_text_document.h +++ b/src/files_text_document.h @@ -1,6 +1,6 @@ #pragma once -#include +#include "files_win32_replace.h" #include #include #include @@ -43,7 +43,7 @@ public: static constexpr size_t editLimit = 8 * pageBytes; explicit TextDocument(std::filesystem::path path, bool editable = true, - TextEncoding encoding=TextEncoding::automatic); + TextEncoding encoding=TextEncoding::automatic,bool snapshotEdits=false); ~TextDocument(); TextDocument(const TextDocument &) = delete; TextDocument &operator=(const TextDocument &) = delete; @@ -63,6 +63,7 @@ public: bool saveNew(std::filesystem::path path, TextSaveFormat format); const wchar_t *encodingName() const; TextEncoding encoding() const { return encoding_; } + const std::optional &expectedVersion() const {return version_;} private: struct Change { uint64_t offset; size_t size; }; @@ -73,7 +74,8 @@ private: uint64_t size_{}, spoolSize_{}; size_t bom_{}; TextEncoding encoding_ = TextEncoding::utf8; - bool editable_; + bool editable_, snapshotEdits_; + std::optional version_; std::map changes_; std::string decode(std::string bytes) const; diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index 19d5639..3921cf7 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -776,7 +776,7 @@ public: { if (backend) remote=std::make_unique(*backend,original); else if(!embedded) document=std::make_unique(draft?std::filesystem::path{}:original,edit, - hex?TextEncoding::utf8:options.encoding); + hex?TextEncoding::utf8:options.encoding,isLocalDocumentPath(original)); if(options.encoding!=TextEncoding::automatic) { newFormat.encoding=options.encoding; @@ -806,6 +806,8 @@ public: void previewFile(const std::filesystem::path &path); void previewEmbeddedText(const std::wstring &title,std::string_view contents,bool diff); bool openBookmark(const ViewerBookmark &bookmark); + nlohmann::json sessionState() const; + void restoreSession(const nlohmann::json &state); std::filesystem::path original; const std::string peerId; @@ -860,13 +862,8 @@ private: bool previewWanted{}, previewVisible{}, previewRetried{}; ULONGLONG previewDeadline{}; ULONGLONG nextFileCheck{}; - struct FileStamp - { - uint64_t writeTime, fileIndex, size; - DWORD volume; - bool operator==(const FileStamp &) const = default; - }; - std::optional previewStamp; + std::optional previewStamp, observedVersion; + bool diskChanged{}; struct MarkdownTask { uint64_t revision; @@ -875,6 +872,8 @@ private: }; std::string previewText; uint64_t previewRevision{}; + int renderedScroll{}; + std::optional sessionScroll; std::optional pendingTask; std::optional taskOffset; std::string previewFragment; @@ -918,6 +917,7 @@ private: static constexpr UINT_PTR quickViewTimer = 5; static constexpr UINT_PTR bookmarkTimer = 6; static constexpr UINT_PTR savedViewerTimer = 7; + static constexpr UINT_PTR externalChangeTimer = 8; struct BookmarkLocation { std::filesystem::path path; @@ -1012,7 +1012,7 @@ private: void changeMode(); ViewerPosition currentPosition() const; void restorePosition(const ViewerPosition &position); - void showTextMode(const ViewerPosition &position,std::string contents); + void showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus=true); void suspendEditor(std::unique_ptr saved={}); void restoreEditor(); void finishSavedViewer(); @@ -1024,7 +1024,9 @@ private: void stopPreview(bool refresh=true,bool keepBrowser=false); void renderPreview(bool keepPosition=false); void applyMarkdownPreferences(const MarkdownPreferences &preferences); - std::optional previewFileStamp() const; + std::optional previewFileStamp() const; + void rememberLocalVersion(); + void pollExternalChanges(); void refreshPreview(); void startMarkdownTask(); void finishMarkdownTask(); @@ -1625,6 +1627,7 @@ void TextWindow::go(uint64_t index) void TextWindow::initializeDocument(std::optional firstPage) { + rememberLocalVersion(); if(hex) { releaseMenu(); @@ -1905,6 +1908,7 @@ void TextWindow::finishSave() navigationHistory.clear(); updateTitle(); } + rememberLocalVersion(); if (!reopened) { search.style.message(window, L"The file was saved. Reopen it to continue editing."); @@ -2000,8 +2004,61 @@ void TextWindow::restorePosition(const ViewerPosition &position) send(SCI_SETXOFFSET,position.horizontal); } -void TextWindow::showTextMode(const ViewerPosition &position,std::string contents) +void writeDocumentPlacement(nlohmann::json &state,HWND window) { + WINDOWPLACEMENT placement{sizeof(placement)}; + if(GetWindowPlacement(window,&placement)) + { + const auto &rect=placement.rcNormalPosition; + state["rect"]={rect.left,rect.top,rect.right,rect.bottom}; + state["maximized"]=placement.showCmd==SW_SHOWMAXIMIZED || + (placement.flags&WPF_RESTORETOMAXIMIZED)!=0; + } +} + +RECT readDocumentBounds(const nlohmann::json &state) +{ + if(!state.contains("rect")) return {}; + const auto rect=state.at("rect").get>(); + return {rect[0],rect[1],rect[2],rect[3]}; +} + +int restoreDocumentPlacement(HWND window,HWND owner,const RECT &bounds,bool maximized) +{ + if(bounds.left>=bounds.right || bounds.top>=bounds.bottom || !MonitorFromRect(&bounds,MONITOR_DEFAULTTONULL)) + return IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW; + WINDOWPLACEMENT placement{sizeof(placement)}; + placement.rcNormalPosition=bounds; + placement.showCmd=maximized?SW_SHOWMAXIMIZED:SW_SHOWNORMAL; + SetWindowPlacement(window,&placement); + return maximized?SW_MAXIMIZE:SW_SHOWNORMAL; +} + +nlohmann::json TextWindow::sessionState() const +{ + if(embedded || remote || draft || !document || !isLocalDocumentPath(original)) return nullptr; + const auto position=currentPosition(); + nlohmann::json state{{"path",utf8(original.native())},{"editor",edit},{"hex",hex}, + {"page",position.page},{"anchor",position.anchor},{"caret",position.caret}, + {"firstLine",position.firstLine},{"horizontal",position.horizontal}}; + if(previewVisible) state["renderedScroll"]=renderedScroll; + writeDocumentPlacement(state,window); + return state; +} + +void TextWindow::restoreSession(const nlohmann::json &state) +{ + ViewerPosition position{std::min(state.value("page",uint64_t{}),pageTotal?pageTotal-1:0), + state.value("anchor",LRESULT{}),state.value("caret",LRESULT{}), + std::max(0,state.value("firstLine",LRESULT{})),std::max(0,state.value("horizontal",LRESULT{}))}; + if(position.page!=page) loadPage(position.page); + restorePosition(position); + if(state.contains("renderedScroll")) sessionScroll=std::max(0,state.at("renderedScroll").get()); +} + +void TextWindow::showTextMode(const ViewerPosition &position,std::string contents,bool takeFocus) +{ + rememberLocalVersion(); if(canPreview()) ShowWindow(editor,SW_HIDE); prefs = loadTextPreferences().profiles[edit]; releaseMenu(); @@ -2014,7 +2071,7 @@ void TextWindow::showTextMode(const ViewerPosition &position,std::string content updateTaskbarGroup(); updatePreview(); layout(); - focusContent(); + if(takeFocus) focusContent(); } void TextWindow::changeMode() @@ -2022,7 +2079,8 @@ void TextWindow::changeMode() if(!edit && remote && !remote->revision.editable) throw std::runtime_error("The remote file does not support editing."); auto position=currentPosition(); - auto replacement=std::make_unique(remote?remote->cache:original,!edit,document->encoding()); + auto replacement=std::make_unique(remote?remote->cache:original,!edit,document->encoding(), + !remote && isLocalDocumentPath(original)); position.page=std::min(position.page,replacement->pages()-1); auto contents=replacement->readPage(position.page); document=std::move(replacement); @@ -2237,20 +2295,55 @@ void TextWindow::goToFragment(std::string_view fragment) else previewFragment=fragment; } -std::optional TextWindow::previewFileStamp() const +std::optional TextWindow::previewFileStamp() const { - if(remote) return {}; + if(remote || !isLocalDocumentPath(original)) return {}; const auto file=CreateFileW(original.c_str(),FILE_READ_ATTRIBUTES, FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr); if(file==INVALID_HANDLE_VALUE) return {}; - BY_HANDLE_FILE_INFORMATION state{}; - const auto found=GetFileInformationByHandle(file,&state); + std::optional stamp; + try {stamp=fileVersion(file);} catch(const std::system_error &) {} CloseHandle(file); - if(!found) return {}; - const auto combine=[](DWORD high,DWORD low){return (uint64_t{high}<<32)|low;}; - return FileStamp{combine(state.ftLastWriteTime.dwHighDateTime,state.ftLastWriteTime.dwLowDateTime), - combine(state.nFileIndexHigh,state.nFileIndexLow), - combine(state.nFileSizeHigh,state.nFileSizeLow),state.dwVolumeSerialNumber}; + return stamp; +} + +void TextWindow::rememberLocalVersion() +{ + if(embedded || remote || !document) return; + observedVersion=edit?document->expectedVersion():previewFileStamp(); + diskChanged=false; +} + +void TextWindow::pollExternalChanges() +{ + if(embedded || remote || draft || !document || busy() || previewWanted || navigation.valid() || !observedVersion) + return; + const auto stamp=previewFileStamp(); + if(!stamp || stamp==observedVersion) return; + if(edit && (GetForegroundWindow()!=window || !IsWindowEnabled(window) || !search.style.reloadChanged)) return; + try + { + if(edit) + { + observedVersion=stamp; + diskChanged=true; + invalidate(); + if(!search.style.reloadChanged(window)) return; + } + auto replacement=std::make_unique(original,edit,hex?TextEncoding::utf8:TextEncoding::automatic,edit); + auto position=currentPosition(); + const auto pages=hex?1+(replacement->size()?replacement->size()-1:0)/hexPageBytes:replacement->pages(); + position.page=std::min(position.page,pages-1); + auto contents=hex?formatHexPage(replacement->readBytes(position.page*hexPageBytes,hexPageBytes), + position.page*hexPageBytes):replacement->readPage(position.page); + if(!hex) language=automatic=detectLanguage(original,contents); + document=std::move(replacement); + showTextMode(position,std::move(contents),edit); + } + catch(const std::exception &error) + { + if(edit) search.style.message(window,wide(error.what()).c_str()); + } } void TextWindow::renderPreview(bool keepPosition) @@ -2265,6 +2358,7 @@ void TextWindow::renderPreview(bool keepPosition) {"fragment",std::exchange(previewFragment,{})},{"title",utf8(filename)}, {"keepPosition",keepPosition}}; if(restoreScroll) message["scroll"]=navigationHistory[navigationIndex].scroll; + if(sessionScroll) message["scroll"]=*std::exchange(sessionScroll,{}); restoreScroll=false; preview.post(wide(message.dump(-1,' ',false,nlohmann::json::error_handler_t::replace))); } @@ -2438,6 +2532,11 @@ void TextWindow::previewMessage(const std::wstring &value) if(embedded && action!="image" && action!="rendered" && action!="failed") return; const auto revision=message.value("revision",previewRevision); if(embedded && revision!=previewRevision) return; + if(action=="scroll") + { + if(!embedded && revision==previewRevision) renderedScroll=std::max(0,message.at("top").get()); + return; + } if(action=="failed") { PostMessageW(window,previewFailed,static_cast(revision),0); @@ -2779,6 +2878,7 @@ void TextWindow::paint() if(pageTotal>1) status+=L" │ Page "+std::to_wstring(page+1)+L"/"+std::to_wstring(pageTotal)+ L" @ "+std::to_wstring(pageOffset); + if(diskChanged && edit) status+=L" │ Disk changed"; status+=L" │ "+std::to_wstring(fileSize)+L" B"; if(bookmarkTask.valid()) status+=L" │ Locating line…"; drawEditorStatus(dc,top,chromeFont,color(TextColor::chromebg),color(TextColor::chrome),scale(12),status); @@ -3083,6 +3183,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, else self->initializeDocument(); if(!self->embedded) { + if(!self->remote) SetTimer(window,externalChangeTimer,500,nullptr); self->updateIcons(GetDpiForWindow(window)); self->updateTaskbarGroup(); } @@ -3169,6 +3270,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, if (wparam == saveTimer) self->finishSave(); if (wparam == openTimer) self->finishOpen(); if (wparam == previewTimer) self->pollImages(); + if (wparam == externalChangeTimer) self->pollExternalChanges(); if (wparam == navigationTimer) self->finishNavigation(); if (wparam == quickViewTimer) self->pollQuickView(); if (wparam == bookmarkTimer) self->finishBookmark(); @@ -3427,7 +3529,8 @@ void previewImageQuickViewFile(HWND window,const std::filesystem::path &path) } void openImageWindow(HWND owner,std::vector images,const std::filesystem::path &path, - TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source,const ImageEditDialogs *editor) + TextDialogs dialogs,const lan::FilesPeer *peer,const RemoteTextSource *source,const ImageEditDialogs *editor, + const ImageWindowSession *session) { try { @@ -3469,15 +3572,23 @@ void openImageWindow(HWND owner,std::vector images,const const auto icon=LoadImageW(instance,MAKEINTRESOURCEW(iconId),IMAGE_ICON,0,0,LR_SHARED|LR_DEFAULTSIZE); if(icon) SendMessageW(window,WM_SETICON,ICON_BIG,reinterpret_cast(icon)); setFileWindowTaskbar(window,iconId,editor?L"HrynCo.KSwitcher.Files.Editor":L"HrynCo.KSwitcher.Files.Viewer"); - ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW); + if(session) restoreImageWindowSession(window,*session); + ShowWindow(window,session?restoreDocumentPlacement(window,owner,session->bounds,session->maximized): + IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW); SetFocus(window); } - catch(const std::exception &error) {dialogs.message(owner,wide(error.what()).c_str());} + catch(const std::exception &error) + { + if(!session) dialogs.message(owner,wide(error.what()).c_str()); + else log(L"Restore Files image: "+wide(error.what())); + } } static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, - const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options) + const RemoteTextSource *backend,std::string_view fragment,bool newWindow,TextOpenOptions options, + const nlohmann::json *session=nullptr) { + HWND created{}; if(!edit && !options.draft && !options.hex && !options.line && isImagePath(path)) { openImageWindow(owner,{path},path,dialogs,nullptr,backend); @@ -3513,10 +3624,90 @@ static void openTextWindowImpl(HWND owner,const std::filesystem::path &path,bool WS_OVERLAPPEDWINDOW|WS_CLIPCHILDREN,bounds.left,bounds.top,bounds.right-bounds.left, bounds.bottom-bounds.top,nullptr,nullptr,instance,&state); if(!window) return; - ShowWindow(window,IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW); + created=window; + int show=IsZoomed(owner)?SW_MAXIMIZE:SW_SHOW; + if(session) + { + state->restoreSession(*session); + show=restoreDocumentPlacement(window,owner,readDocumentBounds(*session),session->value("maximized",false)); + } + ShowWindow(window,show); SendMessageW(window,WM_SETFOCUS,0,0); } - catch(const std::exception &error){dialogs.message(owner,wide(error.what()).c_str());} + catch(const std::exception &error) + { + if(!session) dialogs.message(owner,wide(error.what()).c_str()); + else + { + if(created) DestroyWindow(created); + log(L"Restore Files document: "+wide(error.what())); + } + } +} + +constexpr wchar_t localSessionKey[]=L"LocalDocumentsV1"; + +void saveLocalDocumentSession(const wchar_t *registryKey,bool enabled) +{ + if(!enabled) + { + RegDeleteKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey); + return; + } + auto session=nlohmann::json::array(); + for(const auto window:textWindowOrder) + { + if(session.size()>=128) break; + if(const auto found=textWindows.find(window);found!=textWindows.end()) + { + auto state=found->second->sessionState(); + if(!state.is_null()) session.push_back(std::move(state)); + } + else if(const auto image=imageWindowSession(window)) + { + nlohmann::json state{{"path",utf8(image->path.native())},{"editor",image->editor},{"image",true}, + {"fit",image->fit},{"zoom",image->zoom},{"x",image->x},{"y",image->y}}; + writeDocumentPlacement(state,window); + session.push_back(std::move(state)); + } + } + const auto text=session.dump(); + if(text.size()<=1024*1024) + RegSetKeyValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,REG_BINARY,text.data(),static_cast(text.size())); +} + +void restoreLocalDocumentSession(HWND owner,TextDialogs dialogs,const wchar_t *registryKey, + const ImageEditDialogs &imageEditor) +{ + DWORD bytes{}; + if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS || + !bytes || bytes>1024*1024) return; + std::string text(bytes,'\0'); + if(RegGetValueW(HKEY_CURRENT_USER,registryKey,localSessionKey,RRF_RT_REG_BINARY,nullptr,text.data(),&bytes)!=ERROR_SUCCESS) + return; + const auto session=nlohmann::json::parse(text.begin(),text.begin()+bytes,nullptr,false); + if(!session.is_array()) return; + for(size_t i=0;i(128,session.size());++i) + { + try + { + const auto &state=session[i]; + const std::filesystem::path path=wide(state.at("path").get()); + if(!isLocalDocumentPath(path)) continue; + const auto attributes=GetFileAttributesW(path.c_str()); + if(attributes==INVALID_FILE_ATTRIBUTES || (attributes&FILE_ATTRIBUTE_DIRECTORY)) continue; + const bool editor=state.value("editor",false); + if(state.value("image",false)) + { + if(!isImagePath(path) || (editor && !isEditableImagePath(path))) continue; + ImageWindowSession image{path,editor,state.value("fit",true),state.value("zoom",1.0), + state.value("x",0.0),state.value("y",0.0),readDocumentBounds(state),state.value("maximized",false)}; + openImageWindow(owner,{path},path,dialogs,nullptr,nullptr,editor?&imageEditor:nullptr,&image); + } + else openTextWindowImpl(owner,path,editor,dialogs,nullptr,{},true,{.hex=state.value("hex",false)},&state); + } + catch(const std::exception &error) {log(L"Restore Files document: "+wide(error.what()));} + } } void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, diff --git a/src/files_text_window.h b/src/files_text_window.h index d0c9d26..37ef170 100644 --- a/src/files_text_window.h +++ b/src/files_text_window.h @@ -57,6 +57,7 @@ struct TextDialogs bool (*dismissOwned)(HWND); bool (*confirmExisting)(HWND); bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &); + bool (*reloadChanged)(HWND){}; }; struct TextOpenOptions @@ -110,9 +111,10 @@ void previewQuickViewText(HWND window,const std::wstring &title,std::string_view HWND createImageQuickView(HWND owner,TextDialogs dialogs); void previewImageQuickViewFile(HWND window,const std::filesystem::path &path); struct ImageEditDialogs; +struct ImageWindowSession; void openImageWindow(HWND owner,std::vector images,const std::filesystem::path &path, TextDialogs dialogs,const lan::FilesPeer *peer=nullptr,const RemoteTextSource *source=nullptr, - const ImageEditDialogs *editor=nullptr); + const ImageEditDialogs *editor=nullptr,const ImageWindowSession *session=nullptr); void showAllViewerBookmarks(HWND owner,TextDialogs dialogs); void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, @@ -120,6 +122,8 @@ void openTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextD TextOpenOptions options={}); void openRemoteTextWindow(HWND owner,const std::filesystem::path &path,bool edit,TextDialogs dialogs, const RemoteTextSource &source,std::string_view fragment={},bool newWindow=false,TextOpenOptions options={}); +void saveLocalDocumentSession(const wchar_t *registryKey,bool enabled); +void restoreLocalDocumentSession(HWND owner,TextDialogs dialogs,const wchar_t *registryKey,const ImageEditDialogs &imageEditor); void textWindowOwnerClosed(); void standaloneFilesWindowOpened(); void standaloneFilesWindowClosed(); diff --git a/src/files_win32_replace.h b/src/files_win32_replace.h index ed23ada..2454bdb 100644 --- a/src/files_win32_replace.h +++ b/src/files_win32_replace.h @@ -5,9 +5,20 @@ #include #include #include +#include +#include namespace ks::files { +inline bool isLocalDocumentPath(const std::filesystem::path &path) +{ + std::wstring_view name=path.native(); + if(name.starts_with(L"\\\\?\\")) name.remove_prefix(4); + if(name.size()<3 || name[1]!=L':' || (name[2]!=L'\\' && name[2]!=L'/')) return false; + const auto type=GetDriveTypeW(std::wstring(name.substr(0,3)).c_str()); + return type==DRIVE_FIXED || type==DRIVE_REMOVABLE || type==DRIVE_RAMDISK || type==DRIVE_CDROM; +} + inline std::filesystem::path temporaryPath(const std::filesystem::path &directory) { GUID id{}; @@ -23,6 +34,31 @@ inline bool sameFileIdentity(const BY_HANDLE_FILE_INFORMATION &left,const BY_HAN left.nFileIndexLow==right.nFileIndexLow; } + +struct LocalFileVersion +{ + BY_HANDLE_FILE_INFORMATION info{}; + LONGLONG changeTime{}; + + bool operator==(const LocalFileVersion &other) const + { + return sameFileIdentity(info,other.info) && changeTime==other.changeTime && + info.nFileSizeHigh==other.info.nFileSizeHigh && info.nFileSizeLow==other.info.nFileSizeLow && + CompareFileTime(&info.ftLastWriteTime,&other.info.ftLastWriteTime)==0; + } +}; + +inline LocalFileVersion fileVersion(HANDLE file) +{ + LocalFileVersion version; + if(!GetFileInformationByHandle(file,&version.info)) + throw std::system_error(static_cast(GetLastError()),std::system_category(),"Read file revision"); + FILE_BASIC_INFO basics{}; + if(GetFileInformationByHandleEx(file,FileBasicInfo,&basics,sizeof(basics))) + version.changeTime=basics.ChangeTime.QuadPart; + return version; +} + inline DWORD replaceFileWithBackup(const std::filesystem::path &original,const std::filesystem::path &replacement, const std::filesystem::path &backup) { diff --git a/tests/files_text_document.cpp b/tests/files_text_document.cpp index 7c834a3..95cd17e 100644 --- a/tests/files_text_document.cpp +++ b/tests/files_text_document.cpp @@ -171,6 +171,29 @@ void hexBytes(const fs::path &file) "Hex offsets advance by the row width"); } +void watchedEditor(const fs::path &file) +{ + writeFile(file,"original bytes"); + TextDocument editor(file,true,TextEncoding::automatic,true); + check(editor.expectedVersion().has_value(),"local editor captured the original version"); + writeFile(file,"external bytes"); + check(editor.readPage(0)=="original bytes","external edit replaced the editor snapshot"); + editor.stage(0,"editor buffer"); + bool rejected=false; + try {editor.save();} + catch(const std::runtime_error &error) + { + rejected=std::string_view(error.what()).find("changed outside Files")!=std::string_view::npos; + } + check(rejected && editor.readPage(0)=="editor buffer","external edit was overwritten or the draft was cleared"); + TextDocument reloaded(file,true,TextEncoding::automatic,true); + check(reloaded.readPage(0)=="external bytes","reload did not take the external version"); + reloaded.stage(0,"confirmed write"); + check(reloaded.save() && reloaded.readPage(0)=="confirmed write","local save lost the new snapshot"); + writeFile(file,"next change"); + check(reloaded.readPage(0)=="confirmed write","the post-save editor lost snapshot isolation"); +} + void bookmarkedLines(const fs::path &file) { const auto longLine=std::string(TextDocument::pageBytes+32,'x'); @@ -262,6 +285,7 @@ int main() rejectExternalReplacement(fixture.directory / L"external.txt"); saveDraft(fixture.directory / L"created.txt"); hexBytes(fixture.directory / L"raw.bin"); + watchedEditor(fixture.directory / L"watched.txt"); bookmarkedLines(fixture.directory / L"bookmarks.txt"); comparisonEdits(); sparseFile(fixture.directory / L"5gib.log"); From eb0f6ead7269908ec1c1508463e843e94ac2ff19 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 22:54:25 +0200 Subject: [PATCH 44/61] Add named keyboard schemes for Files commands Refs #128 --- FILES-UI.md | 1 + resources/files.rc | 40 ++++- src/files_command_history.inl | 57 ------- src/files_compare.inl | 23 --- src/files_key_schemes.inl | 255 +++++++++++++++++++++++++++++++ src/files_key_schemes_dialog.inl | 220 ++++++++++++++++++++++++++ src/files_main.cpp | 246 +++++++++++++---------------- src/files_options.inl | 54 ++----- 8 files changed, 630 insertions(+), 266 deletions(-) create mode 100644 src/files_key_schemes.inl create mode 100644 src/files_key_schemes_dialog.inl diff --git a/FILES-UI.md b/FILES-UI.md index b18561d..3f858dd 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -741,6 +741,7 @@ Warning і початковий фокус на No. - При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання. - Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку. +- Commands → Keyboard shortcuts відкриває іменовані схеми для команд файлових панелей та історії команд. У схемі можна задати кілька клавіш, вибрати основну, вилучити прив’язку, скопіювати схему під новим іменем, перемкнути чи скинути її. OK зберігає активну схему. Меню показує всі прив’язки, нижній ряд і текстові підказки відображають основну. Діалог відхиляє дублікати в контекстах, що перетинаються, і клавіші, зайняті навігацією. Попередні прив’язки історії та порівняння завантажуються як схема Previous settings. - Appearance → Dialog frame налаштовує зовнішній і внутрішній відступи від 0 до 24 px при 96 DPI. Row text padding додає від 0 до 4 ширин символу з кожного боку тексту в рядках Folder shortcuts. Inner padding задає відстань від рамки до краю списку. Ширина попапа враховує обидва текстові відступи, а довгі шляхи скорочуються в межах доступної ширини. Живий зразок показує чернетку. Apply зберігає значення, Cancel відкидає незастосовані зміни, Reset selected to defaults повертає 8 px, 14 px і 0 символів. Профілі без цих параметрів використовують ті самі значення. - У ресурсі чи виклику задавай назву кнопки й клавішу доступу. Спільна функція `paintDialogButton` центрує текст, підсвічує фокус і додає фігурні дужки для дії за замовчуванням та квадратні для решти кнопок. - Модальні діалоги редактора й переглядача використовують той самий шрифт, що й діалоги операцій Files. Розміри полів і кнопок враховують метрики цього шрифту. diff --git a/resources/files.rc b/resources/files.rc index a0cbb4c..c8332da 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -156,6 +156,38 @@ BEGIN PUSHBUTTON "Cancel", IDCANCEL, 162, 44, 50, 14 END +615 DIALOGEX 0, 0, 371, 214 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Keyboard shortcuts" +FONT 9, "Segoe UI" +BEGIN + LTEXT "Active &scheme", -1, 9, 9, 160, 11 + COMBOBOX 610, 9, 22, 194, 120, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL + PUSHBUTTON "&Copy as…", 611, 211, 22, 69, 15 + PUSHBUTTON "Rese&t scheme", 612, 288, 22, 74, 15 + LTEXT "&Command", -1, 9, 49, 166, 11 + LISTBOX 613, 9, 63, 166, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP + LTEXT "", 614, 184, 49, 178, 11 + LISTBOX 615, 184, 63, 178, 80, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP + CONTROL "", 616, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 184, 152, 74, 15 + PUSHBUTTON "&Add", 617, 264, 152, 44, 15 + PUSHBUTTON "&Remove", 618, 314, 152, 48, 15 + PUSHBUTTON "Make &primary", 619, 184, 172, 75, 15 + DEFPUSHBUTTON "OK", IDOK, 250, 192, 52, 15 + PUSHBUTTON "Cancel", IDCANCEL, 310, 192, 52, 15 +END + +616 DIALOGEX 0, 0, 233, 73 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Copy keyboard scheme" +FONT 9, "Segoe UI" +BEGIN + LTEXT "Scheme &name", -1, 9, 9, 214, 11 + EDITTEXT 620, 9, 23, 215, 15, ES_AUTOHSCROLL + DEFPUSHBUTTON "Copy", IDOK, 112, 49, 52, 15 + PUSHBUTTON "Cancel", IDCANCEL, 172, 49, 52, 15 +END + 101 DIALOGEX 0, 0, 397, 310 STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN CAPTION "KSwitcher Files Options" @@ -194,10 +226,7 @@ BEGIN COMBOBOX 305, 311, 51, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL LTEXT "&Row text padding (characters)", 306, 131, 77, 173, 12 COMBOBOX 307, 311, 74, 56, 76, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL - LTEXT "Previous command", 320, 131, 30, 120, 12 - CONTROL "", 321, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 27, 110, 15 - LTEXT "Open command history", 322, 131, 53, 120, 12 - CONTROL "", 323, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 260, 50, 110, 15 + PUSHBUTTON "&Keyboard shortcuts…", 321, 131, 30, 127, 15 AUTOCHECKBOX "Allow &paired PCs to run PowerShell commands here", 370, 131, 79, 250, 14 AUTOCHECKBOX "Allow paired PCs to &hibernate this PC", 371, 131, 95, 250, 14 AUTOCHECKBOX "Allow paired PCs to &update KSwitcher here", 372, 131, 111, 250, 14 @@ -250,8 +279,7 @@ BEGIN COMBOBOX 411, 250, 76, 132, 126, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL PUSHBUTTON "Change color…", 412, 250, 97, 82, 15 LTEXT "", 413, 338, 100, 45, 12 - LTEXT "Compare files &shortcut", 414, 131, 130, 117, 12 - CONTROL "", 415, "msctls_hotkey32", WS_TABSTOP | WS_BORDER, 250, 127, 132, 15 + PUSHBUTTON "&Keyboard shortcuts…", 415, 131, 127, 127, 15 DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14 PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14 PUSHBUTTON "&Apply", 283, 338, 289, 50, 14 diff --git a/src/files_command_history.inl b/src/files_command_history.inl index 44f073d..9784c48 100644 --- a/src/files_command_history.inl +++ b/src/files_command_history.inl @@ -1,5 +1,3 @@ -constexpr std::array defaultHistoryKeys{MAKEWORD('E',HOTKEYF_CONTROL),MAKEWORD(VK_F8,HOTKEYF_ALT)}; -auto commandHistoryKeys=defaultHistoryKeys; constexpr size_t commandHistoryLimit=1000; std::wstring commandHistoryLabel(const std::wstring &command) @@ -19,41 +17,6 @@ std::wstring commandHistoryLabel(const std::wstring &command) return fs::path(path).is_absolute()?path:command; } -bool validHistoryKeys(const std::array &keys) -{ - if(keys[0]==keys[1]) return false; - return std::all_of(keys.begin(),keys.end(),[](WORD binding) - { - const auto key=LOBYTE(binding), modifiers=HIBYTE(binding); - const bool letter=key>='A' && key<='Z'; - const bool function=key>=VK_F1 && key<=VK_F12; - if(!letter && !function) return false; - if(modifiers==HOTKEYF_CONTROL) - return letter && key!='C' && key!='F' && key!='R' && key!='V' && key!='X' && key!='A' && key!='Z' && key!='Y'; - if(modifiers==HOTKEYF_ALT) return function && key!=VK_F1 && key!=VK_F2 && key!=VK_F4 && key!=VK_F10; - return false; - }); -} - -std::array optionHistoryKeys(HWND dialog) -{ - return {static_cast(SendDlgItemMessageW(dialog,321,HKM_GETHOTKEY,0,0)), - static_cast(SendDlgItemMessageW(dialog,323,HKM_GETHOTKEY,0,0))}; -} - -void setOptionHistoryKeys(HWND dialog,const std::array &keys) -{ - SendDlgItemMessageW(dialog,321,HKM_SETHOTKEY,keys[0],0); - SendDlgItemMessageW(dialog,323,HKM_SETHOTKEY,keys[1],0); -} - -void loadCommandHistoryKeys() -{ - const std::array keys{static_cast(preference(L"PreviousCommandKey",defaultHistoryKeys[0])), - static_cast(preference(L"CommandHistoryKey",defaultHistoryKeys[1]))}; - commandHistoryKeys=validHistoryKeys(keys)?keys:defaultHistoryKeys; -} - void loadCommandHistory() { @@ -107,23 +70,3 @@ void recallPreviousCommand() if(terminalHistoryIndex==terminalHistory.size()) terminalHistoryDraft=terminalInputText(); recallCommand(terminalHistoryIndex-1); } - -void showCommandHistory(HWND owner); - -bool handleCommandHistoryKey(HWND window,const MSG &message) -{ - if(message.message!=WM_KEYDOWN && message.message!=WM_SYSKEYDOWN) return false; - if((GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000)) return false; - const BYTE modifiers=((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0) | - ((GetKeyState(VK_MENU)&0x8000)?HOTKEYF_ALT:0) | ((GetKeyState(VK_SHIFT)&0x8000)?HOTKEYF_SHIFT:0); - const auto binding=MAKEWORD(message.wParam,modifiers); - if(binding==commandHistoryKeys[0] && (message.hwnd==terminalInput || - message.hwnd==panels[0].list || message.hwnd==panels[1].list)) - { - recallPreviousCommand(); - return true; - } - if(binding!=commandHistoryKeys[1]) return false; - if(!(message.lParam&(1LL<<30))) showCommandHistory(window); - return true; -} diff --git a/src/files_compare.inl b/src/files_compare.inl index 9b48638..a9968c5 100644 --- a/src/files_compare.inl +++ b/src/files_compare.inl @@ -4,31 +4,8 @@ enum ComparisonColor { CompareBackground, CompareText, CompareInsert, CompareDel constexpr const wchar_t *comparisonColorNames[]{L"Background",L"Text",L"Insertion",L"Deletion",L"Replacement", L"Changed fragment",L"Alignment padding",L"Divider",L"Text on changed lines"}; constexpr wchar_t comparisonAppearanceKey[]=L"ComparisonAppearance"; -constexpr wchar_t comparisonShortcutKey[]=L"ComparisonShortcut"; -constexpr WORD defaultComparisonShortcut=MAKEWORD(VK_F11,HOTKEYF_SHIFT); -WORD comparisonShortcut=defaultComparisonShortcut; constexpr int comparisonSplitScale=10000; -bool validComparisonShortcut(WORD shortcut) -{ - const auto key=LOBYTE(shortcut),modifiers=HIBYTE(shortcut); - return key>=VK_F1 && key<=VK_F12 && - (modifiers==(HOTKEYF_CONTROL|HOTKEYF_SHIFT) || - (modifiers==HOTKEYF_SHIFT && key!=VK_F4 && key!=VK_F8)); -} - -void loadComparisonShortcut() -{ - const auto shortcut=static_cast(preference(comparisonShortcutKey,defaultComparisonShortcut)); - comparisonShortcut=validComparisonShortcut(shortcut)?shortcut:defaultComparisonShortcut; -} - -std::wstring comparisonShortcutLabel() -{ - return std::wstring(HIBYTE(comparisonShortcut)&HOTKEYF_CONTROL?L"Ctrl+Shift+F":L"Shift+F")+ - std::to_wstring(LOBYTE(comparisonShortcut)-VK_F1+1); -} - struct ComparisonAppearance { LOGFONTW font=defaultFilesFont(); diff --git a/src/files_key_schemes.inl b/src/files_key_schemes.inl new file mode 100644 index 0000000..5029bfb --- /dev/null +++ b/src/files_key_schemes.inl @@ -0,0 +1,255 @@ +enum KeyContext : unsigned { panelKeyContext=1, terminalKeyContext=2 }; +enum class FilesKey +{ + Refresh, View, Edit, Copy, Move, Mkdir, Delete, Exit, Compare, Previous, History, + Pack, Find, ExternalView, ExternalEdit, QuickView, FullPath, HexView, Swap, Properties, Next, Count +}; +constexpr size_t keyIndex(FilesKey command) { return static_cast(command); } +constexpr unsigned bothKeyContexts=panelKeyContext|terminalKeyContext; +constexpr WORD chord(BYTE key,BYTE modifiers=0) { return MAKEWORD(key,modifiers); } +constexpr BYTE keyCtrl=HOTKEYF_CONTROL,keyShift=HOTKEYF_SHIFT,keyAlt=HOTKEYF_ALT; +constexpr struct +{ + const char *id; + const wchar_t *label; + unsigned contexts; + std::array defaults; +} filesKeyCommands[]{ + {"refresh",L"Refresh panel",bothKeyContexts,{chord('R',keyCtrl),chord(VK_F2)}}, + {"view",L"View",panelKeyContext,{chord(VK_F3)}}, + {"edit",L"Edit",panelKeyContext,{chord(VK_F4)}}, + {"copy",L"Copy",panelKeyContext,{chord(VK_F5)}}, + {"move",L"Move",panelKeyContext,{chord(VK_F6)}}, + {"mkdir",L"Make folder",panelKeyContext,{chord(VK_F7)}}, + {"delete",L"Delete to Recycle Bin",panelKeyContext,{chord(VK_F8)}}, + {"exit",L"Exit",bothKeyContexts,{chord(VK_F10)}}, + {"compare",L"Compare files",panelKeyContext,{chord(VK_F11,keyShift)}}, + {"previous",L"Previous command",bothKeyContexts,{chord('E',keyCtrl)}}, + {"history",L"Command history",bothKeyContexts,{chord(VK_F8,keyAlt)}}, + {"pack",L"Pack files",panelKeyContext,{chord(VK_F5,keyAlt)}}, + {"find",L"Find files",panelKeyContext,{chord(VK_F7,keyAlt)}}, + {"externalView",L"View externally",panelKeyContext,{chord(VK_F3,keyAlt)}}, + {"externalEdit",L"Edit externally",panelKeyContext,{chord(VK_F4,keyAlt)}}, + {"quickView",L"Quick View",panelKeyContext,{chord('Q',keyCtrl)}}, + {"fullPath",L"Copy full path",panelKeyContext,{chord('C',keyCtrl|keyShift)}}, + {"hexView",L"View as hex",panelKeyContext,{chord(VK_F3,keyShift)}}, + {"swap",L"Swap panels",panelKeyContext,{chord('U',keyCtrl)}}, + {"properties",L"Properties",panelKeyContext,{chord('A',keyCtrl)}}, + {"next",L"Next command",terminalKeyContext,{chord(VK_DOWN)}}, +}; +static_assert(std::size(filesKeyCommands)==keyIndex(FilesKey::Count)); +constexpr size_t filesKeySchemeLimit=24,filesKeysPerCommand=8; +constexpr wchar_t filesKeySchemePreference[]=L"KeySchemesV1"; + +struct FilesKeyScheme +{ + std::wstring name; + std::array,keyIndex(FilesKey::Count)> keys; + bool operator==(const FilesKeyScheme &) const=default; +}; + +struct FilesKeySettings +{ + std::vector schemes; + size_t active{}; + bool operator==(const FilesKeySettings &) const=default; +}; + +std::wstring filesKeyLabel(WORD binding) +{ + if(!binding) return {}; + std::wstring label; + if(HIBYTE(binding)&keyCtrl) label+=L"Ctrl+"; + if(HIBYTE(binding)&keyAlt) label+=L"Alt+"; + if(HIBYTE(binding)&keyShift) label+=L"Shift+"; + const auto key=LOBYTE(binding); + if(key>=VK_F1 && key<=VK_F24) label+=L"F"+std::to_wstring(key-VK_F1+1); + else if(key==VK_DOWN) label+=L"Down"; + else label+=static_cast(key); + return label; +} + +FilesKeyScheme defaultFilesKeyScheme(std::wstring name=L"Default") +{ + FilesKeyScheme scheme{std::move(name),{}}; + for(size_t command=0;command(first.size()), + second.data(),static_cast(second.size()),TRUE)==CSTR_EQUAL; +} + +bool validFilesKeySchemeName(std::wstring_view name) +{ + return !name.empty() && name.size()<=48 && !iswspace(name.front()) && !iswspace(name.back()) && + std::ranges::none_of(name,[](wchar_t character){return iswcntrl(character);}); +} + +unsigned reservedFilesKeyContexts(WORD binding) +{ + const auto key=LOBYTE(binding),mods=HIBYTE(binding); + if(key>=VK_F1 && key<=VK_F24) + { + if(mods==keyAlt && key==VK_F4) return terminalKeyContext; + if((!mods && key==VK_F9) || (mods==keyAlt && (key==VK_F1 || key==VK_F2 || key==VK_F10)) || + (mods==keyShift && key==VK_F4) || (mods==keyShift && key==VK_F10) || + (mods==keyCtrl && key<=VK_F12)) + return panelKeyContext; + return 0; + } + if(key==VK_DOWN && !mods) return panelKeyContext; + if(key>='A' && key<='Z' && (mods&keyCtrl) && !(mods&keyAlt)) + { + constexpr std::wstring_view editing=L"CFOPVXYZ"; + if(mods==keyCtrl && editing.find(key)!=editing.npos) return bothKeyContexts; + if((mods==keyCtrl && key=='A') || (mods==(keyCtrl|keyShift) && (key=='C' || key=='V'))) + return terminalKeyContext; + return 0; + } + return bothKeyContexts; +} + +std::wstring filesKeyConflict(const FilesKeyScheme &scheme,size_t command,WORD binding) +{ + if(!binding || (HIBYTE(binding)&~(keyCtrl|keyShift|keyAlt))) + return L"Use a function key or a letter with Ctrl."; + const auto contexts=filesKeyCommands[command].contexts; + if(reservedFilesKeyContexts(binding)&contexts) + return filesKeyLabel(binding)+L" is reserved or unavailable in this context."; + for(size_t i=0;i parseFilesKeySettings(const Json &stored) +{ + try + { + if(stored.at("version")!=1 || !stored.at("schemes").is_array()) return {}; + const auto &rows=stored.at("schemes"); + if(rows.empty() || rows.size()>filesKeySchemeLimit) return {}; + FilesKeySettings settings; + const auto active=stored.at("active").get(); + for(const auto &row:rows) + { + auto name=ks::wide(row.at("name").get()); + if(!validFilesKeySchemeName(name) || + std::ranges::any_of(settings.schemes,[&](const auto &other) + { return sameFilesKeySchemeName(other.name,name); })) return {}; + FilesKeyScheme scheme{std::move(name),{}}; + const auto &commands=row.at("commands"); + if(!commands.is_object()) return {}; + for(size_t i=0;iis_array() || found->size()>filesKeysPerCommand) return {}; + for(const auto &entry:*found) + { + if(!entry.is_number_unsigned() || entry>0xffff) return {}; + const auto binding=entry.get(); + if(!filesKeyConflict(scheme,i,binding).empty()) return {}; + scheme.keys[i].push_back(binding); + } + } + for(size_t i=0;i(preference(item.name,fallback)); + const auto context=filesKeyCommands[index].contexts; + if(binding==fallback || (HIBYTE(binding)&~(keyCtrl|keyShift|keyAlt)) || + (reservedFilesKeyContexts(binding)&context)) continue; + for(size_t i=0;i0xff || ((GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) return 0; + return chord(static_cast(key),((GetKeyState(VK_CONTROL)&0x8000)?keyCtrl:0) | + ((GetKeyState(VK_SHIFT)&0x8000)?keyShift:0) | ((GetKeyState(VK_MENU)&0x8000)?keyAlt:0)); +} + +std::optional boundFilesCommand(WORD binding,unsigned context) +{ + const auto &keys=filesKeySettings.schemes[filesKeySettings.active].keys; + for(size_t i=0;i(i); + return {}; +} + +std::wstring filesKeyHint(FilesKey command,bool all=false) +{ + std::wstring text; + for(const auto binding:filesKeySettings.schemes[filesKeySettings.active].keys[keyIndex(command)]) + { + if(!text.empty()) text+=L", "; + text+=filesKeyLabel(binding); + if(!all) break; + } + return text; +} + +std::wstring filesKeyMenuLabel(FilesKey command,std::wstring label={}) +{ + if(label.empty()) label=filesKeyCommands[keyIndex(command)].label; + const auto keys=filesKeyHint(command,true); + if(!keys.empty()) label+=L"\t"+keys; + return label; +} diff --git a/src/files_key_schemes_dialog.inl b/src/files_key_schemes_dialog.inl new file mode 100644 index 0000000..191c7fc --- /dev/null +++ b/src/files_key_schemes_dialog.inl @@ -0,0 +1,220 @@ +constexpr int keySchemeChoice=610,keySchemeCopy=611,keySchemeReset=612,keySchemeCommand=613, + keySchemeContext=614,keySchemeBindings=615,keySchemeCapture=616,keySchemeAdd=617,keySchemeRemove=618, + keySchemePrimary=619,keySchemeName=620; + +struct FilesKeySchemeDraft +{ + FilesKeySettings base=filesKeySettings,settings=base; + FilesKey initial; +}; + +INT_PTR CALLBACK copyKeySchemeDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + SetWindowLongPtrW(dialog,DWLP_USER,lp); + auto &name=*reinterpret_cast(lp); + SendDlgItemMessageW(dialog,keySchemeName,EM_SETLIMITTEXT,48,0); + SetDlgItemTextW(dialog,keySchemeName,name.c_str()); + return TRUE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND || LOWORD(wp)!=IDOK) return FALSE; + auto &name=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + wchar_t entry[49]{}; + GetDlgItemTextW(dialog,keySchemeName,entry,std::size(entry)); + name=entry; + FilesModalDialog::finish(dialog,IDOK); + return TRUE; +} + +void refreshFilesKeyBindings(HWND dialog,const FilesKeyScheme &scheme,size_t command,size_t selection=0) +{ + const auto &descriptor=filesKeyCommands[command]; + SetDlgItemTextW(dialog,keySchemeContext, + descriptor.contexts==bothKeyContexts?L"Keys · panels and command output": + descriptor.contexts==terminalKeyContext?L"Keys · command output":L"Keys · file panels"); + const auto list=GetDlgItem(dialog,keySchemeBindings); + SendMessageW(list,LB_RESETCONTENT,0,0); + const auto &keys=scheme.keys[command]; + for(size_t i=0;i(label.c_str())); + } + if(!keys.empty()) SendMessageW(list,LB_SETCURSEL,std::min(selection,keys.size()-1),0); + EnableWindow(GetDlgItem(dialog,keySchemeRemove),!keys.empty()); + EnableWindow(GetDlgItem(dialog,keySchemePrimary),keys.size()>1 && selection>0 && selection(scheme.name.c_str())); + SendMessageW(choice,CB_SETCURSEL,settings.active,0); + EnableWindow(GetDlgItem(dialog,keySchemeCopy),settings.schemes.size()(lp); + SetWindowLongPtrW(dialog,DWLP_USER,lp); + refreshFilesKeySchemes(dialog,draft.settings); + for(const auto &item:filesKeyCommands) + SendDlgItemMessageW(dialog,keySchemeCommand,LB_ADDSTRING,0,reinterpret_cast(item.label)); + const auto index=keyIndex(draft.initial); + SendDlgItemMessageW(dialog,keySchemeCommand,LB_SETCURSEL,index,0); + refreshFilesKeyBindings(dialog,draft.settings.schemes[draft.settings.active],index); + return TRUE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND) return FALSE; + auto &draft=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + auto &settings=draft.settings; + auto &scheme=settings.schemes[settings.active]; + const auto row=SendDlgItemMessageW(dialog,keySchemeCommand,LB_GETCURSEL,0,0); + if(row==LB_ERR) return FALSE; + const auto command=static_cast(row); + const auto position=static_cast(SendDlgItemMessageW(dialog,keySchemeBindings,LB_GETCURSEL,0,0)); + auto &keys=scheme.keys[command]; + switch(LOWORD(wp)) + { + case keySchemeChoice: + if(HIWORD(wp)==CBN_SELCHANGE) + { + const auto chosen=SendDlgItemMessageW(dialog,keySchemeChoice,CB_GETCURSEL,0,0); + if(chosen!=CB_ERR) settings.active=static_cast(chosen); + refreshFilesKeyBindings(dialog,settings.schemes[settings.active],command); + } + return TRUE; + case keySchemeCommand: + if(HIWORD(wp)==LBN_SELCHANGE) refreshFilesKeyBindings(dialog,scheme,command); + return TRUE; + case keySchemeBindings: + if(HIWORD(wp)==LBN_SELCHANGE) + EnableWindow(GetDlgItem(dialog,keySchemePrimary),position>0 && position=filesKeySchemeLimit) return TRUE; + std::wstring name=scheme.name.substr(0,43)+L" copy"; + FilesModalDialog copyName(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(616),dialog, + copyKeySchemeDialog,reinterpret_cast(&name),false); + if(copyName.runModal()!=IDOK) return TRUE; + if(!validFilesKeySchemeName(name) || std::ranges::any_of(settings.schemes,[&](const auto &other) + { return sameFilesKeySchemeName(other.name,name); })) + { + showFilesNotice(dialog,L"Enter a unique name with no leading or trailing spaces.",L"Keyboard shortcuts"); + return TRUE; + } + auto copy=scheme; + copy.name=std::move(name); + settings.schemes.push_back(std::move(copy)); + settings.active=settings.schemes.size()-1; + refreshFilesKeySchemes(dialog,settings); + refreshFilesKeyBindings(dialog,settings.schemes.back(),command); + return TRUE; + } + case keySchemeReset: + { + FilesNoticeOptions notice; + notice.confirm=true; + notice.accept=L"&Reset"; + const auto prompt=L"Reset all keys in “"+scheme.name+L"” to defaults?"; + if(showFilesNotice(dialog,prompt.c_str(),L"Keyboard shortcuts",notice)!=IDYES) return TRUE; + scheme=defaultFilesKeyScheme(scheme.name); + refreshFilesKeyBindings(dialog,scheme,command); + return TRUE; + } + case keySchemeAdd: + { + if(keys.size()>=filesKeysPerCommand) return TRUE; + const auto binding=static_cast(SendDlgItemMessageW(dialog,keySchemeCapture,HKM_GETHOTKEY,0,0)); + if(const auto conflict=filesKeyConflict(scheme,command,binding);!conflict.empty()) + { + showFilesNotice(dialog,conflict.c_str(),L"Keyboard shortcuts"); + SetFocus(GetDlgItem(dialog,keySchemeCapture)); + return TRUE; + } + keys.push_back(binding); + SendDlgItemMessageW(dialog,keySchemeCapture,HKM_SETHOTKEY,0,0); + refreshFilesKeyBindings(dialog,scheme,command,keys.size()-1); + return TRUE; + } + case keySchemeRemove: + if(position0 && position(&draft),false); + dialog.runModal(); +} diff --git a/src/files_main.cpp b/src/files_main.cpp index aa565a5..cf1baa3 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -805,10 +805,12 @@ size_t terminalHistoryIndex{}; std::wstring terminalHistoryDraft; constexpr UINT_PTR transferHighlightTimer=1; unsigned transferHighlightPhase{}; -constexpr struct KeyBarCommand { int id; WPARAM key; const wchar_t *label; } keyBar[]{ - {110,VK_F2,L"Ctrl+R Refresh"}, {111,VK_F3,L"F3 View"}, {112,VK_F4,L"F4 Edit"}, - {113,VK_F5,L"F5 Copy"}, {114,VK_F6,L"F6 Move"}, {115,VK_F7,L"F7 Mkdir"}, - {117,VK_F8,L"F8 Delete"}, {116,VK_F10,L"F10 Exit"} +DWORD preference(const wchar_t *name,DWORD fallback); +#include "files_key_schemes.inl" +constexpr struct KeyBarCommand { int id; FilesKey command; const wchar_t *label; } keyBar[]{ + {110,FilesKey::Refresh,L"Refresh"}, {111,FilesKey::View,L"View"}, {112,FilesKey::Edit,L"Edit"}, + {113,FilesKey::Copy,L"Copy"}, {114,FilesKey::Move,L"Move"}, {115,FilesKey::Mkdir,L"Mkdir"}, + {117,FilesKey::Delete,L"Delete"}, {116,FilesKey::Exit,L"Exit"} }; HWND status{}, commands[std::size(keyBar)]{}; int active{}, split{}; @@ -2724,10 +2726,9 @@ LRESULT CALLBACK terminalInputKeys(HWND input,UINT message,WPARAM wp,LPARAM lp,U SendMessageW(panels[active].list,WM_KEYDOWN,wp,lp); return 0; } - if(message==WM_KEYDOWN && (wp==VK_UP || wp==VK_DOWN)) + if(message==WM_KEYDOWN && wp==VK_UP) { - if(wp==VK_UP) recallPreviousCommand(); - if(wp==VK_DOWN && terminalHistoryIndexfailure,true); + setStatus((refreshKey.empty()?L"Refresh to retry":refreshKey+L" to retry")+ + L" · "+panel.remoteRetry->failure,true); return; } if(panel.findOrigin) @@ -2838,7 +2841,7 @@ void showFileDetails(const Panel &panel) const auto count=std::to_wstring(panel.rows.size()); if(error==ERROR_CONNECTION_ABORTED) setStatus(count+(panel.rows.size()==1?L" match":L" matches")+ - L" · Connection interrupted · Ctrl+R Retry · Esc Back"); + L" · Connection interrupted · "+(refreshKey.empty()?L"Refresh to retry":refreshKey+L" Retry")+L" · Esc Back"); else setStatus(count+(error==ERROR_CANCELLED?L" matches (stopped)": error?L" matches (some folders could not be read)":L" matches")+ L" · Enter: Go · Esc: Back"); @@ -2847,7 +2850,8 @@ void showFileDetails(const Panel &panel) if(transferProfileList(panel)) { setStatus(transferProfiles(panel.ftp->protocol).rows.empty()?L"Shift+F4 New connection": - L"Shift+F4 New F4 Edit Enter Connect"); + L"Shift+F4 New "+(filesKeyHint(FilesKey::Edit).empty()?L"":filesKeyHint(FilesKey::Edit)+L" Edit ")+ + L"Enter Connect"); return; } auto row=SendMessageW(panel.list,LB_GETCURSEL,0,0); @@ -3891,6 +3895,8 @@ void showProcesses(HWND owner,std::vector paths={}); bool gitChangesAvailable(const Panel &panel); void openGitChanges(HWND owner,const Panel &panel); void showEnvironmentPanel(HWND owner); +void editFilesKeySchemes(HWND owner,FilesKey initial); +void showCommandHistory(HWND owner); bool selectablePickerRow(LRESULT row) { @@ -3942,6 +3948,8 @@ void selectDrive() else if(menuIndex==2 && row==16) openGitChanges(owner,panels[active]); else if(menuIndex==2 && row==17) showEnvironmentPanel(owner); else if(menuIndex==2 && row==18) swapPanels(owner); + else if(menuIndex==2 && row==19) showCommandHistory(owner); + else if(menuIndex==2 && row==20) editFilesKeySchemes(owner,FilesKey::Refresh); else if(menuIndex==1 && row==4) createArchive(owner,panels[active]); else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]); else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]); @@ -4578,17 +4586,6 @@ void toggleQuickView(HWND owner) layout(owner); } -bool handleQuickViewKey(HWND window,const MSG &message) -{ - if(message.message!=WM_KEYDOWN || message.wParam!='Q' || terminalVisible || - !commandLineAvailable(window) || - !(GetKeyState(VK_CONTROL)&0x8000) || - ((GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) - return false; - if(!(message.lParam&(1LL<<30))) toggleQuickView(window); - return true; -} - ks::files::RemoteTextSource transferTextSource(const TransferProfile &profile); void openPanelImage(const Panel &panel,const fs::path &path,const ks::files::RemoteTextSource *source=nullptr) @@ -7919,6 +7916,72 @@ void editTransferProfile(Panel &panel,bool create); #include "files_properties.inl" #include "files_context_menu.inl" +void runFilesKeyCommand(HWND owner,int side,FilesKey command) +{ + auto &panel=panels[side]; + switch(command) + { + case FilesKey::Refresh: refreshPanel(panel); break; + case FilesKey::View: + case FilesKey::Edit: + { + const bool edit=command==FilesKey::Edit; + if(transferProfileList(panel)) + { + if(edit) editTransferProfile(panel,false); + break; + } + const auto row=currentPanelRow(panel); + if(edit || row==LB_ERR || !calculateFolderSizes(panel,row)) openSelectedText(panel,edit,false); + break; + } + case FilesKey::Copy: + case FilesKey::Move: copySelection(owner,panel,panels[1-side],command==FilesKey::Move); break; + case FilesKey::Mkdir: makeFolder(owner,panel); break; + case FilesKey::Delete: deleteSelection(owner,panel,false); break; + case FilesKey::Exit: SendMessageW(owner,WM_CLOSE,0,0); break; + case FilesKey::Compare: compareSelectedFiles(owner); break; + case FilesKey::Previous: recallPreviousCommand(); break; + case FilesKey::Next: + if(terminalHistoryIndex(index),*command); return 0; } - if (wp == VK_F10) { SendMessageW(GetParent(window), WM_CLOSE, 0, 0); return 0; } - if (wp == VK_F3 || wp == VK_F4) + if(wp==VK_DELETE && (GetKeyState(VK_SHIFT)&0x8000)) { - auto &panel=panels[index]; - if(transferProfileList(panel)) - { - if(wp==VK_F4) editTransferProfile(panel,false); - return 0; - } - const auto row=currentPanelRow(panel); - if(wp==VK_F3 && row!=LB_ERR && calculateFolderSizes(panel,row)) return 0; - openSelectedText(panel,wp==VK_F4,false); - return 0; - } - if (wp == VK_F5 || wp == VK_F6) - { - copySelection(GetParent(window),panels[index],panels[1-index],wp==VK_F6); - return 0; - } - if(wp==VK_F7) - { - makeFolder(GetParent(window),panels[index]); - return 0; - } - if(wp==VK_F8 || (wp==VK_DELETE && (GetKeyState(VK_SHIFT)&0x8000))) - { - deleteSelection(GetParent(window),panels[index],wp==VK_DELETE); + deleteSelection(GetParent(window),panels[index],true); return 0; } } @@ -8180,12 +8219,12 @@ bool loadFilesPreferences(HWND window) compactLayout=preference(compactLayoutKey,0)!=0; restoreDocuments=preference(restoreDocumentsKey,0)!=0; statusFields=preference(L"StatusFields",defaultStatusFields)&15; - loadCommandHistoryKeys(); - loadComparisonShortcut(); + loadFilesKeySettings(); return true; } #include "files_find.inl" +#include "files_key_schemes_dialog.inl" #include "files_options.inl" #include "files_panel_columns_dialog.inl" #include "files_space_analyzer.inl" @@ -8235,16 +8274,18 @@ 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",L"Pack files…\tAlt+F5", - L"Properties…\tCtrl+A",L"Locking processes…"}; + else if(index==1) rows={filesKeyMenuLabel(FilesKey::Copy),filesKeyMenuLabel(FilesKey::Move), + filesKeyMenuLabel(FilesKey::Mkdir),filesKeyMenuLabel(FilesKey::Exit),filesKeyMenuLabel(FilesKey::Pack,L"Pack files…"), + filesKeyMenuLabel(FilesKey::Properties,L"Properties…"),L"Locking processes…"}; else if(index==2) { - rows={L"Refresh panel\tCtrl+R",L"View\tF3",L"Edit\tF4",L"Folder shortcuts", - L"View externally\tAlt+F3",L"Edit externally\tAlt+F4", - L"Hibernate remote PC",L"Update remote KSwitcher",L"Compare files\t"+comparisonShortcutLabel(), - L"Find files\tAlt+F7",quickViewWindow?L"Close Quick View\tCtrl+Q":L"Quick View\tCtrl+Q", - L"Copy full path\tCtrl+Shift+C",L"Space Analyzer",L"View as hex\tShift+F3",L"Viewer bookmarks…",L"Processes…", - L"Git Changes…",L"Environment Variables…",L"Swap panels\tCtrl+U"}; + rows={filesKeyMenuLabel(FilesKey::Refresh),filesKeyMenuLabel(FilesKey::View),filesKeyMenuLabel(FilesKey::Edit), + L"Folder shortcuts",filesKeyMenuLabel(FilesKey::ExternalView),filesKeyMenuLabel(FilesKey::ExternalEdit), + L"Hibernate remote PC",L"Update remote KSwitcher",filesKeyMenuLabel(FilesKey::Compare), + filesKeyMenuLabel(FilesKey::Find),filesKeyMenuLabel(FilesKey::QuickView,quickViewWindow?L"Close Quick View":L"Quick View"), + filesKeyMenuLabel(FilesKey::FullPath),L"Space Analyzer",filesKeyMenuLabel(FilesKey::HexView), + L"Viewer bookmarks…",L"Processes…",L"Git Changes…",L"Environment Variables…",filesKeyMenuLabel(FilesKey::Swap), + filesKeyMenuLabel(FilesKey::History),L"Keyboard shortcuts…"}; } const auto &panel=panels[active]; const bool remoteResults=remoteSearchResults(panel); @@ -8255,7 +8296,7 @@ void openMenu(HWND window, int index) if(remoteSearchActionAvailable(113)) commandActions.push_back(0); if(remoteSearchActionAvailable(114)) { - if(panel.ftp) rows[1]=L"Rename\tF6"; + if(panel.ftp) rows[1]=filesKeyMenuLabel(FilesKey::Move,L"Rename"); commandActions.push_back(1); } commandActions.push_back(3); @@ -8291,6 +8332,7 @@ void openMenu(HWND window, int index) } if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10); if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7}); + commandActions.insert(commandActions.end(),{-1,19,20}); } else for(size_t i=0;i(i)); @@ -8510,6 +8552,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) if(reinterpret_cast(wp)!=window) { loadFilesPreferences(window); + refreshFilesKeyBar(); layout(window); layoutOpenCommandHistory(); showFileDetails(panels[active]); @@ -8647,7 +8690,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) if (!mono || !blue || !teal || !menuBar || !picker || !pickerFrame || !status || !panelSearchPopup) return -1; SendMessageW(status, WM_SETFONT, reinterpret_cast(mono), FALSE); for (int i = 0; i < static_cast(std::size(commands)); ++i) - commands[i] = CreateWindowW(L"BUTTON", keyBar[i].label, WS_CHILD | WS_VISIBLE | BS_OWNERDRAW, + commands[i] = CreateWindowW(L"BUTTON", filesKeyBarLabel(keyBar[i].command,keyBar[i].label).c_str(), + WS_CHILD | WS_VISIBLE | BS_OWNERDRAW, 0, 0, 0, 0, window, reinterpret_cast(static_cast(keyBar[i].id)), instance, nullptr); for(int i=0;i(driveButtons.size());++i) { @@ -8976,7 +9020,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) if(std::find(std::begin(commands),std::end(commands),item.hwndItem)!=std::end(commands)) { if(item.CtlID==114 && remoteSearchResults(panels[active]) && panels[active].ftp) - text=L"F6 Rename"; + text=filesKeyBarLabel(FilesKey::Move,L"Rename"); const auto separator=text.find(L' '); auto key=text.substr(0,separator); if(key.starts_with(L'F') && key.size()>1) key.erase(0,1); @@ -9284,7 +9328,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) { for(const auto &command:keyBar) if(LOWORD(wp)==command.id && remoteSearchActionAvailable(command.id)) - SendMessageW(panels[active].list,WM_KEYDOWN,command.key,0); + runFilesKeyCommand(window,active,command.command); } if (LOWORD(wp) >= 102 && LOWORD(wp) <= 103 && HIWORD(wp) == LBN_DBLCLK) enter(panels[LOWORD(wp) - 102]); @@ -9447,7 +9491,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) } continue; } - if(handleQuickViewKey(window,message) || handlePanelPathKey(window,message)) continue; + if(handlePanelPathKey(window,message) || handleFilesKeyChord(window,message)) continue; if((message.message==WM_KEYDOWN || message.message==WM_SYSKEYDOWN) && !terminalVisible && commandLineAvailable(window) && (message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list) && @@ -9505,34 +9549,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) continue; } } - if(!terminalVisible && !copyInProgress && !commandHistoryWindow && !FilesModalDialog::activeFor(window) && - 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)) - { - if(!(message.lParam & (1LL<<30))) - { - hidePicker(); - showMenu(false); - if(message.wParam==VK_F5) createArchive(window,panels[active]); - else findPanelFiles(window,panels[active]); - } - continue; - } - if(!copyInProgress && !commandHistoryWindow && !FilesModalDialog::activeFor(window) && !terminalVisible && - message.message==WM_SYSKEYDOWN && (message.wParam==VK_F3 || message.wParam==VK_F4) && - (message.lParam & (1LL<<29)) && - !(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) && - (message.hwnd==window || IsChild(window,message.hwnd))) - { - if(!(message.lParam & (1LL<<30))) - { - hidePicker(); - showMenu(false); - openSelectedText(panels[active],message.wParam==VK_F4,true); - } - continue; - } if(message.message==WM_KEYDOWN && (message.wParam==VK_UP || message.wParam==VK_DOWN) && (GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) && (message.hwnd==window || IsChild(window,message.hwnd)) && !terminalVisible && !copyInProgress) @@ -9586,21 +9602,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) continue; } const bool filesMessage=message.hwnd==window || IsChild(window,message.hwnd); - if(filesMessage && !terminalVisible && !copyInProgress && !commandHistoryWindow && - !FilesModalDialog::activeFor(window) && message.message==WM_KEYDOWN && - !(GetKeyState(VK_MENU)&0x8000) && !(GetKeyState(VK_LWIN)&0x8000) && - !(GetKeyState(VK_RWIN)&0x8000) && (GetKeyState(VK_SHIFT)&0x8000) && - MAKEWORD(message.wParam,HOTKEYF_SHIFT|((GetKeyState(VK_CONTROL)&0x8000)?HOTKEYF_CONTROL:0))== - comparisonShortcut) - { - if(!(message.lParam & (1LL<<30))) - { - hidePicker(); - showMenu(false); - compareSelectedFiles(window); - } - continue; - } if(mainInput && !terminalVisible && !copyInProgress && (message.message==WM_KEYDOWN || (message.message==WM_SYSKEYDOWN && message.wParam==VK_F10)) && message.wParam>=VK_F1 && message.wParam<=VK_F12 && @@ -9635,17 +9636,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) } continue; } - if(ctrl && shift && message.wParam=='C' && !terminalVisible && commandLineAvailable(window)) - { - if(!(message.lParam & (1LL<<30))) copyFullPanelPath(window,panels[active]); - continue; - } - if(ctrl && !shift && message.wParam=='A' && !terminalVisible && commandLineAvailable(window) && - (!GetWindowTextLengthW(terminalInput) || panelFocused) && panelItemPropertiesAvailable(panels[active])) - { - if(!(message.lParam&(1LL<<30))) showPanelItemProperties(window,panels[active]); - continue; - } if(shift && !ctrl && message.wParam==VK_F4 && !terminalVisible) { if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window)) @@ -9656,21 +9646,13 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) } continue; } - if(shift && !ctrl && message.wParam==VK_F3 && !terminalVisible && commandLineAvailable(window)) - { - if(!(message.lParam&(1LL<<30))) openSelectedText(panels[active],false,false,true); - continue; - } if(ctrl && !shift && - (message.wParam=='F' || message.wParam=='C' || message.wParam=='R' || - (message.wParam=='U' && !terminalVisible) || + (message.wParam=='F' || message.wParam=='C' || message.wParam==VK_RETURN || message.wParam==VK_INSERT)) { if(!(message.lParam & (1LL<<30))) { if(message.wParam=='F') insertCurrentPanelPath(); - else if(message.wParam=='R') refreshPanel(panels[active]); - else if(message.wParam=='U') swapPanels(window); else if(message.wParam==VK_RETURN) insertCurrentPanelPath(true); else if(message.wParam==VK_INSERT) copyCommandLineOrPanelNames(window); else copyOrInterruptTerminal(); @@ -9685,7 +9667,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) continue; } } - if(filesMessage && !copyInProgress && handleCommandHistoryKey(window,message)) continue; const bool modified=(GetKeyState(VK_CONTROL)&0x8000) || (GetKeyState(VK_SHIFT)&0x8000) || (GetKeyState(VK_LWIN)&0x8000) || (GetKeyState(VK_RWIN)&0x8000); if(filesMessage && !copyInProgress && @@ -9751,13 +9732,6 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) continue; } } - if (message.message == WM_SYSKEYDOWN && message.wParam == VK_F10 && - !(GetKeyState(VK_CONTROL) & 0x8000) && !(GetKeyState(VK_MENU) & 0x8000) && - !(GetKeyState(VK_SHIFT) & 0x8000)) - { - SendMessageW(window, WM_CLOSE, 0, 0); - continue; - } if (message.message == WM_SYSKEYDOWN && (message.wParam == VK_F1 || message.wParam == VK_F2)) { chooseDrive(static_cast(message.wParam - VK_F1)); diff --git a/src/files_options.inl b/src/files_options.inl index 7b73352..11eb4ab 100644 --- a/src/files_options.inl +++ b/src/files_options.inl @@ -4,9 +4,9 @@ enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line", L"Viewer",L"Editor",L"All settings",L"File comparison"}; constexpr int comparisonFontLabel=408,comparisonChooseFont=409,comparisonColorCombo=411, - comparisonChooseColor=412,comparisonColorValue=413,comparisonShortcutControl=415; + comparisonChooseColor=412,comparisonColorValue=413,comparisonKeySchemesButton=415; constexpr int comparisonControls[]{comparisonFontLabel,comparisonChooseFont,410,comparisonColorCombo, - comparisonChooseColor,comparisonColorValue,414,comparisonShortcutControl}; + comparisonChooseColor,comparisonColorValue,comparisonKeySchemesButton}; constexpr const wchar_t *colorNames[]{L"Panel background",L"Text",L"Frame",L"Popup background", L"Menu selection",L"Command bar",L"File cursor"}; enum PanelSection { PanelLayout, WideColumns, StatusColumns }; @@ -106,7 +106,6 @@ struct OptionsBaseline DialogFramePadding padding=dialogFramePadding; std::array palette=colors; std::vector styles=fileStyles; - std::array keys=commandHistoryKeys; bool remoteTerminal=ks::lan::remoteTerminalAllowed(); bool remoteHibernate=ks::lan::remoteHibernateAllowed(); bool remoteUpdate=ks::lan::remoteUpdateAllowed(); @@ -117,7 +116,6 @@ struct OptionsBaseline std::array modes{panels[0].mode,panels[1].mode}; ks::files::TextSettings text=ks::files::loadTextPreferences(); ComparisonAppearance comparison=readComparisonAppearance(); - WORD compareShortcut=comparisonShortcut; }; struct OptionsDraft @@ -192,11 +190,10 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft) checked(compactLayoutControl)!=base.compact || checked(restoreDocumentsControl)!=base.restoreLocal || fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles || draft.framePadding!=base.padding || optionsFontChanged(draft) || - optionHistoryKeys(dialog)!=base.keys || checked(optionsRemoteTerminal)!=base.remoteTerminal || + checked(optionsRemoteTerminal)!=base.remoteTerminal || checked(optionsRemoteHibernate)!=base.remoteHibernate || checked(optionsRemoteUpdate)!=base.remoteUpdate || - draft.text!=base.text || draft.comparison!=base.comparison || - SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0)!=base.compareShortcut; + draft.text!=base.text || draft.comparison!=base.comparison; EnableWindow(GetDlgItem(dialog,optionsApply),dirty); InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE); } @@ -506,7 +503,7 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) for(const auto &option:frameOptions) SendDlgItemMessageW(dialog,option.id,CB_SETCURSEL,draft.framePadding.*option.value,0); } - constexpr int commandLineControls[]{320,321,322,323,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate}; + constexpr int commandLineControls[]{321,optionsRemoteTerminal,optionsRemoteHibernate,optionsRemoteUpdate}; show(commandLineControls,page==CommandLine && section==0); show(markdownControls,markdown); show(textControls,textOptionsPage(page) && !markdown); @@ -611,10 +608,10 @@ void filterOptions(HWND dialog,OptionsDraft &draft) matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground")); } else if(page==CommandLine) addSection(L"Command history",0, - matches(L"Previous command") || matches(L"Allow paired PCs to run PowerShell commands here") || + matches(L"Previous command") || matches(L"Keyboard shortcuts") || matches(L"Allow paired PCs to run PowerShell commands here") || matches(L"Allow paired PCs to hibernate this PC") || matches(L"Allow paired PCs to update KSwitcher here")); else if(page==CompareFiles) - addSection(L"Font and colors",0,matches(L"Compare files shortcut") || std::any_of(std::begin(comparisonColorNames), + addSection(L"Font and colors",0,matches(L"Compare files shortcut") || matches(L"Keyboard shortcuts") || std::any_of(std::begin(comparisonColorNames), std::end(comparisonColorNames),matches)); else if(textOptionsPage(page)) { @@ -672,8 +669,6 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) for(const auto label:comparisonColorNames) SendDlgItemMessageW(dialog,comparisonColorCombo,CB_ADDSTRING,0,reinterpret_cast(label)); SendDlgItemMessageW(dialog,comparisonColorCombo,CB_SETCURSEL,0,0); - SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETRULES,HKCOMB_NONE,HOTKEYF_SHIFT); - SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,comparisonShortcut,0); SendDlgItemMessageW(dialog,optionsSearch,EM_SETLIMITTEXT,255,0); for(const auto &option:frameOptions) for(DWORD value=0;value<=option.maximum;++value) @@ -696,7 +691,6 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments); 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()); CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed()); CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed()); @@ -862,13 +856,9 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) return TRUE; case optionsReset: if(draft->page==allOptions || draft->page==CompareFiles) - { draft->comparison=ComparisonAppearance{}; - SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_SETHOTKEY,defaultComparisonShortcut,0); - } if(draft->page==allOptions || draft->page==CommandLine) { - setOptionHistoryKeys(dialog,defaultHistoryKeys); CheckDlgButton(dialog,optionsRemoteTerminal,BST_UNCHECKED); CheckDlgButton(dialog,optionsRemoteHibernate,BST_UNCHECKED); CheckDlgButton(dialog,optionsRemoteUpdate,BST_UNCHECKED); @@ -920,22 +910,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) case optionsRemoteTerminal: case optionsRemoteHibernate: case optionsRemoteUpdate: updateOptionsApply(dialog,*draft); return TRUE; - case 321: case 323: case comparisonShortcutControl: - updateOptionsApply(dialog,*draft); + case 321: case comparisonKeySchemesButton: + editFilesKeySchemes(dialog,LOWORD(wp)==321?FilesKey::Previous:FilesKey::Compare); return TRUE; case optionsApply: case IDOK: { - const auto compareShortcut=static_cast( - SendDlgItemMessageW(dialog,comparisonShortcutControl,HKM_GETHOTKEY,0,0)); - if(!validComparisonShortcut(compareShortcut)) - { - showFilesNotice(dialog,L"Choose Shift or Ctrl+Shift with a function key. Shift+F4 and Shift+F8 are reserved.", - optionsTitles[CompareFiles]); - if(IsWindowVisible(GetDlgItem(dialog,comparisonShortcutControl))) - SetFocus(GetDlgItem(dialog,comparisonShortcutControl)); - return TRUE; - } if(draft->markdownError) { if(!draft->markdownNode) SetDlgItemTextW(dialog,optionsSearch,L""); @@ -1004,15 +984,6 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } textSettings.schemes=draft->text.schemes; } - auto keys=optionHistoryKeys(dialog); - loadCommandHistoryKeys(); - for(size_t i=0;istyles!=base.styles; loadFileStyles(); if(stylesChanged && fileStyles!=base.styles && fileStyles!=draft->styles) @@ -1058,10 +1029,6 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) if(value!=initial) savePreference(name,value); }; const auto checked=[&](int id){return IsDlgButtonChecked(dialog,id)==BST_CHECKED;}; - const auto inputKeys=optionHistoryKeys(dialog); - saveChanged(L"PreviousCommandKey",inputKeys[0],base.keys[0]); - saveChanged(L"CommandHistoryKey",inputKeys[1],base.keys[1]); - saveChanged(comparisonShortcutKey,compareShortcut,base.compareShortcut); saveChanged(ks::lan::remoteTerminalPreference,checked(optionsRemoteTerminal),base.remoteTerminal); saveChanged(ks::lan::remoteHibernatePreference,checked(optionsRemoteHibernate),base.remoteHibernate); saveChanged(ks::lan::remoteUpdatePreference,checked(optionsRemoteUpdate),base.remoteUpdate); @@ -1097,6 +1064,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) if(mode!=base.modes[index]) savePanelMode(index,mode); } loadFilesPreferences(owner); + refreshFilesKeyBar(); notifyFilesPreferences(owner); const auto dialogOwner=GetWindow(dialog,GW_OWNER); if(dialogOwner!=owner) @@ -1121,8 +1089,6 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) CheckDlgButton(dialog,restoreDocumentsControl,restoreDocuments); 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); CheckDlgButton(dialog,optionsRemoteTerminal,ks::lan::remoteTerminalAllowed()); CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed()); CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed()); From b6b7164742b508400b840e815506cdf6fc9ae01d Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 23:06:45 +0200 Subject: [PATCH 45/61] Add selective Files settings JSON import and export Refs #129 --- FILES-UI.md | 1 + resources/files.rc | 15 ++ src/files_key_schemes_dialog.inl | 18 +- src/files_main.cpp | 15 +- src/files_options.inl | 58 ++++--- src/files_options_transfer.inl | 275 +++++++++++++++++++++++++++++++ src/files_styles.inl | 65 ++++---- 7 files changed, 388 insertions(+), 59 deletions(-) create mode 100644 src/files_options_transfer.inl diff --git a/FILES-UI.md b/FILES-UI.md index 3f858dd..9fb4a2d 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -741,6 +741,7 @@ Warning і початковий фокус на No. - При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання. - Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку. +- Options → Import JSON / Export JSON переносить вибрані групи збережених параметрів Files. Окремо доступні кольори панелей і порівняння разом зі стилями файлів, режими й компонування панелей та іменовані схеми клавіш. Перед заміною відмінних схем з однаковою назвою Files запитує підтвердження. Імпорт спочатку оновлює чернетку Options. Apply або OK зберігає зміни, Cancel відкидає їх. Формат містить лише ці параметри. Невідомі поля і групи пропускаються. - Commands → Keyboard shortcuts відкриває іменовані схеми для команд файлових панелей та історії команд. У схемі можна задати кілька клавіш, вибрати основну, вилучити прив’язку, скопіювати схему під новим іменем, перемкнути чи скинути її. OK зберігає активну схему. Меню показує всі прив’язки, нижній ряд і текстові підказки відображають основну. Діалог відхиляє дублікати в контекстах, що перетинаються, і клавіші, зайняті навігацією. Попередні прив’язки історії та порівняння завантажуються як схема Previous settings. - Appearance → Dialog frame налаштовує зовнішній і внутрішній відступи від 0 до 24 px при 96 DPI. Row text padding додає від 0 до 4 ширин символу з кожного боку тексту в рядках Folder shortcuts. Inner padding задає відстань від рамки до краю списку. Ширина попапа враховує обидва текстові відступи, а довгі шляхи скорочуються в межах доступної ширини. Живий зразок показує чернетку. Apply зберігає значення, Cancel відкидає незастосовані зміни, Reset selected to defaults повертає 8 px, 14 px і 0 символів. Профілі без цих параметрів використовують ті самі значення. - У ресурсі чи виклику задавай назву кнопки й клавішу доступу. Спільна функція `paintDialogButton` центрує текст, підсвічує фокус і додає фігурні дужки для дії за замовчуванням та квадратні для решти кнопок. diff --git a/resources/files.rc b/resources/files.rc index c8332da..c47b8cf 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -188,6 +188,19 @@ BEGIN PUSHBUTTON "Cancel", IDCANCEL, 172, 49, 52, 15 END +617 DIALOGEX 0, 0, 240, 124 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Files settings" +FONT 9, "Segoe UI" +BEGIN + LTEXT "", 624, 9, 9, 222, 24 + AUTOCHECKBOX "Colors and file styles", 621, 9, 39, 222, 13 + AUTOCHECKBOX "Panel modes and layout", 622, 9, 55, 222, 13 + AUTOCHECKBOX "Keyboard schemes", 623, 9, 71, 222, 13 + DEFPUSHBUTTON "Load", IDOK, 118, 99, 52, 15 + PUSHBUTTON "Cancel", IDCANCEL, 179, 99, 52, 15 +END + 101 DIALOGEX 0, 0, 397, 310 STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN CAPTION "KSwitcher Files Options" @@ -280,6 +293,8 @@ BEGIN PUSHBUTTON "Change color…", 412, 250, 97, 82, 15 LTEXT "", 413, 338, 100, 45, 12 PUSHBUTTON "&Keyboard shortcuts…", 415, 131, 127, 127, 15 + PUSHBUTTON "&Import JSON…", 525, 8, 289, 70, 14 + PUSHBUTTON "&Export JSON…", 526, 84, 289, 70, 14 DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14 PUSHBUTTON "Cancel", IDCANCEL, 280, 289, 50, 14 PUSHBUTTON "&Apply", 283, 338, 289, 50, 14 diff --git a/src/files_key_schemes_dialog.inl b/src/files_key_schemes_dialog.inl index 191c7fc..40d46c9 100644 --- a/src/files_key_schemes_dialog.inl +++ b/src/files_key_schemes_dialog.inl @@ -6,6 +6,7 @@ struct FilesKeySchemeDraft { FilesKeySettings base=filesKeySettings,settings=base; FilesKey initial; + FilesKeySettings *pending{}; }; INT_PTR CALLBACK copyKeySchemeDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) @@ -184,8 +185,15 @@ INT_PTR CALLBACK filesKeySchemesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM } return TRUE; case IDOK: - if(settings!=draft.base) + if(draft.pending) *draft.pending=settings; + else if(settings!=draft.base) { + const OptionsWriteLock writeLock; + if(!writeLock.acquired()) + { + showFilesNotice(dialog,L"Another window is saving Files settings. Try again.",L"Keyboard shortcuts"); + return TRUE; + } loadFilesKeySettings(); if(filesKeySettings!=draft.base && filesKeySettings!=settings) { @@ -209,11 +217,11 @@ INT_PTR CALLBACK filesKeySchemesDialog(HWND dialog,UINT message,WPARAM wp,LPARAM return FALSE; } -void editFilesKeySchemes(HWND owner,FilesKey initial) +void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending) { - loadFilesKeySettings(); - FilesKeySchemeDraft draft; - draft.initial=initial; + if(!pending) loadFilesKeySettings(); + const auto &base=pending?*pending:filesKeySettings; + FilesKeySchemeDraft draft{base,base,initial,pending}; FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(615),owner, filesKeySchemesDialog,reinterpret_cast(&draft),false); dialog.runModal(); diff --git a/src/files_main.cpp b/src/files_main.cpp index cf1baa3..fe14710 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -3895,7 +3895,7 @@ void showProcesses(HWND owner,std::vector paths={}); bool gitChangesAvailable(const Panel &panel); void openGitChanges(HWND owner,const Panel &panel); void showEnvironmentPanel(HWND owner); -void editFilesKeySchemes(HWND owner,FilesKey initial); +void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending=nullptr); void showCommandHistory(HWND owner); bool selectablePickerRow(LRESULT row) @@ -8224,6 +8224,19 @@ bool loadFilesPreferences(HWND window) } #include "files_find.inl" +struct OptionsWriteLock +{ + HANDLE mutex=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.OptionsWrite"); + DWORD result=mutex?WaitForSingleObject(mutex,2000):WAIT_FAILED; + + bool acquired() const { return result==WAIT_OBJECT_0 || result==WAIT_ABANDONED; } + ~OptionsWriteLock() + { + if(acquired()) ReleaseMutex(mutex); + if(mutex) CloseHandle(mutex); + } +}; + #include "files_key_schemes_dialog.inl" #include "files_options.inl" #include "files_panel_columns_dialog.inl" diff --git a/src/files_options.inl b/src/files_options.inl index 11eb4ab..c1865d0 100644 --- a/src/files_options.inl +++ b/src/files_options.inl @@ -1,4 +1,5 @@ constexpr int optionsSearch=270,optionsTree=271,optionsTitle=272,optionsApply=283,optionsReset=284,optionsProperty=285,optionsResetProperty=286, + optionsImport=525,optionsExport=526, optionsRemoteTerminal=370,optionsRemoteHibernate=371,optionsRemoteUpdate=372; enum OptionsPage { PanelModes, PanelColors, Appearance, CommandLine, TextViewer, TextEditor, allOptions, CompareFiles }; constexpr const wchar_t *optionsTitles[]{L"File panel modes",L"Colors",L"Appearance",L"Command line", @@ -53,7 +54,7 @@ constexpr struct {innerFramePadding,&DialogFramePadding::inner,maxDialogFramePadding}, {rowTextPadding,&DialogFramePadding::rowText,maxDialogRowTextPadding}}; -enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight }; +enum class OptionsAnchor { StretchWidth, StretchHeight, BottomRight, BottomLeft }; struct OptionsControl { int id; @@ -116,6 +117,7 @@ struct OptionsBaseline std::array modes{panels[0].mode,panels[1].mode}; ks::files::TextSettings text=ks::files::loadTextPreferences(); ComparisonAppearance comparison=readComparisonAppearance(); + FilesKeySettings keySettings=filesKeySettings; }; struct OptionsDraft @@ -123,6 +125,7 @@ struct OptionsDraft OptionsBaseline baseline; ks::files::TextSettings text=baseline.text; ComparisonAppearance comparison=baseline.comparison; + FilesKeySettings keySettings=baseline.keySettings; HWND filesWindow{}; LOGFONTW font=displayFont; int points=fontPoints; @@ -138,13 +141,14 @@ struct OptionsDraft HTREEITEM wideColumnsNode{},markdownNode{}; RECT initialClient{}; UINT initialDpi=96; - OptionsControl controls[8]{ + OptionsControl controls[10]{ {optionsTree,OptionsAnchor::StretchHeight}, {optionsTitle,OptionsAnchor::StretchWidth}, {275,OptionsAnchor::StretchWidth},{277,OptionsAnchor::StretchWidth}, {281,OptionsAnchor::StretchWidth}, {IDOK,OptionsAnchor::BottomRight},{IDCANCEL,OptionsAnchor::BottomRight}, - {optionsApply,OptionsAnchor::BottomRight}}; + {optionsApply,OptionsAnchor::BottomRight}, + {optionsImport,OptionsAnchor::BottomLeft},{optionsExport,OptionsAnchor::BottomLeft}}; }; @@ -162,19 +166,6 @@ bool optionsFontChanged(const OptionsDraft &draft) _wcsicmp(pending.lfFaceName,applied.lfFaceName)!=0; } -struct OptionsWriteLock -{ - HANDLE mutex=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.OptionsWrite"); - DWORD result=mutex?WaitForSingleObject(mutex,2000):WAIT_FAILED; - - bool acquired() const { return result==WAIT_OBJECT_0 || result==WAIT_ABANDONED; } - ~OptionsWriteLock() - { - if(acquired()) ReleaseMutex(mutex); - if(mutex) CloseHandle(mutex); - } -}; - void updateOptionsApply(HWND dialog,const OptionsDraft &draft) { BOOL valid{}; @@ -193,7 +184,7 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft) checked(optionsRemoteTerminal)!=base.remoteTerminal || checked(optionsRemoteHibernate)!=base.remoteHibernate || checked(optionsRemoteUpdate)!=base.remoteUpdate || - draft.text!=base.text || draft.comparison!=base.comparison; + draft.text!=base.text || draft.comparison!=base.comparison || draft.keySettings!=base.keySettings; EnableWindow(GetDlgItem(dialog,optionsApply),dirty); InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE); } @@ -251,6 +242,7 @@ void layoutOptions(HWND dialog,const OptionsDraft &draft) case OptionsAnchor::StretchWidth: width+=dx;break; case OptionsAnchor::StretchHeight: height+=dy;break; case OptionsAnchor::BottomRight: x+=dx;y+=dy;break; + case OptionsAnchor::BottomLeft: y+=dy;break; } SetWindowPos(GetDlgItem(dialog,control.id),nullptr,x,y,width,height, SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW); @@ -639,6 +631,8 @@ void filterOptions(HWND dialog,OptionsDraft &draft) if(!first) SetDlgItemTextW(dialog,optionsTitle,L"No matching settings"); } +#include "files_options_transfer.inl" + INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) { if(message==WM_INITDIALOG) @@ -911,7 +905,11 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) updateOptionsApply(dialog,*draft); return TRUE; case 321: case comparisonKeySchemesButton: - editFilesKeySchemes(dialog,LOWORD(wp)==321?FilesKey::Previous:FilesKey::Compare); + editFilesKeySchemes(dialog,LOWORD(wp)==321?FilesKey::Previous:FilesKey::Compare,&draft->keySettings); + updateOptionsApply(dialog,*draft); + return TRUE; + case optionsImport: case optionsExport: + transferFilesOptions(dialog,*draft,LOWORD(wp)==optionsImport); return TRUE; case optionsApply: case IDOK: @@ -943,6 +941,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) return TRUE; } const auto &base=draft->baseline; + const bool keysChanged=draft->keySettings!=base.keySettings; + loadFilesKeySettings(); + if(keysChanged && filesKeySettings!=base.keySettings && filesKeySettings!=draft->keySettings) + { + showFilesNotice(dialog,L"Keyboard schemes changed in another window. Reopen Options before editing them again.", + L"Keyboard shortcuts"); + return TRUE; + } const auto storedComparison=readComparisonAppearance(); const bool comparisonChanged=draft->comparison!=base.comparison; if(comparisonChanged && storedComparison!=base.comparison && storedComparison!=draft->comparison) @@ -952,7 +958,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) return TRUE; } const bool textChanged=draft->text!=base.text; - auto textSettings=ks::files::loadTextPreferences(); + const auto storedText=ks::files::loadTextPreferences(); + auto textSettings=storedText; if(draft->text.markdown!=base.text.markdown) { if(textSettings.markdown!=base.text.markdown && textSettings.markdown!=draft->text.markdown) @@ -1024,6 +1031,17 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) return TRUE; } } + if(keysChanged && !writeFilesJsonPreference(filesKeySchemePreference,serializeFilesKeySettings(draft->keySettings))) + { + if(textChanged) + try {ks::files::saveTextPreferences(storedText);} + catch(const std::exception &) {setStatus(L"Could not restore earlier text settings.",true);} + if(comparisonChanged) saveComparisonAppearance(storedComparison); + if(fontChanged) applyFont(owner,base.font,base.points); + if(stylesChanged) saveFileStyles(fileStyles); + showFilesNotice(dialog,L"Could not save the keyboard schemes.",L"Keyboard shortcuts"); + return TRUE; + } const auto saveChanged=[](const wchar_t *name,DWORD value,DWORD initial) { if(value!=initial) savePreference(name,value); @@ -1072,6 +1090,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) draft->baseline=OptionsBaseline{}; draft->text=draft->baseline.text; draft->comparison=draft->baseline.comparison; + draft->keySettings=draft->baseline.keySettings; showMarkdownOptions(dialog,draft->text.markdown); populateTextSchemes(dialog,draft->text); draft->font=displayFont; @@ -1108,6 +1127,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) void runOptions(HWND owner,int page) { + loadFilesKeySettings(); OptionsDraft draft; draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER); const DWORD initial=static_cast((page<<8)|1); diff --git a/src/files_options_transfer.inl b/src/files_options_transfer.inl new file mode 100644 index 0000000..57f6e2c --- /dev/null +++ b/src/files_options_transfer.inl @@ -0,0 +1,275 @@ +constexpr struct +{ + const char *id; + const wchar_t *label; + int control; +} filesTransferGroups[]{ + {"colors",L"&Colors and file styles",621}, + {"panels",L"&Panel modes and layout",622}, + {"keys",L"&Keyboard schemes",623}, +}; + +constexpr struct +{ + const char *id; + int control; + bool OptionsBaseline::*value; +} transferablePanelChecks[]{ + {"alignFileExtensions",202,&OptionsBaseline::extensions}, + {"alignFolderExtensions",204,&OptionsBaseline::folders}, + {"showDetails",203,&OptionsBaseline::details}, + {"rightClickMarks",rightClickMarksControl,&OptionsBaseline::mouseMarks}, + {"driveButtons",driveButtonsControl,&OptionsBaseline::drives}, + {"compactLayout",compactLayoutControl,&OptionsBaseline::compact}, +}; + +struct FilesTransferDraft +{ + bool importing{}; + Json groups=Json::object(); + std::array chosen{}; +}; + +INT_PTR CALLBACK filesTransferDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + auto &draft=*reinterpret_cast(lp); + SetWindowLongPtrW(dialog,DWLP_USER,lp); + SetWindowTextW(dialog,draft.importing?L"Import Files settings":L"Export Files settings"); + SetDlgItemTextW(dialog,624,draft.importing? + L"Choose groups to load into Options. Apply saves the changes.": + L"Choose groups to export from your saved Files settings."); + SetDlgItemTextW(dialog,IDOK,draft.importing?L"&Load":L"&Export"); + for(const auto &group:filesTransferGroups) + { + const bool available=draft.groups.contains(group.id); + const auto control=GetDlgItem(dialog,group.control); + SetWindowTextW(control,group.label); + ShowWindow(control,available?SW_SHOW:SW_HIDE); + CheckDlgButton(dialog,group.control,available?BST_CHECKED:BST_UNCHECKED); + } + return TRUE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && LOWORD(wp)==IDCANCEL)) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND) return FALSE; + auto &draft=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + for(size_t i=0;i file{}; + if(!importing) wcscpy_s(file.data(),file.size(),L"KSwitcher.Files.settings.json"); + OPENFILENAMEW pick{sizeof(pick)}; + pick.hwndOwner=owner; + pick.lpstrTitle=importing?L"Open Files settings JSON":L"Save Files settings JSON"; + pick.lpstrFilter=L"JSON files (*.json)\0*.json\0All files (*.*)\0*.*\0"; + pick.lpstrFile=file.data(); + pick.nMaxFile=static_cast(file.size()); + pick.lpstrDefExt=L"json"; + pick.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST| + (importing?OFN_FILEMUSTEXIST:OFN_OVERWRITEPROMPT); + if(importing?GetOpenFileNameW(&pick):GetSaveFileNameW(&pick)) return file.data(); + if(CommDlgExtendedError()) throw std::runtime_error("Could not open the file picker."); + return {}; +} + +Json exportFilesOptionGroups(const OptionsBaseline &saved) +{ + Json colors{{"panels",saved.palette},{"comparison",saved.comparison.palette},{"fileStyles",serializeFileStyles(saved.styles)}}; + Json panels{{"leftMode",static_cast(saved.modes[0])}, + {"rightMode",static_cast(saved.modes[1])},{"sizeWidth",saved.width},{"statusFields",saved.fields}}; + for(const auto &check:transferablePanelChecks) panels[check.id]=saved.*check.value; + return {{"colors",std::move(colors)},{"panels",std::move(panels)},{"keys",serializeFilesKeySettings(saved.keySettings)}}; +} + +template +void importFilesColors(const Json &value,Palette &palette) +{ + if(!value.is_array()) throw std::runtime_error("Expected an array of colors."); + for(size_t i=0;i0xffffff) + throw std::runtime_error("A color is outside the RGB range."); + palette[i]=value[i].template get(); + } +} + +DWORD importFilesOptionNumber(const Json &value,DWORD minimum,DWORD maximum) +{ + if(!value.is_number_unsigned() || valuemaximum) + throw std::runtime_error("A panel setting is outside its supported range."); + return value.get(); +} + +std::optional mergeImportedFilesKeySchemes(HWND owner,const FilesKeySettings &local,const Json &value) +{ + const auto imported=parseFilesKeySettings(value); + if(!imported) throw std::runtime_error("The keyboard schemes contain invalid or conflicting bindings."); + auto result=local; + size_t replacements{}; + for(size_t i=0;ischemes.size();++i) + { + const auto &scheme=imported->schemes[i]; + const auto existing=std::ranges::find_if(result.schemes,[&](const auto &candidate) + { return sameFilesKeySchemeName(candidate.name,scheme.name); }); + const auto position=static_cast(existing-result.schemes.begin()); + if(i==imported->active) result.active=position; + if(existing==result.schemes.end()) result.schemes.push_back(scheme); + else if(existing->keys!=scheme.keys) + { + ++replacements; + auto name=existing->name; + *existing=scheme; + existing->name=std::move(name); + } + } + if(result.schemes.size()>filesKeySchemeLimit) + throw std::runtime_error("The imported keyboard schemes exceed the number Files can store."); + if(replacements) + { + const auto prompt=L"Replace "+std::to_wstring(replacements)+ + (replacements==1?L" keyboard scheme with the same name?":L" keyboard schemes with the same names?"); + if(showFilesNotice(owner,prompt.c_str(),L"Import Files settings", + {.confirm=true,.accept=L"&Replace"})!=IDYES) return {}; + } + return result; +} + +void stageImportedFilesOptions(HWND dialog,OptionsDraft &draft,const Json &groups) +{ + auto palette=draft.palette; + auto comparison=draft.comparison.palette; + auto styles=draft.styles; + auto options=OptionsBaseline{}; + options.modes={panelModeOption(dialog,0),panelModeOption(dialog,1)}; + options.width=GetDlgItemInt(dialog,201,nullptr,FALSE); + options.fields=0; + for(int i=0;i<4;++i) + if(IsDlgButtonChecked(dialog,205+i)==BST_CHECKED) options.fields|=1u<is_object()) throw std::runtime_error("Invalid colors group."); + if(colorGroup->contains("panels")) importFilesColors(colorGroup->at("panels"),palette); + if(colorGroup->contains("comparison")) importFilesColors(colorGroup->at("comparison"),comparison); + if(colorGroup->contains("fileStyles")) + { + auto parsed=parseFileStyles(colorGroup->at("fileStyles")); + if(!parsed) throw std::runtime_error("Invalid file styles."); + styles=std::move(*parsed); + } + } + const auto panelGroup=groups.find("panels"); + if(panelGroup!=groups.end()) + { + if(!panelGroup->is_object()) throw std::runtime_error("Invalid panel modes and layout group."); + for(const auto &check:transferablePanelChecks) + if(panelGroup->contains(check.id)) options.*check.value=panelGroup->at(check.id).get(); + constexpr const char *modeKeys[]{"leftMode","rightMode"}; + for(size_t i=0;icontains(modeKeys[i])) + options.modes[i]=static_cast(importFilesOptionNumber( + panelGroup->at(modeKeys[i]),0,std::size(panelModeNames)-1)); + if(panelGroup->contains("sizeWidth")) + options.width=importFilesOptionNumber(panelGroup->at("sizeWidth"),6,16); + if(panelGroup->contains("statusFields")) + options.fields=importFilesOptionNumber(panelGroup->at("statusFields"),0,15); + } + if(groups.contains("keys")) + { + auto keys=mergeImportedFilesKeySchemes(dialog,draft.keySettings,groups.at("keys")); + if(!keys) return; + draft.keySettings=std::move(*keys); + } + if(colorGroup!=groups.end()) + { + draft.palette=palette; + draft.comparison.palette=comparison; + draft.styles=std::move(styles); + } + if(panelGroup!=groups.end()) + { + if(panelGroup->contains("sizeWidth")) SetDlgItemInt(dialog,201,options.width,FALSE); + for(int index=0;index<2;++index) + SendDlgItemMessageW(dialog,273+index,CB_SETCURSEL,static_cast(options.modes[index]),0); + for(const auto &check:transferablePanelChecks) + CheckDlgButton(dialog,check.control,options.*check.value?BST_CHECKED:BST_UNCHECKED); + for(int i=0;i<4;++i) CheckDlgButton(dialog,205+i,options.fields&(1u<32) throw std::runtime_error("The JSON contains too many nested levels."); + return true; + }); + if(document.value("format",std::string{})!="kswitcher-files-settings" || document.at("version")!=1) + throw std::runtime_error("This Files settings format or version is unsupported."); + const auto &groups=document.at("groups"); + if(!groups.is_object()) throw std::runtime_error("The document does not contain settings groups."); + for(const auto &group:filesTransferGroups) + if(groups.contains(group.id)) transfer.groups[group.id]=groups.at(group.id); + if(transfer.groups.empty()) throw std::runtime_error("The file does not contain any supported settings groups."); + } + else transfer.groups=exportFilesOptionGroups(options.baseline); + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(617),dialog,filesTransferDialog, + reinterpret_cast(&transfer))!=IDOK) return; + for(size_t i=0;i(right.size()),TRUE)==CSTR_EQUAL; } -void loadFileStyles() +std::optional> parseFileStyles(const Json &rows) { - DWORD bytes{}; - if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,nullptr,&bytes)!=ERROR_SUCCESS || - !bytes || bytes>256*1024) return; - std::string data(bytes,'\0'); - if(RegGetValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,RRF_RT_REG_BINARY,nullptr,data.data(),&bytes)!=ERROR_SUCCESS) - return; try { - const auto rows=Json::parse(data.begin(),data.begin()+bytes); - if(!rows.is_array() || rows.size()>64) return; + if(!rows.is_array() || rows.size()>64) return {}; std::vector parsed; for(const auto &row:rows) { FileStyle style{ks::wide(row.at("extension").get())}; - if(style.extension!=L"@system-hidden" && fileStyleExtension(style.extension)!=style.extension) return; - if(std::any_of(parsed.begin(),parsed.end(),[&](const auto &existing){return existing.extension==style.extension;})) - return; - const auto color=[&](const char *key)->std::optional + if(style.extension!=L"@system-hidden" && fileStyleExtension(style.extension)!=style.extension) return {}; + if(std::ranges::any_of(parsed,[&](const auto &existing){return existing.extension==style.extension;})) + return {}; + const auto color=[](const Json &entry,const char *key)->std::optional { - if(!row.contains(key)) return {}; - const auto value=row.at(key).get(); - if(value>0xffffff) throw std::runtime_error("Invalid file style color"); - return value; + if(!entry.contains(key)) return {}; + const auto &value=entry.at(key); + if(!value.is_number_unsigned() || value>0xffffff) throw std::runtime_error("Invalid file style color"); + return value.get(); }; - style.foreground=color("foreground"); - style.background=color("background"); + style.foreground=color(row,"foreground"); + style.background=color(row,"background"); style.underline=row.value("underline",false); style.strikeout=row.value("strikeout",false); if(row.contains("states")) { const auto &states=row.at("states"); - if(!states.is_array() || states.size()!=style.states.size()) return; + if(!states.is_array() || states.size()!=style.states.size()) return {}; for(size_t i=0;istd::optional - { - if(!states[i].contains(key)) return {}; - const auto value=states[i].at(key).get(); - if(value>0xffffff) throw std::runtime_error("Invalid state color"); - return value; - }; - style.states[i]={read("foreground"),read("background")}; + if(!states[i].is_object()) return {}; + style.states[i]={color(states[i],"foreground"),color(states[i],"background")}; } } parsed.push_back(std::move(style)); } - fileStyles=std::move(parsed); + return parsed; } - catch(const std::exception &) {} + catch(const std::exception &) {return {};} } -bool saveFileStyles(const std::vector &styles) +void loadFileStyles() +{ + fileStyles=defaultFileStyles; + if(const auto rows=readFilesJsonPreference(fileStyleKey)) + if(auto parsed=parseFileStyles(*rows)) fileStyles=std::move(*parsed); +} + +Json serializeFileStyles(const std::vector &styles) { auto rows=Json::array(); for(const auto &style:styles) @@ -119,9 +113,12 @@ bool saveFileStyles(const std::vector &styles) } rows.push_back(std::move(row)); } - const auto data=rows.dump(); - return RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,fileStyleKey,REG_BINARY,data.data(), - static_cast(data.size()))==ERROR_SUCCESS; + return rows; +} + +bool saveFileStyles(const std::vector &styles) +{ + return writeFilesJsonPreference(fileStyleKey,serializeFileStyles(styles)); } struct FileRowStyle From 040658f350a581d4c04d9a09f1b8434035e53c85 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 23:21:06 +0200 Subject: [PATCH 46/61] Add independent Files scales and Windows theme palettes Refs #130 --- FILES-UI.md | 2 + resources/files.rc | 8 ++ src/files_appearance.h | 33 +++++ src/files_compare.inl | 13 +- src/files_main.cpp | 93 +++++++++---- src/files_options.inl | 248 +++++++++++++++++++++++++++++----- src/files_options_preview.inl | 3 +- src/files_text_preferences.h | 6 + src/files_text_window.cpp | 73 ++++++++-- src/files_text_window.h | 4 +- 10 files changed, 405 insertions(+), 78 deletions(-) create mode 100644 src/files_appearance.h diff --git a/FILES-UI.md b/FILES-UI.md index 9fb4a2d..15b5716 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -743,6 +743,8 @@ Warning і початковий фокус на No. - Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку. - Options → Import JSON / Export JSON переносить вибрані групи збережених параметрів Files. Окремо доступні кольори панелей і порівняння разом зі стилями файлів, режими й компонування панелей та іменовані схеми клавіш. Перед заміною відмінних схем з однаковою назвою Files запитує підтвердження. Імпорт спочатку оновлює чернетку Options. Apply або OK зберігає зміни, Cancel відкидає їх. Формат містить лише ці параметри. Невідомі поля і групи пропускаються. - Commands → Keyboard shortcuts відкриває іменовані схеми для команд файлових панелей та історії команд. У схемі можна задати кілька клавіш, вибрати основну, вилучити прив’язку, скопіювати схему під новим іменем, перемкнути чи скинути її. OK зберігає активну схему. Меню показує всі прив’язки, нижній ряд і текстові підказки відображають основну. Діалог відхиляє дублікати в контекстах, що перетинаються, і клавіші, зайняті навігацією. Попередні прив’язки історії та порівняння завантажуються як схема Previous settings. +- Масштаб панелей, текстового Viewer, Editor, Markdown, термінала й порівняння зберігається окремо. У Commands є Panel appearance або Terminal appearance залежно від видимої області. Options у Viewer, Editor та Markdown і кнопка Appearance у порівнянні відкривають відповідну сторінку. Значення 100% використовує обраний базовий розмір шрифту. +- Viewer і Editor підтримують колірну схему System (Windows). У Appearance → System themes можна призначити окремі палітри світлому й темному режимам Windows, включно із власними схемами. Rename scheme змінює назву власної схеми у списку, Viewer, Editor і призначеннях світлого та темного режимів. - Appearance → Dialog frame налаштовує зовнішній і внутрішній відступи від 0 до 24 px при 96 DPI. Row text padding додає від 0 до 4 ширин символу з кожного боку тексту в рядках Folder shortcuts. Inner padding задає відстань від рамки до краю списку. Ширина попапа враховує обидва текстові відступи, а довгі шляхи скорочуються в межах доступної ширини. Живий зразок показує чернетку. Apply зберігає значення, Cancel відкидає незастосовані зміни, Reset selected to defaults повертає 8 px, 14 px і 0 символів. Профілі без цих параметрів використовують ті самі значення. - У ресурсі чи виклику задавай назву кнопки й клавішу доступу. Спільна функція `paintDialogButton` центрує текст, підсвічує фокус і додає фігурні дужки для дії за замовчуванням та квадратні для решти кнопок. - Модальні діалоги редактора й переглядача використовують той самий шрифт, що й діалоги операцій Files. Розміри полів і кнопок враховують метрики цього шрифту. diff --git a/resources/files.rc b/resources/files.rc index c47b8cf..c17a4db 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -278,6 +278,7 @@ BEGIN PUSHBUTTON "Change color…", 366, 257, 181, 82, 15 LTEXT "", 367, 345, 184, 45, 12 PUSHBUTTON "&Save scheme…", 368, 131, 163, 118, 15 + PUSHBUTTON "Re&name scheme…", 534, 257, 163, 125, 15 AUTOCHECKBOX "Restore local Viewer and Editor windows after restart", 524, 131, 210, 250, 13 LTEXT "Maximum &width (px, 0 = full window)", 373, 131, 31, 184, 12 EDITTEXT 374, 318, 28, 64, 14, ES_NUMBER | ES_AUTOHSCROLL @@ -293,6 +294,13 @@ BEGIN PUSHBUTTON "Change color…", 412, 250, 97, 82, 15 LTEXT "", 413, 338, 100, 45, 12 PUSHBUTTON "&Keyboard shortcuts…", 415, 131, 127, 127, 15 + LTEXT "&Scale", 528, 131, 235, 118, 12 + COMBOBOX 529, 257, 232, 125, 98, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL + LTEXT "&Light mode palette", 530, 131, 32, 118, 12 + COMBOBOX 531, 250, 29, 132, 115, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL + LTEXT "&Dark mode palette", 532, 131, 56, 118, 12 + COMBOBOX 533, 250, 53, 132, 115, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL + LTEXT "Viewer and Editor use these palettes when Color scheme is set to System (Windows).", 535, 131, 80, 250, 28 PUSHBUTTON "&Import JSON…", 525, 8, 289, 70, 14 PUSHBUTTON "&Export JSON…", 526, 84, 289, 70, 14 DEFPUSHBUTTON "OK", IDOK, 222, 289, 50, 14 diff --git a/src/files_appearance.h b/src/files_appearance.h new file mode 100644 index 0000000..deaf089 --- /dev/null +++ b/src/files_appearance.h @@ -0,0 +1,33 @@ +#pragma once + +#include +#include +#include +#include + +namespace ks::files +{ +enum class AppearanceArea { panels, viewer, editor, markdown, terminal, comparison, count }; +inline constexpr size_t appearanceIndex(AppearanceArea area) { return static_cast(area); } +using AppearanceScales=std::array; +inline constexpr AppearanceScales defaultAppearanceScales{100,100,100,100,100,100}; +inline constexpr unsigned minAppearanceScale=75,maxAppearanceScale=200; + +inline int scaledAppearanceSize(int size,unsigned percent) +{ + return MulDiv(size,static_cast(percent),100); +} + +inline bool windowsAppThemeChanged(UINT message,LPARAM parameter) +{ + return message==WM_THEMECHANGED || (message==WM_SETTINGCHANGE && parameter && + std::wcscmp(reinterpret_cast(parameter),L"ImmersiveColorSet")==0); +} + +inline bool windowsUsesDarkApps() +{ + DWORD light=1,bytes=sizeof(light); + return RegGetValueW(HKEY_CURRENT_USER,L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", + L"AppsUseLightTheme",RRF_RT_REG_DWORD,nullptr,&light,&bytes)==ERROR_SUCCESS && !light; +} +} diff --git a/src/files_compare.inl b/src/files_compare.inl index a9968c5..97df201 100644 --- a/src/files_compare.inl +++ b/src/files_compare.inl @@ -134,8 +134,9 @@ void applyComparisonFont(HWND dialog,FileComparison &comparison) { auto font=comparison.appearance.font; const auto dpi=GetDpiForWindow(dialog); - const auto points=std::clamp(comparison.appearance.points+comparison.zoom,80,240); - comparison.zoom=points-comparison.appearance.points; + const auto base=areaFontPoints(comparison.appearance.points,AppearanceArea::comparison); + const auto points=std::clamp(base+comparison.zoom,60,480); + comparison.zoom=points-base; font.lfHeight=-MulDiv(points,dpi,720); font.lfWidth=0; if(const auto next=CreateFontIndirectW(&font)) @@ -178,8 +179,8 @@ bool zoomComparison(HWND dialog,FileComparison &comparison,WPARAM wheel) comparison.wheelRemainder+=GET_WHEEL_DELTA_WPARAM(wheel); const auto steps=comparison.wheelRemainder/WHEEL_DELTA; comparison.wheelRemainder%=WHEEL_DELTA; - const auto base=comparison.appearance.points; - const auto zoom=std::clamp(base+comparison.zoom+10*steps,80,240)-base; + const auto base=areaFontPoints(comparison.appearance.points,AppearanceArea::comparison); + const auto zoom=std::clamp(base+comparison.zoom+10*steps,60,480)-base; if(zoom!=comparison.zoom) { comparison.zoom=zoom; @@ -1000,7 +1001,8 @@ void initializeComparisonToolbar(HWND toolbar) {icon(HIST_BACK),404,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Previous")}, {icon(HIST_FORWARD),405,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Next")}, {separator,0,0,BTNS_SEP,{},0,0}, - {I_IMAGENONE,406,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast(L"Show whitespace changes")} + {I_IMAGENONE,406,TBSTATE_ENABLED,text|BTNS_CHECK,{},0,reinterpret_cast(L"Show whitespace changes")}, + {I_IMAGENONE,527,TBSTATE_ENABLED,text,{},0,reinterpret_cast(L"Appearance…")} }; SendMessageW(toolbar,TB_ADDBUTTONSW,std::size(buttons),reinterpret_cast(buttons)); } @@ -1107,6 +1109,7 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) const auto id=LOWORD(wp); if(comparison->working) return TRUE; if(id==IDCANCEL) {closeComparison(dialog,*comparison);return TRUE;} + if(id==527) {editFilesAppearance(dialog,AppearanceArea::comparison);return TRUE;} if(id==applyLeft || id==applyRight) { const auto side=id-applyLeft; diff --git a/src/files_main.cpp b/src/files_main.cpp index fe14710..5368e4d 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -48,6 +48,7 @@ #include "files_text_window.h" #include "files_menu_navigation.h" #include "files_text_preferences.h" +#include "files_appearance.h" #include "files_menu_paint.h" #include "files_dropdown_paint.h" #include "files_scrollbar.h" @@ -1061,10 +1062,33 @@ void setMode(int index,PanelMode mode) if((previous^effectivePanelColumns(panel))&extendedColumnMask) refreshPanelColumnData(panel); showFileDetails(panels[active]); } -HFONT mono{}; +HFONT mono{},terminalFont{}; LOGFONTW displayFont{}; int fontPoints=110; -int textHeight=20, cellWidth=9; +int textHeight=20, cellWidth=9,terminalTextHeight=20; + +using ks::files::AppearanceArea; +constexpr const wchar_t *areaScaleKeys[]{L"PanelScale",L"ViewerScale",L"EditorScale",L"MarkdownScale", + L"TerminalScale",L"ComparisonScale"}; +static_assert(std::size(areaScaleKeys)==ks::files::appearanceIndex(AppearanceArea::count)); + +unsigned readAreaScale(AppearanceArea area) +{ + const auto value=preference(areaScaleKeys[ks::files::appearanceIndex(area)],100); + return value>=ks::files::minAppearanceScale && value<=ks::files::maxAppearanceScale?value:100; +} + +ks::files::AppearanceScales readAreaScales() +{ + auto result=ks::files::defaultAppearanceScales; + for(size_t i=0;i(i)); + return result; +} + +int areaFontPoints(int points,AppearanceArea area) +{ + return ks::files::scaledAppearanceSize(points,readAreaScale(area)); +} using PanelColumnRects=std::array; @@ -1188,21 +1212,33 @@ std::array fileStyleFonts{}; bool applyFont(HWND owner, LOGFONTW font, int points) { const auto dpi=GetDpiForWindow(owner); - font.lfHeight=-MulDiv(points,dpi,720); font.lfWidth=0; - auto next=CreateFontIndirectW(&font); - if(!next) return false; + const int terminalPoints=areaFontPoints(points,AppearanceArea::terminal); + font.lfHeight=-MulDiv(terminalPoints,dpi,720); + const auto nextTerminal=CreateFontIndirectW(&font); + font.lfHeight=-MulDiv(areaFontPoints(points,AppearanceArea::panels),dpi,720); + const auto next=CreateFontIndirectW(&font); auto dc=GetDC(owner); - if(!dc){DeleteObject(next);return false;} - auto previous=SelectObject(dc,next); - TEXTMETRICW metrics{}; + if(!next || !nextTerminal || !dc) + { + if(next) DeleteObject(next); + if(nextTerminal) DeleteObject(nextTerminal); + if(dc) ReleaseDC(owner,dc); + return false; + } + const auto previous=SelectObject(dc,next); + TEXTMETRICW metrics{},terminalMetrics{}; GetTextMetricsW(dc,&metrics); + SelectObject(dc,nextTerminal); + GetTextMetricsW(dc,&terminalMetrics); SelectObject(dc,previous); ReleaseDC(owner,dc); textHeight=std::max(static_cast(MulDiv(16,dpi,96)),metrics.tmHeight+MulDiv(6,dpi,96)); cellWidth=std::max(1L,metrics.tmAveCharWidth); - auto old=mono; + terminalTextHeight=std::max(static_cast(MulDiv(16,dpi,96)),terminalMetrics.tmHeight+MulDiv(6,dpi,96)); + const auto old=mono,oldTerminal=terminalFont; mono=next; + terminalFont=nextTerminal; for(unsigned i=1;i(mono),FALSE); @@ -1224,7 +1261,8 @@ bool applyFont(HWND owner, LOGFONTW font, int points) if(picker) SendMessageW(picker,LB_SETITEMHEIGHT,0,textHeight); if(status) SendMessageW(status,WM_SETFONT,reinterpret_cast(mono),FALSE); for(const auto control:{terminalInput,terminalOutput,terminalPrompt}) - if(control) SendMessageW(control,WM_SETFONT,reinterpret_cast(mono),FALSE); + if(control) SendMessageW(control,WM_SETFONT,reinterpret_cast(terminalFont),FALSE); + if(oldTerminal) DeleteObject(oldTerminal); if(old) { EnumThreadWindows(GetCurrentThreadId(),[](HWND window,LPARAM parameter)->BOOL @@ -1637,7 +1675,7 @@ void layout(HWND window,bool activeOnly) RECT rect{}; GetClientRect(window, &rect); int width = rect.right, height = rect.bottom; - const int inputTop=height-2*textHeight; + const int inputTop=height-textHeight-terminalTextHeight; const bool gitMode=showingGitChanges(); const int terminalBottom=std::max(4,inputTop); const int summaryHeight=!terminalVisible && hasSelectionSummary()?textHeight:0; @@ -1648,7 +1686,7 @@ void layout(HWND window,bool activeOnly) const int panelMargin=compactLayout?4:5; const int pathTop=driveHeight+(compactLayout?1:4); const int terminalTop=terminalVisible?4:std::max(4,terminalBottom- - std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/textHeight-4))*textHeight); + std::min(terminalRows,std::max(0,(terminalBottom-detailsHeight)/terminalTextHeight-4))*terminalTextHeight); const int panelBottom=terminalTop-detailsHeight; const bool showOutput=!gitMode && terminalTop(prompt.size())*cellWidth,0}; if(const auto dc=GetDC(window)) { - const auto previous=SelectObject(dc,mono); + const auto previous=SelectObject(dc,terminalFont); GetTextExtentPoint32W(dc,prompt.c_str(),static_cast(prompt.size()),&promptExtent); SelectObject(dc,previous); ReleaseDC(window,dc); } const int promptWidth=std::min(width/2,static_cast(promptExtent.cx)); - place(terminalPrompt,4,inputTop,promptWidth,textHeight); - place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),textHeight); + place(terminalPrompt,4,inputTop,promptWidth,terminalTextHeight); + place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),terminalTextHeight); if(activeOnly) { const RECT details{0,panelBottom+detailsInset+summaryHeight,width, @@ -2408,7 +2446,7 @@ bool ensureTerminalView(HWND owner,bool ssh=false) auto &source=ssh?sshView:terminalView; if(message==L"ready") { - source.setFont(displayFont,fontPoints); + source.setFont(displayFont,areaFontPoints(fontPoints,AppearanceArea::terminal)); if(ssh) source.post(L"ssh-reset"); if(terminalTrace.is_open() && !ssh) source.enableTrace(traceTerminalOutput); } @@ -3779,7 +3817,7 @@ ks::files::FarDropDownPalette farDropDownPalette(); void prepareCopyDialog(HWND dialog); void prepareTextDialog(HWND dialog); void showTextMessage(HWND owner,const wchar_t *text); -void editTextOptions(HWND owner,bool edit); +void editFilesAppearance(HWND owner,AppearanceArea area); void startPeerAction(std::packaged_task task,const std::wstring &status) { @@ -3950,6 +3988,7 @@ void selectDrive() else if(menuIndex==2 && row==18) swapPanels(owner); else if(menuIndex==2 && row==19) showCommandHistory(owner); else if(menuIndex==2 && row==20) editFilesKeySchemes(owner,FilesKey::Refresh); + else if(menuIndex==2 && row==21) editFilesAppearance(owner,terminalVisible?AppearanceArea::terminal:AppearanceArea::panels); else if(menuIndex==1 && row==4) createArchive(owner,panels[active]); else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]); else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]); @@ -4519,7 +4558,7 @@ void openSelectedWithSystem(const Panel &panel) ks::files::TextDialogs textWindowDialogs() { - return {confirmTextSave,paintTextDialog,paintSearchDialog,prepareTextDialog,editTextOptions,showTextMessage,readFilesFont, + return {confirmTextSave,paintTextDialog,paintSearchDialog,prepareTextDialog,editFilesAppearance,showTextMessage,readFilesFont, farDropDownPalette,FilesModalDialog::run,FilesModalDialog::finish,FilesModalDialog::dismissOwned, [](HWND owner) { @@ -4531,7 +4570,7 @@ ks::files::TextDialogs textWindowDialogs() return showFilesNotice(owner,L"The file changed outside Files. Reload the disk version?", L"File changed on disk",{.confirm=true,.tone=FilesNoticeTone::warning, .accept=L"&Reload",.decline=L"&Keep buffer"})==IDYES; - }}; + },readAreaScale}; } void refreshQuickView(const Panel &panel) @@ -8298,7 +8337,8 @@ void openMenu(HWND window, int index) filesKeyMenuLabel(FilesKey::Find),filesKeyMenuLabel(FilesKey::QuickView,quickViewWindow?L"Close Quick View":L"Quick View"), filesKeyMenuLabel(FilesKey::FullPath),L"Space Analyzer",filesKeyMenuLabel(FilesKey::HexView), L"Viewer bookmarks…",L"Processes…",L"Git Changes…",L"Environment Variables…",filesKeyMenuLabel(FilesKey::Swap), - filesKeyMenuLabel(FilesKey::History),L"Keyboard shortcuts…"}; + filesKeyMenuLabel(FilesKey::History),L"Keyboard shortcuts…", + terminalVisible?L"Terminal appearance…":L"Panel appearance…"}; } const auto &panel=panels[active]; const bool remoteResults=remoteSearchResults(panel); @@ -8345,7 +8385,7 @@ void openMenu(HWND window, int index) } if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10); if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7}); - commandActions.insert(commandActions.end(),{-1,19,20}); + commandActions.insert(commandActions.end(),{-1,19,20,21}); } else for(size_t i=0;i(i)); @@ -8558,6 +8598,8 @@ void handleFilesReturn(bool shift) LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) { + if(quickViewWindow && ks::files::windowsAppThemeChanged(message,lp)) + SendMessageW(quickViewWindow,message,wp,lp); if(message==filesPreferencesChanged) { if(quickViewWindow) SendNotifyMessageW(quickViewWindow,message,wp,lp); @@ -8694,7 +8736,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) terminalBackground=CreateSolidBrush(terminalSurface); if(!terminalInput || !terminalOutput || !terminalPrompt || !terminalBackground) return -1; for(const auto control:{terminalInput,terminalOutput,terminalPrompt}) - SendMessageW(control,WM_SETFONT,reinterpret_cast(mono),FALSE); + SendMessageW(control,WM_SETFONT,reinterpret_cast(terminalFont),FALSE); SendMessageW(terminalInput,EM_SETLIMITTEXT,2048,0); SendMessageW(terminalInput,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,0); SetWindowSubclass(terminalInput,terminalInputKeys,1,0); @@ -9568,7 +9610,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { RECT bounds{}; GetClientRect(window,&bounds); - const auto maximum=std::max(0,static_cast(bounds.bottom)/textHeight-8); + const auto maximum=std::max(0,static_cast(bounds.bottom)/terminalTextHeight-8); const int rows=std::clamp(terminalRows+(message.wParam==VK_UP?1:-1),0,maximum); traceTerminal(message.wParam==VK_UP?"key-grow":"key-shrink",terminalRows,rows); if(rows && !showCommandOutput(window,panels[active])) continue; @@ -9755,6 +9797,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) } for(auto font:fileStyleFonts) if(font) DeleteObject(font); DeleteObject(mono); + DeleteObject(terminalFont); DeleteObject(blue); DeleteObject(teal); DeleteObject(terminalBackground); diff --git a/src/files_options.inl b/src/files_options.inl index c1865d0..972f2db 100644 --- a/src/files_options.inl +++ b/src/files_options.inl @@ -18,14 +18,17 @@ constexpr int wideColumnControls[]{275,276,201,202,204}; constexpr int statusColumnControls[]{277,203,205,206,207,208}; constexpr int colorOptionControls[]{279,280}; constexpr int appearanceControls[]{281,282}; -enum AppearanceSection { Font, DialogFrame }; +enum AppearanceSection { Font, DialogFrame, SystemThemes }; +constexpr int terminalScaleSection=1,areaScaleLabel=528,areaScaleControl=529; +constexpr int systemLightChoice=531,systemDarkChoice=533; +constexpr int systemThemeControls[]{530,systemLightChoice,532,systemDarkChoice,535}; constexpr int outerFramePadding=303,innerFramePadding=305,rowTextPadding=307; constexpr int dialogFrameControls[]{302,outerFramePadding,304,innerFramePadding,306,rowTextPadding}; constexpr int restoreDocumentsControl=524; constexpr int textTabWidth=357,textLineEnding=359, - textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368; + textTheme=363,textColor=365,textChangeColor=366,textColorValue=367,textSaveScheme=368,textRenameScheme=534; constexpr int textControls[]{350,351,352,353,356,textTabWidth, - 362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme}; + 362,textTheme,364,textColor,textChangeColor,textColorValue,textSaveScheme,textRenameScheme}; constexpr int editingControls[]{354,355,358,textLineEnding}; constexpr int markdownSection=1,markdownWidth=374,markdownFamily=376,markdownChoose=377,markdownSize=379; constexpr int markdownControls[]{373,markdownWidth,375,markdownFamily,markdownChoose,378,markdownSize}; @@ -118,6 +121,7 @@ struct OptionsBaseline ks::files::TextSettings text=ks::files::loadTextPreferences(); ComparisonAppearance comparison=readComparisonAppearance(); FilesKeySettings keySettings=filesKeySettings; + ks::files::AppearanceScales scales=readAreaScales(); }; struct OptionsDraft @@ -126,6 +130,7 @@ struct OptionsDraft ks::files::TextSettings text=baseline.text; ComparisonAppearance comparison=baseline.comparison; FilesKeySettings keySettings=baseline.keySettings; + ks::files::AppearanceScales scales=baseline.scales; HWND filesWindow{}; LOGFONTW font=displayFont; int points=fontPoints; @@ -184,7 +189,8 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft) checked(optionsRemoteTerminal)!=base.remoteTerminal || checked(optionsRemoteHibernate)!=base.remoteHibernate || checked(optionsRemoteUpdate)!=base.remoteUpdate || - draft.text!=base.text || draft.comparison!=base.comparison || draft.keySettings!=base.keySettings; + draft.text!=base.text || draft.comparison!=base.comparison || draft.keySettings!=base.keySettings || + draft.scales!=base.scales; EnableWindow(GetDlgItem(dialog,optionsApply),dirty); InvalidateRect(GetDlgItem(dialog,fileStylePreview),nullptr,FALSE); } @@ -278,19 +284,22 @@ void populateTextSchemes(HWND dialog,const ks::files::TextSettings &settings) }; add(L"Custom"); for(const auto name:ks::files::textPaletteNames) add(name); + add(L"System (Windows)"); for(const auto &scheme:settings.schemes) add(scheme.name.c_str()); } size_t currentTextScheme(const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile) { - for(size_t index=0;index(lp); + if(!name.empty()) + { + SetWindowTextW(dialog,L"Rename color scheme"); + SetDlgItemTextW(dialog,100,name.c_str()); + SetDlgItemTextW(dialog,IDOK,L"Rename"); + } groupDialogButtons(dialog,{IDOK,IDCANCEL},true); return TRUE; } @@ -318,13 +334,22 @@ INT_PTR CALLBACK schemeNameDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) return TRUE; } -void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files::TextPreferences &profile) +bool reservedTextSchemeName(const std::wstring &name) { + return sameSchemeName(name,L"Custom") || sameSchemeName(name,L"System (Windows)") || + sameSchemeName(name,ks::files::systemTextScheme) || + std::any_of(std::begin(ks::files::textPaletteNames),std::end(ks::files::textPaletteNames), + [&](const wchar_t *preset){return sameSchemeName(name,preset);}); +} + +void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,bool edit) +{ + auto &profile=settings.profiles[edit]; + const auto palette=ks::files::resolvedTextProfile(settings,edit).colors; std::wstring name; if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog, reinterpret_cast(&name))!=IDOK) return; - if(sameSchemeName(name,L"Custom") || std::any_of(std::begin(ks::files::textPaletteNames), - std::end(ks::files::textPaletteNames),[&](const wchar_t *preset){return sameSchemeName(name,preset);})) + if(reservedTextSchemeName(name)) { showFilesNotice(dialog,L"Choose a different name for your color scheme.",L"Save color scheme"); return; @@ -335,7 +360,7 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files { if(showFilesNotice(dialog,L"Replace the saved scheme with the current colors?",L"Save color scheme", {.confirm=true,.tone=FilesNoticeTone::neutral})!=IDYES) return; - existing->colors=profile.colors; + existing->colors=palette; profile.scheme=existing->name; } else @@ -345,18 +370,44 @@ void saveTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,ks::files showFilesNotice(dialog,L"The color scheme list is full.",L"Save color scheme"); return; } - settings.schemes.push_back({name,profile.colors}); + settings.schemes.push_back({name,palette}); profile.scheme=std::move(name); } + profile.colors=palette; populateTextSchemes(dialog,settings); } -void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,const ks::files::TextPreferences &profile) +void renameTextSchemeDraft(HWND dialog,ks::files::TextSettings &settings,const ks::files::TextPreferences &profile) { + const auto scheme=std::ranges::find_if(settings.schemes,[&](const auto &candidate) + { return sameSchemeName(profile.scheme,candidate.name.c_str()); }); + if(scheme==settings.schemes.end()) return; + auto name=scheme->name; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(608),dialog,schemeNameDialog, + reinterpret_cast(&name))!=IDOK || name==scheme->name) return; + if(reservedTextSchemeName(name) || std::ranges::any_of(settings.schemes,[&](const auto &candidate) + {return &candidate!=&*scheme && sameSchemeName(name,candidate.name.c_str());})) + { + showFilesNotice(dialog,L"Choose a unique name for the color scheme.",L"Rename color scheme"); + return; + } + for(auto &document:settings.profiles) + if(sameSchemeName(document.scheme,scheme->name.c_str())) document.scheme=name; + for(auto &role:settings.systemThemes) + if(sameSchemeName(role,scheme->name.c_str())) role=name; + scheme->name=std::move(name); + populateTextSchemes(dialog,settings); +} + +void showTextOptions(HWND dialog,const ks::files::TextSettings &settings,bool edit) +{ + const auto profile=ks::files::resolvedTextProfile(settings,edit); for(const auto &check:textChecks) CheckDlgButton(dialog,check.id,profile.*check.value?BST_CHECKED:BST_UNCHECKED); SendDlgItemMessageW(dialog,textTabWidth,CB_SETCURSEL,profile.tabWidth-1,0); SendDlgItemMessageW(dialog,textLineEnding,CB_SETCURSEL,profile.lineEnding,0); - SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,currentTextScheme(settings,profile),0); + const auto selected=currentTextScheme(settings,profile); + SendDlgItemMessageW(dialog,textTheme,CB_SETCURSEL,selected,0); + EnableWindow(GetDlgItem(dialog,textRenameScheme),selected>=std::size(ks::files::textPalettes)+2); refreshTextColor(dialog,profile); } @@ -391,12 +442,20 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command) if(const auto check=std::find_if(std::begin(textChecks),std::end(textChecks), [id](const auto &entry){return entry.id==id;});check!=std::end(textChecks)) profile.*check->value=IsDlgButtonChecked(dialog,id)==BST_CHECKED; - else if(id==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,profile); + else if(id==textSaveScheme) saveTextSchemeDraft(dialog,draft.text,draft.page==TextEditor); + else if(id==textRenameScheme) renameTextSchemeDraft(dialog,draft.text,profile); else if(id==textChangeColor) { const auto index=row(textColor); if(index>=0 && static_cast(index)(selected)+1; break; case textLineEnding: profile.lineEnding=static_cast(selected); break; case textTheme: - if(selected==0) profile.scheme.clear(); + if(selected==0) + { + profile.colors=ks::files::resolvedTextProfile(draft.text,draft.page==TextEditor).colors; + profile.scheme.clear(); + } else if(const auto scheme=static_cast(selected-1);scheme=draft.text.schemes.size()) return false; profile.scheme=draft.text.schemes[index].name; profile.colors=draft.text.schemes[index].colors; @@ -426,7 +490,7 @@ bool changeTextOption(HWND dialog,OptionsDraft &draft,WPARAM command) } } else return false; - showTextOptions(dialog,draft.text,profile); + showTextOptions(dialog,draft.text,draft.page==TextEditor); updateOptionsApply(dialog,draft); return true; } @@ -445,6 +509,65 @@ void showComparisonOptions(HWND dialog,const ComparisonAppearance &appearance) SetDlgItemTextW(dialog,comparisonColorValue,hex); } +std::optional optionsScaleArea(int page,int section) +{ + if(page==Appearance && section==Font) return AppearanceArea::panels; + if(page==CommandLine && section==terminalScaleSection) return AppearanceArea::terminal; + if(page==TextViewer) return section==markdownSection?AppearanceArea::markdown:AppearanceArea::viewer; + if(page==TextEditor) return AppearanceArea::editor; + if(page==CompareFiles) return AppearanceArea::comparison; + return {}; +} + +void showAreaScale(HWND dialog,const OptionsDraft &draft,std::optional area) +{ + const auto label=GetDlgItem(dialog,areaScaleLabel); + const auto field=GetDlgItem(dialog,areaScaleControl); + ShowWindow(label,area?SW_SHOW:SW_HIDE); + ShowWindow(field,area?SW_SHOW:SW_HIDE); + if(!area) return; + const auto index=ks::files::appearanceIndex(*area); + constexpr const wchar_t *labels[]{L"&Panel scale",L"&Viewer scale",L"&Editor scale",L"&Markdown scale", + L"&Terminal scale",L"&Comparison scale"}; + constexpr int top[]{77,232,232,124,29,155}; + SetWindowTextW(label,labels[index]); + RECT labelBox{131,top[index]+3,0,0},fieldBox{257,top[index],0,0}; + MapDialogRect(dialog,&labelBox); + MapDialogRect(dialog,&fieldBox); + const auto flags=SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE; + SetWindowPos(label,nullptr,labelBox.left,labelBox.top,0,0,flags); + SetWindowPos(field,nullptr,fieldBox.left,fieldBox.top,0,0,flags); + SendMessageW(field,CB_RESETCONTENT,0,0); + const auto selected=draft.scales[index]; + for(unsigned percent=ks::files::minAppearanceScale;percent<=ks::files::maxAppearanceScale;++percent) + { + if(percent%5 && percent!=selected) continue; + const auto caption=std::to_wstring(percent)+L"%"; + const auto row=SendMessageW(field,CB_ADDSTRING,0,reinterpret_cast(caption.c_str())); + if(row<0) continue; + SendMessageW(field,CB_SETITEMDATA,row,percent); + if(percent==selected) SendMessageW(field,CB_SETCURSEL,row,0); + } +} + +void showSystemThemeRoles(HWND dialog,const ks::files::TextSettings &settings) +{ + constexpr int controls[]{systemLightChoice,systemDarkChoice}; + for(size_t role=0;role(name)); + if(row>=0 && sameSchemeName(settings.systemThemes[role],name)) + SendMessageW(control,CB_SETCURSEL,row,0); + }; + for(const auto name:ks::files::textPaletteNames) add(name); + for(const auto &scheme:settings.schemes) add(scheme.name.c_str()); + } +} + void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) { draft.page=page; @@ -459,7 +582,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) else if(section>=0 && !textOptionsPage(page) && page!=CompareFiles) title=page==PanelModes?panelSectionNames[section]:page==PanelColors? (section==fileStyleSection?L"File type styles":colorNames[section]): - page==CommandLine?L"Command history":section==DialogFrame?L"Dialog frame":L"Font"; + page==CommandLine?(section==terminalScaleSection?L"Terminal appearance":L"Command history"): + section==SystemThemes?L"System themes":section==DialogFrame?L"Dialog frame":L"Font"; } SetDlgItemTextW(dialog,optionsTitle,title); const auto show=[&](auto &controls,bool visible) @@ -487,6 +611,9 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) show(wideColumnControls,page==PanelModes && section==WideColumns); show(statusColumnControls,page==PanelModes && section==StatusColumns); show(appearanceControls,page==Appearance && section==Font); + show(systemThemeControls,page==Appearance && section==SystemThemes); + if(page==Appearance && section==SystemThemes) showSystemThemeRoles(dialog,draft.text); + showAreaScale(dialog,draft,optionsScaleArea(page,section)); show(comparisonControls,page==CompareFiles); if(page==CompareFiles) showComparisonOptions(dialog,draft.comparison); show(dialogFrameControls,page==Appearance && section==DialogFrame); @@ -501,12 +628,13 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) show(textControls,textOptionsPage(page) && !markdown); ShowWindow(GetDlgItem(dialog,restoreDocumentsControl),page==TextViewer && !markdown?SW_SHOW:SW_HIDE); show(editingControls,page==TextEditor); - if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,draft.text.profiles[page==TextEditor]); + if(textOptionsPage(page) && !markdown) showTextOptions(dialog,draft.text,page==TextEditor); const bool fileTypes=page==PanelColors && section==fileStyleSection; constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState}; show(fileStyleControls,fileTypes); const auto preview=GetDlgItem(dialog,fileStylePreview); - ShowWindow(preview,page>=0 && page=0?SW_SHOW:SW_HIDE); + const bool panelPreview=page>=0 && page=0 && !(page==Appearance && section==SystemThemes); + ShowWindow(preview,panelPreview?SW_SHOW:SW_HIDE); layoutOptionsPreview(dialog); RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN); show(colorOptionControls,page==PanelColors && section>=0 && !fileTypes); @@ -599,16 +727,21 @@ void filterOptions(HWND dialog,OptionsDraft &draft) addSection(L"File type styles",fileStyleSection,extensionMatches || matches(L"System and hidden") || matches(L"Underline") || matches(L"Strikethrough") || matches(L"Foreground")); } - else if(page==CommandLine) addSection(L"Command history",0, - matches(L"Previous command") || matches(L"Keyboard shortcuts") || matches(L"Allow paired PCs to run PowerShell commands here") || - matches(L"Allow paired PCs to hibernate this PC") || matches(L"Allow paired PCs to update KSwitcher here")); + else if(page==CommandLine) + { + addSection(L"Command history",0,matches(L"Previous command") || matches(L"Keyboard shortcuts") || + matches(L"Allow paired PCs to run PowerShell commands here") || matches(L"Allow paired PCs to hibernate this PC") || + matches(L"Allow paired PCs to update KSwitcher here")); + addSection(L"Terminal appearance",terminalScaleSection,matches(L"Terminal scale")); + } else if(page==CompareFiles) - addSection(L"Font and colors",0,matches(L"Compare files shortcut") || matches(L"Keyboard shortcuts") || std::any_of(std::begin(comparisonColorNames), + addSection(L"Font and colors",0,matches(L"Comparison scale") || matches(L"Compare files shortcut") || matches(L"Keyboard shortcuts") || std::any_of(std::begin(comparisonColorNames), std::end(comparisonColorNames),matches)); else if(textOptionsPage(page)) { const bool propertyMatches=matches(L"Tab width") || - matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Customize colors") || + matches(L"Color scheme") || matches(L"Save scheme") || matches(L"Rename scheme") || matches(L"Customize colors") || + matches(page==TextEditor?L"Editor scale":L"Viewer scale") || (page==TextEditor && matches(L"Line endings for new lines")) || (page==TextViewer && matches(L"Restore local Viewer and Editor windows after restart")) || std::any_of(std::begin(textChecks),std::end(textChecks),[&](const auto &check) @@ -616,11 +749,13 @@ void filterOptions(HWND dialog,OptionsDraft &draft) std::any_of(std::begin(ks::files::textColorNames),std::end(ks::files::textColorNames),matches); addSection(page==TextEditor?L"Editing and appearance":L"Viewing and appearance",0,propertyMatches); if(page==TextViewer) addSection(L"Markdown",markdownSection, - matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size")); + matches(L"Maximum width") || matches(L"Full window") || matches(L"Font family") || matches(L"Font size") || + matches(L"Markdown scale")); } else { - addSection(L"Font",Font,matches(L"Display font")); + addSection(L"Font",Font,matches(L"Display font") || matches(L"Panel scale")); + addSection(L"System themes",SystemThemes,matches(L"Light mode palette") || matches(L"Dark mode palette")); addSection(L"Dialog frame",DialogFrame, matches(L"Outer padding") || matches(L"Inner padding") || matches(L"Row text padding")); } @@ -742,6 +877,29 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) case optionsSearch: if(HIWORD(wp)==EN_CHANGE) filterOptions(dialog,*draft); return TRUE; + case areaScaleControl: + if(HIWORD(wp)==CBN_SELCHANGE) + if(const auto area=optionsScaleArea(draft->page,draft->section)) + { + const auto row=SendDlgItemMessageW(dialog,areaScaleControl,CB_GETCURSEL,0,0); + if(row>=0) + { + const auto percent=SendDlgItemMessageW(dialog,areaScaleControl,CB_GETITEMDATA,row,0); + if(percent>=ks::files::minAppearanceScale && percent<=ks::files::maxAppearanceScale) + draft->scales[ks::files::appearanceIndex(*area)]=static_cast(percent); + } + updateOptionsApply(dialog,*draft); + } + return TRUE; + case systemLightChoice: case systemDarkChoice: + if(HIWORD(wp)==CBN_SELCHANGE) + { + wchar_t name[ks::files::maxTextPaletteName+1]{}; + GetDlgItemTextW(dialog,LOWORD(wp),name,std::size(name)); + if(ks::files::namedTextPalette(draft->text,name)) draft->text.systemThemes[LOWORD(wp)==systemDarkChoice]=name; + updateOptionsApply(dialog,*draft); + } + return TRUE; case 279: if(draft->page==PanelColors && draft->section>=0 && draft->sectionpage==allOptions) draft->scales=ks::files::defaultAppearanceScales; + else if(const auto area=optionsScaleArea(draft->page,draft->section)) + draft->scales[ks::files::appearanceIndex(*area)]=100; + if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==SystemThemes))) + draft->text.systemThemes=ks::files::TextSettings{}.systemThemes; if(draft->page==allOptions || draft->page==CompareFiles) draft->comparison=ComparisonAppearance{}; if(draft->page==allOptions || draft->page==CommandLine) @@ -867,12 +1030,12 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) if(draft->page==allOptions || (draft->page==PanelColors && (draft->section<0 || draft->section==fileStyleSection))) draft->styles=defaultFileStyles; - if(draft->page==allOptions || (draft->page==Appearance && draft->section!=DialogFrame)) + if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==Font))) { draft->font=defaultFilesFont(); draft->points=defaultFontPoints; } - if(draft->page==allOptions || (draft->page==Appearance && draft->section!=Font)) + if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==DialogFrame))) draft->framePadding=defaultDialogFramePadding; if(draft->page==allOptions || (draft->page==TextViewer && draft->section!=markdownSection)) CheckDlgButton(dialog,restoreDocumentsControl,BST_UNCHECKED); @@ -991,6 +1154,16 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } textSettings.schemes=draft->text.schemes; } + if(draft->text.systemThemes!=base.text.systemThemes) + { + if(textSettings.systemThemes!=base.text.systemThemes && textSettings.systemThemes!=draft->text.systemThemes) + { + showFilesNotice(dialog,L"System theme choices changed in another window. Reopen Options before editing them again.", + L"System themes"); + return TRUE; + } + textSettings.systemThemes=draft->text.systemThemes; + } const bool stylesChanged=draft->styles!=base.styles; loadFileStyles(); if(stylesChanged && fileStyles!=base.styles && fileStyles!=draft->styles) @@ -1071,6 +1244,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) saveChanged(dialogFrameOuterKey,draft->framePadding.outer,base.padding.outer); saveChanged(dialogFrameInnerKey,draft->framePadding.inner,base.padding.inner); saveChanged(dialogRowTextKey,draft->framePadding.rowText,base.padding.rowText); + for(size_t i=0;iscales.size();++i) saveChanged(areaScaleKeys[i],draft->scales[i],base.scales[i]); if(fontChanged) { savePreference(L"FontPoints",fontPoints); @@ -1091,6 +1265,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) draft->text=draft->baseline.text; draft->comparison=draft->baseline.comparison; draft->keySettings=draft->baseline.keySettings; + draft->scales=draft->baseline.scales; showMarkdownOptions(dialog,draft->text.markdown); populateTextSchemes(dialog,draft->text); draft->font=displayFont; @@ -1125,13 +1300,13 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) return FALSE; } -void runOptions(HWND owner,int page) +void runOptions(HWND owner,int page,int section=0,bool restoreLocation=true) { loadFilesKeySettings(); OptionsDraft draft; draft.filesWindow=GetAncestor(owner,GA_ROOTOWNER); - const DWORD initial=static_cast((page<<8)|1); - const auto saved=preference(optionsLocationKey,initial); + const DWORD initial=static_cast((page<<8)|(section+1)); + const auto saved=restoreLocation?preference(optionsLocationKey,initial):initial; draft.location=(saved>>8)<=CompareFiles?saved:initial; draft.page=static_cast(draft.location>>8); draft.section=static_cast(draft.location&255)-1; @@ -1148,7 +1323,10 @@ void editOptions(HWND owner) SetFocus(panels[active].list); } -void editTextOptions(HWND owner,bool edit) +void editFilesAppearance(HWND owner,AppearanceArea area) { - runOptions(owner,edit?TextEditor:TextViewer); + constexpr int pages[]{Appearance,TextViewer,TextEditor,TextViewer,CommandLine,CompareFiles}; + constexpr int sections[]{Font,0,0,markdownSection,terminalScaleSection,0}; + const auto index=ks::files::appearanceIndex(area); + runOptions(owner,pages[index],sections[index],false); } diff --git a/src/files_options_preview.inl b/src/files_options_preview.inl index caa4394..0cc1da8 100644 --- a/src/files_options_preview.inl +++ b/src/files_options_preview.inl @@ -7,7 +7,8 @@ void paintOptionsPreview(HWND dialog,const DRAWITEMSTRUCT &item,const OptionsDra const auto dpi=GetDpiForWindow(item.hwndItem); const auto px=[&](int value){return MulDiv(value,dpi,96);}; auto font=draft.font; - font.lfHeight=-MulDiv(draft.points,dpi,720); + const auto panelScale=draft.scales[ks::files::appearanceIndex(AppearanceArea::panels)]; + font.lfHeight=-MulDiv(ks::files::scaledAppearanceSize(draft.points,panelScale),dpi,720); font.lfWidth=0; const auto previewFont=CreateFontIndirectW(&font); SelectObject(dc,previewFont?previewFont:mono); diff --git a/src/files_text_preferences.h b/src/files_text_preferences.h index a234e89..62d7581 100644 --- a/src/files_text_preferences.h +++ b/src/files_text_preferences.h @@ -2,12 +2,15 @@ #include #include +#include +#include #include #include namespace ks::files { inline constexpr size_t documentColorCount = 10; +inline constexpr wchar_t systemTextScheme[]=L"@system"; using TextPalette = std::array; inline constexpr const wchar_t *textPaletteNames[] = {L"FAR (blue)", L"Dark", L"Light"}; inline constexpr TextPalette textPalettes[] = { @@ -56,8 +59,11 @@ struct TextSettings TextPreferencesSet profiles; std::vector schemes; MarkdownPreferences markdown; + std::array systemThemes{textPaletteNames[2],textPaletteNames[1]}; bool operator==(const TextSettings &) const = default; }; +std::optional namedTextPalette(const TextSettings &settings,std::wstring_view name); +TextPreferences resolvedTextProfile(const TextSettings &settings,bool editor); TextSettings loadTextPreferences(); void saveTextPreferences(const TextSettings &settings); } diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index 3921cf7..fab1850 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -73,6 +73,30 @@ void readTextProfile(TextPreferences &prefs, const nlohmann::json &data) } } +std::optional namedTextPalette(const TextSettings &settings,std::wstring_view name) +{ + const auto matches=[&](const wchar_t *other) + { + return !name.empty() && CompareStringOrdinal(name.data(),static_cast(name.size()),other,-1,TRUE)==CSTR_EQUAL; + }; + for(size_t i=0;iis_object()) + { + constexpr const char *roles[]{"light","dark"}; + for(size_t i=0;ifind(roles[i]);name!=system->end() && name->is_string()) + { + auto value=wide(name->get()); + if(value.size()<=maxTextPaletteName && namedTextPalette(settings,value)) + settings.systemThemes[i]=std::move(value); + } + } return settings; } const wchar_t *legacy[]{L"files-viewer.json", L"files-editor.json"}; @@ -140,6 +175,7 @@ void saveTextPreferences(const TextSettings &settings) schemes.push_back({{"name", utf8(scheme.name)}, {"colors", scheme.colors}}); data["markdown"]={{"width",settings.markdown.width},{"fontSize",settings.markdown.fontSize}, {"font",utf8(settings.markdown.font)}}; + data["systemThemes"]={{"light",utf8(settings.systemThemes[0])},{"dark",utf8(settings.systemThemes[1])}}; const auto json = data.dump(2); atomicWrite(dataDirectory() / L"files-text.json", Bytes(json.begin(), json.end())); } @@ -683,6 +719,19 @@ std::future> fetchRemoteText(const RemoteTextSou return result; } +unsigned textAreaScale(TextDialogs dialogs,AppearanceArea area) +{ + return dialogs.readScale?dialogs.readScale(area):100; +} + +TextWindowFont scaledDocumentFont(TextDialogs dialogs,bool editor) +{ + auto font=dialogs.readFont(); + font.tenthsOfPoint=scaledAppearanceSize(font.tenthsOfPoint, + textAreaScale(dialogs,editor?AppearanceArea::editor:AppearanceArea::viewer)); + return font; +} + class TextWindow; std::map> textWindows; std::vector textWindowOrder; @@ -771,7 +820,7 @@ public: : original(std::move(path)), peerId(backend?backend->id:""), filename(original.filename().wstring()), edit(editable), draft(options.draft), embedded(quickView), hex(options.hex && !editable), initialBookmark(options.line), - prefs(loadTextPreferences().profiles[editable]), filesFont(dialogs.readFont()), + prefs(resolvedTextProfile(loadTextPreferences(),editable)), filesFont(scaledDocumentFont(dialogs,editable)), search{dialogs}, previewFragment(fragment) { if (backend) remote=std::make_unique(*backend,original); @@ -1318,8 +1367,8 @@ void TextWindow::reloadPreferences() pendingPreferences = false; auto settings = loadTextPreferences(); applyMarkdownPreferences(settings.markdown); - auto &profile = settings.profiles[edit]; - const auto font = search.style.readFont(); + auto profile=resolvedTextProfile(settings,edit); + const auto font=scaledDocumentFont(search.style,edit); const bool fontChanged = font.tenthsOfPoint != filesFont.tenthsOfPoint || std::memcmp(&font.font, &filesFont.font, sizeof(LOGFONTW)) != 0; if (!fontChanged && profile == prefs) return; @@ -2060,7 +2109,8 @@ void TextWindow::showTextMode(const ViewerPosition &position,std::string content { rememberLocalVersion(); if(canPreview()) ShowWindow(editor,SW_HIDE); - prefs = loadTextPreferences().profiles[edit]; + prefs=resolvedTextProfile(loadTextPreferences(),edit); + filesFont=scaledDocumentFont(search.style,edit); releaseMenu(); createMenu(); installLexer(); @@ -2366,8 +2416,9 @@ void TextWindow::renderPreview(bool keepPosition) void TextWindow::applyMarkdownPreferences(const MarkdownPreferences &preferences) { if(!preview.initialized()) return; + const auto scale=textAreaScale(search.style,AppearanceArea::markdown); preview.post(wide(nlohmann::json{{"action","appearance"},{"width",preferences.width}, - {"fontSize",preferences.fontSize},{"font",utf8(preferences.font)}}.dump())); + {"fontSize",preferences.fontSize*scale/100.0},{"font",utf8(preferences.font)}}.dump())); } void TextWindow::refreshPreview() @@ -2992,7 +3043,7 @@ void TextWindow::command(UINT id) case lexerAuto: language = automatic; installLexer(); return; case lexerPlain: language = {}; installLexer(); return; case options: - search.style.options(window, edit); + search.style.options(window,previewWanted?AppearanceArea::markdown:edit?AppearanceArea::editor:AppearanceArea::viewer); SetFocus(editor); return; default: @@ -3125,7 +3176,7 @@ LRESULT CALLBACK TextWindow::procedure(HWND window, UINT message, WPARAM wparam, const auto self=found->second; try { - if (message == preferencesChanged) + if(message==preferencesChanged || windowsAppThemeChanged(message,lparam)) { self->reloadPreferences(); return 0; @@ -3511,10 +3562,10 @@ void previewQuickViewText(HWND window,const std::wstring &title,std::string_view preview->second->previewEmbeddedText(title,contents,diff); } -ImageViewStyle imageViewStyle(TextDialogs dialogs) +ImageViewStyle imageViewStyle(TextDialogs dialogs,bool edit=false) { - const auto font=dialogs.readFont(); - const auto colors=loadTextPreferences().profiles[0].colors; + const auto font=scaledDocumentFont(dialogs,edit); + const auto colors=resolvedTextProfile(loadTextPreferences(),edit).colors; return {font.font,font.tenthsOfPoint,colors[0],colors[1],colors[2],colors[3],colors[4]}; } @@ -3560,7 +3611,7 @@ void openImageWindow(HWND owner,std::vector images,const } } if(!textWindows.contains(owner)) filesOwner=owner; - const auto window=createImageView(owner,false,imageViewStyle(dialogs),std::move(images),path,std::move(load), + const auto window=createImageView(owner,false,imageViewStyle(dialogs,editor!=nullptr),std::move(images),path,std::move(load), [](HWND closed) { std::erase(textWindowOrder,closed); quitWhenFilesWindowsClose(); diff --git a/src/files_text_window.h b/src/files_text_window.h index 37ef170..20c33f8 100644 --- a/src/files_text_window.h +++ b/src/files_text_window.h @@ -1,6 +1,7 @@ #pragma once #include +#include "files_appearance.h" #include #include #include @@ -48,7 +49,7 @@ struct TextDialogs INT_PTR (*paint)(HWND, UINT, WPARAM, LPARAM, const wchar_t *); INT_PTR (*paintSearch)(HWND, UINT, WPARAM, LPARAM); void (*prepare)(HWND); - void (*options)(HWND, bool); + void (*options)(HWND, AppearanceArea); void (*message)(HWND, const wchar_t *); TextWindowFont (*readFont)(); FarDropDownPalette (*dropDownPalette)(); @@ -58,6 +59,7 @@ struct TextDialogs bool (*confirmExisting)(HWND); bool (*saveOptions)(HWND,std::filesystem::path &,TextSaveFormat &); bool (*reloadChanged)(HWND){}; + unsigned (*readScale)(AppearanceArea){}; }; struct TextOpenOptions From f4dcd0efd93a3f9472eb7c14c81f18bcf9f596f9 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 23:29:30 +0200 Subject: [PATCH 47/61] Add contextual offline help to Files Refs #131 --- FILES-UI.md | 1 + resources/files.rc | 13 ++ src/files_dialog_input.inl | 19 ++- src/files_help.h | 13 ++ src/files_help.inl | 276 +++++++++++++++++++++++++++++++++++++ src/files_key_schemes.inl | 2 + src/files_main.cpp | 16 ++- src/files_text_window.cpp | 19 ++- src/files_text_window.h | 1 + 9 files changed, 352 insertions(+), 8 deletions(-) create mode 100644 src/files_help.h create mode 100644 src/files_help.inl diff --git a/FILES-UI.md b/FILES-UI.md index 15b5716..4032daf 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -741,6 +741,7 @@ Warning і початковий фокус на No. - При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання. - Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку. +- F1 відкриває вбудовану офлайн-довідку для панелі, вибраного пункту меню чи поточного діалогу. Пошук фільтрує теми за назвою й текстом. Esc закриває довідку та повертає фокус. У командному рядку з назвою команди F1 зберігає перехід до її довідки Windows. Загальна довідка також доступна через Commands → Help. - Options → Import JSON / Export JSON переносить вибрані групи збережених параметрів Files. Окремо доступні кольори панелей і порівняння разом зі стилями файлів, режими й компонування панелей та іменовані схеми клавіш. Перед заміною відмінних схем з однаковою назвою Files запитує підтвердження. Імпорт спочатку оновлює чернетку Options. Apply або OK зберігає зміни, Cancel відкидає їх. Формат містить лише ці параметри. Невідомі поля і групи пропускаються. - Commands → Keyboard shortcuts відкриває іменовані схеми для команд файлових панелей та історії команд. У схемі можна задати кілька клавіш, вибрати основну, вилучити прив’язку, скопіювати схему під новим іменем, перемкнути чи скинути її. OK зберігає активну схему. Меню показує всі прив’язки, нижній ряд і текстові підказки відображають основну. Діалог відхиляє дублікати в контекстах, що перетинаються, і клавіші, зайняті навігацією. Попередні прив’язки історії та порівняння завантажуються як схема Previous settings. - Масштаб панелей, текстового Viewer, Editor, Markdown, термінала й порівняння зберігається окремо. У Commands є Panel appearance або Terminal appearance залежно від видимої області. Options у Viewer, Editor та Markdown і кнопка Appearance у порівнянні відкривають відповідну сторінку. Значення 100% використовує обраний базовий розмір шрифту. diff --git a/resources/files.rc b/resources/files.rc index c17a4db..0445bd6 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -201,6 +201,19 @@ BEGIN PUSHBUTTON "Cancel", IDCANCEL, 179, 99, 52, 15 END +618 DIALOGEX 0, 0, 468, 242 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "KSwitcher Files Help" +FONT 9, "Segoe UI" +BEGIN + LTEXT "&Search help", -1, 9, 9, 112, 11 + EDITTEXT 670, 9, 23, 145, 15, ES_AUTOHSCROLL + LISTBOX 671, 9, 45, 145, 160, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP + LTEXT "", 672, 165, 23, 294, 15 + EDITTEXT 673, 165, 45, 294, 160, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | ES_WANTRETURN | WS_VSCROLL + DEFPUSHBUTTON "&Close", IDOK, 403, 216, 56, 16 +END + 101 DIALOGEX 0, 0, 397, 310 STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN CAPTION "KSwitcher Files Options" diff --git a/src/files_dialog_input.inl b/src/files_dialog_input.inl index a39deee..13b63d5 100644 --- a/src/files_dialog_input.inl +++ b/src/files_dialog_input.inl @@ -1,3 +1,5 @@ +bool handleFilesHelpMessage(const MSG &message); + HWND activeFilesDialog{}; HHOOK filesDialogMouseHook{}; @@ -53,9 +55,10 @@ class FilesModalDialog { public: FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument, - bool watchOutsideClicks=true) + bool watchOutsideClicks=true,bool fitToOwner=true) : owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument), - watchOutsideClicks_(watchOutsideClicks) + resource_(IS_INTRESOURCE(resource)?static_cast(reinterpret_cast(resource)):0), + watchOutsideClicks_(watchOutsideClicks),fitToOwner_(fitToOwner) { window_=CreateDialogParamW(instance,resource,owner,dispatchDialog,reinterpret_cast(this)); } @@ -66,6 +69,12 @@ public: HWND window() const { return window_; } + static unsigned resourceFor(HWND window) + { + const auto *state=reinterpret_cast(GetPropW(window,stateProperty_)); + return state?state->resource_:0; + } + static HWND activeFor(HWND owner) { const auto root=GetAncestor(owner,GA_ROOTOWNER); @@ -111,7 +120,7 @@ public: activeFilesDialog=window_; entered_=true; refreshMouseHook(); - if(GetWindowRect(owner_,&ownerBounds_)) + if(fitToOwner_ && GetWindowRect(owner_,&ownerBounds_)) { if(!layout_) captureLayout(); SetWindowSubclass(owner_,trackOwner,reinterpret_cast(this),reinterpret_cast(this)); @@ -146,6 +155,7 @@ public: { if(message.hwnd==dialog || IsChild(dialog,message.hwnd)) { + if(handleFilesHelpMessage(message)) return true; if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE) { SendMessageW(dialog,WM_COMMAND,IDCANCEL,0); @@ -209,7 +219,8 @@ private: DLGPROC procedure_; LPARAM argument_; INT_PTR result_=IDCANCEL; - bool entered_{},finished_{},watchOutsideClicks_; + unsigned resource_{}; + bool entered_{},finished_{},watchOutsideClicks_,fitToOwner_; static void refreshMouseHook() { diff --git a/src/files_help.h b/src/files_help.h new file mode 100644 index 0000000..6aef6a6 --- /dev/null +++ b/src/files_help.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +namespace ks::files +{ +inline constexpr UINT filesHelpRequest=WM_APP+273; +enum class FilesHelpTopic +{ + panels, menus, navigation, find, transfer, deleteFiles, archive, space, properties, connections, + terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, count +}; +} diff --git a/src/files_help.inl b/src/files_help.inl new file mode 100644 index 0000000..257c1be --- /dev/null +++ b/src/files_help.inl @@ -0,0 +1,276 @@ +using ks::files::FilesHelpTopic; + +constexpr struct +{ + const wchar_t *title,*keywords,*body; +} filesHelpTopics[]{ + {L"File panels",L"commander left right selection tabs keyboard refresh", + L"Use Tab to switch panes. Enter opens the selected folder or file. Insert marks an item and advances to the next row. The selection summary counts marked items.\r\n\r\n" + L"The command bar shows the primary keys for common actions. The Left and Right menus switch modes, choose drives, sort items, and filter a pane."}, + {L"Menus and shortcuts",L"f9 access keys commands actions configuration", + L"Press F9 to show the menu bar. Use the arrow keys to move between categories and entries. Press Enter to run the highlighted command.\r\n\r\n" + L"Press F1 on a menu item for its topic. Commands → Keyboard shortcuts lists the active scheme and lets you assign extra bindings."}, + {L"Locations and navigation",L"folder path history breadcrumbs drives recent bookmark directory unc", + L"Use the breadcrumb in a local or remote pane to jump to an ancestor. The folder history keeps earlier locations for that pane. Recent folders are available from the drive picker.\r\n\r\n" + L"Folder shortcuts open frequently used locations. In the default scheme Ctrl+0–9 recalls a digit and Ctrl+Shift+0–9 adds the current folder."}, + {L"Find files",L"search filter mask results alt f7 paths subfolders", + L"Find files searches from the active folder, including subfolders. Supply a filename mask such as *.md. The results show their locations and can be opened or used in file operations.\r\n\r\n" + L"Enter visits a result's folder. Esc stops an active search or returns from the results. Use Quick View for a preview of a local result."}, + {L"Copy, move and rename",L"transfer destination mask overwrite permissions timestamps clipboard queue", + L"Copy and Move use the selection in the active pane. The destination starts with the other pane. Check the destination and the conflict policy before starting the operation.\r\n\r\n" + L"Copy/Move options can limit the selection by mask, target several folders, and preserve timestamps or supported permissions. The progress dialog shows the active file and an estimate when enough data has transferred."}, + {L"Delete and Recycle Bin",L"permanent remove recovery confirmation shift delete", + L"Delete respects the selected items and shows a confirmation. Local files are sent to the Recycle Bin when supported. Check the notice for remote locations or permanent deletion.\r\n\r\n" + L"Shift+Delete requests permanent deletion. Cancel the confirmation to keep the selection without deleting it."}, + {L"Archives",L"zip 7z pack extract compression update", + L"Open a ZIP or 7z archive from a local pane to browse its entries. Copy entries out to extract them. Back out through the parent entry or Esc.\r\n\r\n" + L"Use Pack files to create or update a ZIP or 7z archive. Review the destination, compression and conflict choices before saving."}, + {L"Space Analyzer",L"storage folder size allocation disk tree treemap sunburst", + L"Open Space Analyzer from Commands for a local folder. The tree and charts show which folders consume space. Select an item to inspect its contribution and choose the display you need.\r\n\r\n" + L"Logical size describes file data. Allocated size describes disk allocation where it can be measured."}, + {L"Properties and locking processes",L"context menu windows owner attributes filesystem locks handle", + L"Properties shows available file details and Windows attributes. The Windows context menu exposes actions supplied by the file type and the operating system.\r\n\r\n" + L"Use Locking processes for selected local items to see processes with open handles. Save any work in the owning program before closing it."}, + {L"Network connections",L"ftp sftp smb lan ssh host authentication credentials password remote", + L"The drive picker opens FTP, SFTP and SMB connection profiles, as well as paired LAN computers. Create a profile with its protocol, host and starting folder.\r\n\r\n" + L"Check the remote server identity when connecting. If a listing is interrupted, use the Refresh command shown in the pane's status line to retry."}, + {L"Command line and terminal",L"powershell ssh console history windows command f1", + L"Type a PowerShell command and press Enter to run it in the active pane's context. Ctrl+O switches between the file panes and terminal output. Previous command and Command history use the active keyboard scheme.\r\n\r\n" + L"With a command name at the caret, F1 can open its Windows command reference. With an empty command line F1 opens the Files guide."}, + {L"Text Viewer and Quick View",L"preview read file html hex bookmark go to search", + L"View opens a separate window. Quick View previews the local selection alongside its pane. View as hex displays binary data. A local Viewer refreshes when its file is changed externally.\r\n\r\n" + L"Use the Viewer menus for Find, page navigation and bookmarks. Options opens the Viewer appearance page."}, + {L"Text Editor",L"edit save encoding f2 f4 f6 external changes buffers", + L"Edit opens a text file for changes. The Editor menu provides Save, Find, undo and encoding controls. Switching to Viewer keeps a pending Editor buffer for the open document.\r\n\r\n" + L"When the disk version changes, choose Reload or Keep buffer. Saving checks the disk version again and reports a conflict if the file has changed."}, + {L"Markdown preview",L"markdown rendered source local links images search", + L"Open a Markdown file in Viewer to read the rendered document. Use its navigation controls for local links and its search form to find rendered text. Switch back to source for editing.\r\n\r\n" + L"Options opens the Markdown page for width, font and scale. Markdown's scale is separate from the text Viewer and Editor."}, + {L"Image Viewer and Editor",L"png jpeg image zoom rotate crop undo save copy", + L"View opens supported images with fit, zoom and navigation controls. Local PNG and JPEG files can be opened with Edit to rotate or crop them.\r\n\r\n" + L"Use Undo to reverse edits and Save Copy to create a new file. Replacing the original requires confirmation and checks for external changes."}, + {L"File comparison",L"diff unified changes left right hunk apply undo whitespace", + L"Select the two files and choose Compare files. Previous and Next jump between change blocks. Unified changes the view, and Fold unchanged collapses matching context.\r\n\r\n" + L"Apply to left or right changes that side's draft. Use Undo or save the selected side when ready. Appearance opens the comparison font, colors and scale."}, + {L"Git Changes",L"staged unstaged repository status commit branch diff", + L"Open Git Changes in a Git working tree to inspect changes, branches and history. Select an entry to review its diff.\r\n\r\n" + L"Stage the changes you want to include. Commit staged changes shows the items currently in the index before writing the commit."}, + {L"Environment Variables",L"user system process path edit windows variables", + L"Environment Variables lists user, system and process scopes. Choose a scope, then review the selected name and value before editing.\r\n\r\n" + L"Changes to the system scope require the appropriate Windows permission. Existing applications may need to reopen before using updated values."}, + {L"Files Options",L"preferences settings search apply reset cancel layout font", + L"Search settings by name or choose a section in the tree. Apply saves the draft and refreshes affected windows. Cancel discards the pending changes.\r\n\r\n" + L"Reset selected to defaults applies to the displayed section. Import JSON and Export JSON transfer supported settings groups between profiles."}, + {L"Keyboard schemes",L"keys shortcuts multiple primary named duplicate context conflict", + L"Use Commands → Keyboard shortcuts to switch or copy a named scheme. Select a command, enter a key and choose Add. Make primary controls which binding appears in the command bar.\r\n\r\n" + L"Keys already assigned in an overlapping context cannot be added to another command in that context. F1 opens this guide."}, + {L"Appearance and scale",L"theme light dark windows appearance font palette size", + L"Panels, Viewer, Editor, Markdown, terminal and comparison each have a saved scale. Use the visible area's Options or Appearance command to open its settings.\r\n\r\n" + L"Viewer and Editor can use System (Windows). Assign either a stock or named palette to each Windows mode under Appearance → System themes."}, + {L"Import and export settings",L"json portable backup restore transfer option groups", + L"Select the saved settings groups to include in an export. The supported groups cover colors and file styles, panel layout and keyboard schemes.\r\n\r\n" + L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."} +}; +static_assert(std::size(filesHelpTopics)==static_cast(FilesHelpTopic::count)); + +constexpr int helpSearch=670,helpTopics=671,helpTitle=672,helpBody=673; + +void displayFilesHelpTopic(HWND dialog,int topic) +{ + if(topic<0) + { + SetDlgItemTextW(dialog,helpTitle,L"No matching help topics"); + SetDlgItemTextW(dialog,helpBody,L""); + return; + } + const auto &entry=filesHelpTopics[topic]; + SetDlgItemTextW(dialog,helpTitle,entry.title); + SetDlgItemTextW(dialog,helpBody,entry.body); + SendDlgItemMessageW(dialog,helpBody,EM_SETSEL,0,0); + SendDlgItemMessageW(dialog,helpBody,EM_SCROLLCARET,0,0); +} + +void filterFilesHelpTopics(HWND dialog,int previous) +{ + wchar_t buffer[129]{}; + GetDlgItemTextW(dialog,helpSearch,buffer,std::size(buffer)); + std::wistringstream query(ks::lower(buffer)); + std::vector tokens; + for(std::wstring term;query>>term;) tokens.push_back(std::move(term)); + const auto list=GetDlgItem(dialog,helpTopics); + SendMessageW(list,LB_RESETCONTENT,0,0); + int displayed=-1; + LRESULT selected=LB_ERR; + for(size_t i=0;i(topic.title)); + if(row<0) continue; + SendMessageW(list,LB_SETITEMDATA,row,i); + if(selected==LB_ERR || static_cast(i)==previous) + { + selected=row; + displayed=static_cast(i); + } + } + if(selected!=LB_ERR) SendMessageW(list,LB_SETCURSEL,selected,0); + displayFilesHelpTopic(dialog,displayed); +} + +int selectedFilesHelpTopic(HWND dialog) +{ + const auto row=SendDlgItemMessageW(dialog,helpTopics,LB_GETCURSEL,0,0); + return row==LB_ERR?-1:static_cast(SendDlgItemMessageW(dialog,helpTopics,LB_GETITEMDATA,row,0)); +} + +INT_PTR CALLBACK filesHelpDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + SendDlgItemMessageW(dialog,helpSearch,EM_SETLIMITTEXT,128,0); + filterFilesHelpTopics(dialog,static_cast(lp)); + SetFocus(GetDlgItem(dialog,helpSearch)); + return FALSE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL))) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND) return FALSE; + if(LOWORD(wp)==helpSearch && HIWORD(wp)==EN_CHANGE) + filterFilesHelpTopics(dialog,selectedFilesHelpTopic(dialog)); + if(LOWORD(wp)==helpTopics && HIWORD(wp)==LBN_SELCHANGE) + displayFilesHelpTopic(dialog,selectedFilesHelpTopic(dialog)); + return TRUE; +} + +void showFilesHelp(HWND owner,FilesHelpTopic topic) +{ + if(!owner || !IsWindow(owner) || FilesModalDialog::resourceFor(owner)==618) return; + FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(618),owner,filesHelpDialog, + static_cast(topic),false,false); + dialog.runModal(); +} + +FilesHelpTopic filesMenuHelpTopic() +{ + if(folderPicker) return FilesHelpTopic::navigation; + if(!commandPicker) return IsWindowVisible(picker)?FilesHelpTopic::connections:FilesHelpTopic::menus; + const auto row=SendMessageW(picker,LB_GETCURSEL,0,0); + if(!selectablePickerRow(row)) return FilesHelpTopic::menus; + const int action=commandActions[row]; + if(menuIndex==0 || menuIndex==4) return action==4?FilesHelpTopic::navigation:FilesHelpTopic::panels; + if(menuIndex==1) + { + if(action==4) return FilesHelpTopic::archive; + if(action==5 || action==6) return FilesHelpTopic::properties; + return action<=2?FilesHelpTopic::transfer:FilesHelpTopic::menus; + } + if(menuIndex!=2) return FilesHelpTopic::menus; + switch(action) + { + case 1: case 4: case 10: case 13: case 14: return FilesHelpTopic::viewer; + case 2: case 5: return FilesHelpTopic::editor; + case 3: case 11: return FilesHelpTopic::navigation; + case 6: case 7: return FilesHelpTopic::connections; + case 8: return FilesHelpTopic::comparison; + case 9: return FilesHelpTopic::find; + case 12: return FilesHelpTopic::space; + case 15: return FilesHelpTopic::properties; + case 16: return FilesHelpTopic::git; + case 17: return FilesHelpTopic::environment; + case 19: return FilesHelpTopic::terminal; + case 20: return FilesHelpTopic::keys; + case 21: return FilesHelpTopic::appearance; + default: return FilesHelpTopic::menus; + } +} + +std::optional filesHelpForWindow(HWND root,HWND target) +{ + const auto resource=FilesModalDialog::resourceFor(root); + switch(resource) + { + case 618: return {}; + case 101: + { + const auto control=GetDlgCtrlID(target); + if(control==optionsImport || control==optionsExport) return FilesHelpTopic::portability; + if(control==321 || control==comparisonKeySchemesButton) return FilesHelpTopic::keys; + if(const auto *option=reinterpret_cast(GetWindowLongPtrW(root,DWLP_USER))) + { + if(option->page==Appearance || control==areaScaleControl) return FilesHelpTopic::appearance; + if(option->page==TextViewer && option->section==markdownSection) return FilesHelpTopic::markdown; + if(option->page==PanelModes) return FilesHelpTopic::panels; + if(option->page==CommandLine) return FilesHelpTopic::terminal; + if(option->page==CompareFiles) return FilesHelpTopic::comparison; + } + return FilesHelpTopic::options; + } + case 102: case 103: case 104: case 105: case 108: case 113: case 129: return FilesHelpTopic::transfer; + case 106: case 107: return FilesHelpTopic::deleteFiles; + case 109: case 110: case 117: return FilesHelpTopic::navigation; + case 111: return FilesHelpTopic::terminal; + case 112: case 121: case 122: case 123: case 124: return FilesHelpTopic::connections; + case 114: case 115: return FilesHelpTopic::comparison; + case 116: return FilesHelpTopic::find; + case 118: return FilesHelpTopic::space; + case 119: return FilesHelpTopic::panels; + case 120: return FilesHelpTopic::archive; + case 125: case 609: return FilesHelpTopic::properties; + case 126: return FilesHelpTopic::git; + case 127: case 128: return FilesHelpTopic::environment; + case 130: return FilesHelpTopic::images; + case 602: case 613: case 614: return FilesHelpTopic::viewer; + case 603: case 611: case 612: return FilesHelpTopic::editor; + case 608: return FilesHelpTopic::appearance; + case 615: case 616: return FilesHelpTopic::keys; + case 617: return FilesHelpTopic::portability; + case 604: case 607: + if(const auto owner=GetWindow(root,GW_OWNER);owner && owner!=root) + return filesHelpForWindow(owner,owner); + break; + } + if(comparisonWindows.contains(root)) return FilesHelpTopic::comparison; + if(const auto area=ks::files::textWindowAppearanceArea(root)) + return *area==AppearanceArea::markdown?FilesHelpTopic::markdown: + *area==AppearanceArea::editor?FilesHelpTopic::editor:FilesHelpTopic::viewer; + wchar_t type[64]{}; + GetClassNameW(root,type,std::size(type)); + if(std::wstring_view(type)==L"KSwitcherFilesImageViewer") return FilesHelpTopic::images; + if(root!=GetParent(terminalInput)) return resource?std::optional(FilesHelpTopic::options):std::nullopt; + if(gitChangesView && (target==gitChangesView->host || IsChild(gitChangesView->host,target))) return FilesHelpTopic::git; + if(quickImageWindow && (target==quickImageWindow || IsChild(quickImageWindow,target))) return FilesHelpTopic::images; + if(quickViewWindow && (target==quickViewWindow || IsChild(quickViewWindow,target))) return FilesHelpTopic::viewer; + if(IsWindowVisible(menuBar) || IsWindowVisible(picker)) return filesMenuHelpTopic(); + if(terminalVisible || target==terminalOutput || IsChild(terminalOutput,target)) return FilesHelpTopic::terminal; + if(target==panels[0].path || target==panels[1].path) return FilesHelpTopic::navigation; + return panels[active].findOrigin?FilesHelpTopic::find:FilesHelpTopic::panels; +} + +bool handleFilesHelpMessage(const MSG &message) +{ + const bool posted=message.message==ks::files::filesHelpRequest; + if(!message.hwnd || (!posted && (message.message!=WM_KEYDOWN || message.wParam!=VK_F1 || + ((GetKeyState(VK_CONTROL)|GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)| + GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)))) return false; + const auto root=GetAncestor(message.hwnd,GA_ROOT); + auto target=message.hwnd; + if(root==target) + if(const auto focus=GetFocus();focus && IsChild(root,focus)) target=focus; + if(FilesModalDialog::resourceFor(root)==618) return true; + const auto topic=posted && message.hwnd==GetParent(terminalInput)? + std::optional(FilesHelpTopic::terminal):filesHelpForWindow(root,target); + if(!topic) return false; + if(!posted) + { + if(message.lParam&(1LL<<30)) return true; + if(target==terminalInput && commandLineAvailable(root) && handleCompletionKey(VK_F1,message.lParam)) + return true; + } + showFilesHelp(root,*topic); + return true; +} diff --git a/src/files_key_schemes.inl b/src/files_key_schemes.inl index 5029bfb..55daef4 100644 --- a/src/files_key_schemes.inl +++ b/src/files_key_schemes.inl @@ -98,6 +98,7 @@ unsigned reservedFilesKeyContexts(WORD binding) if(key>=VK_F1 && key<=VK_F24) { if(mods==keyAlt && key==VK_F4) return terminalKeyContext; + if(!mods && key==VK_F1) return bothKeyContexts; if((!mods && key==VK_F9) || (mods==keyAlt && (key==VK_F1 || key==VK_F2 || key==VK_F10)) || (mods==keyShift && key==VK_F4) || (mods==keyShift && key==VK_F10) || (mods==keyCtrl && key<=VK_F12)) @@ -156,6 +157,7 @@ std::optional parseFilesKeySettings(const Json &stored) { if(!entry.is_number_unsigned() || entry>0xffff) return {}; const auto binding=entry.get(); + if(binding==chord(VK_F1)) continue; if(!filesKeyConflict(scheme,i,binding).empty()) return {}; scheme.keys[i].push_back(binding); } diff --git a/src/files_main.cpp b/src/files_main.cpp index 5368e4d..4c45980 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -49,6 +49,7 @@ #include "files_menu_navigation.h" #include "files_text_preferences.h" #include "files_appearance.h" +#include "files_help.h" #include "files_menu_paint.h" #include "files_dropdown_paint.h" #include "files_scrollbar.h" @@ -2429,6 +2430,11 @@ void handleTerminalPromptInput(HWND owner,std::wstring_view action) const auto key=std::find_if(std::begin(keys),std::end(keys), [action](const auto &binding){ return binding.first==action; }); if(key==std::end(keys) || handleCompletionKey(key->second,0)) return; + if(key->second==VK_F1) + { + PostMessageW(owner,ks::files::filesHelpRequest,0,0); + return; + } const auto character=key->second==VK_BACK || key->second==VK_ESCAPE; SendMessageW(terminalInput,character?WM_CHAR:WM_KEYDOWN,key->second,0); } @@ -3933,6 +3939,7 @@ void showProcesses(HWND owner,std::vector paths={}); bool gitChangesAvailable(const Panel &panel); void openGitChanges(HWND owner,const Panel &panel); void showEnvironmentPanel(HWND owner); +void showFilesHelp(HWND owner,ks::files::FilesHelpTopic topic); void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending=nullptr); void showCommandHistory(HWND owner); @@ -3989,6 +3996,7 @@ void selectDrive() else if(menuIndex==2 && row==19) showCommandHistory(owner); else if(menuIndex==2 && row==20) editFilesKeySchemes(owner,FilesKey::Refresh); else if(menuIndex==2 && row==21) editFilesAppearance(owner,terminalVisible?AppearanceArea::terminal:AppearanceArea::panels); + else if(menuIndex==2 && row==22) showFilesHelp(owner,terminalVisible?ks::files::FilesHelpTopic::terminal:ks::files::FilesHelpTopic::panels); else if(menuIndex==1 && row==4) createArchive(owner,panels[active]); else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]); else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]); @@ -8338,7 +8346,7 @@ void openMenu(HWND window, int index) filesKeyMenuLabel(FilesKey::FullPath),L"Space Analyzer",filesKeyMenuLabel(FilesKey::HexView), L"Viewer bookmarks…",L"Processes…",L"Git Changes…",L"Environment Variables…",filesKeyMenuLabel(FilesKey::Swap), filesKeyMenuLabel(FilesKey::History),L"Keyboard shortcuts…", - terminalVisible?L"Terminal appearance…":L"Panel appearance…"}; + terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1"}; } const auto &panel=panels[active]; const bool remoteResults=remoteSearchResults(panel); @@ -8385,7 +8393,7 @@ void openMenu(HWND window, int index) } if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10); if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7}); - commandActions.insert(commandActions.end(),{-1,19,20,21}); + commandActions.insert(commandActions.end(),{-1,19,20,21,22}); } else for(size_t i=0;i(i)); @@ -9452,6 +9460,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } return DefWindowProcW(window, message, wp, lp); } + +#include "files_help.inl" } int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) @@ -9523,7 +9533,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) { if(GetForegroundWindow()==window || IsChild(window,GetFocus())) restoreCommandFocus(); if(GetMessageW(&message,nullptr,0,0)<=0) break; - if(handleComparisonMessage(message)) continue; + if(handleFilesHelpMessage(message) || handleComparisonMessage(message)) continue; if(message.message==WM_KEYDOWN && message.wParam==VK_TAB && (GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_MENU)&0x8000) && ks::files::cycleTextWindows(GetAncestor(message.hwnd,GA_ROOT),(GetKeyState(VK_SHIFT)&0x8000)!=0)) diff --git a/src/files_text_window.cpp b/src/files_text_window.cpp index fab1850..920569a 100644 --- a/src/files_text_window.cpp +++ b/src/files_text_window.cpp @@ -1,4 +1,5 @@ #include "files_text_window.h" +#include "files_help.h" #include "files_image_view.h" #include "files_text_preferences.h" #include "files_menu_paint.h" @@ -857,6 +858,10 @@ public: bool openBookmark(const ViewerBookmark &bookmark); nlohmann::json sessionState() const; void restoreSession(const nlohmann::json &state); + AppearanceArea appearanceArea() const + { + return previewWanted?AppearanceArea::markdown:edit?AppearanceArea::editor:AppearanceArea::viewer; + } std::filesystem::path original; const std::string peerId; @@ -2266,6 +2271,11 @@ bool TextWindow::startPreviewBrowser() { const bool ctrl=(GetKeyState(VK_CONTROL)&0x8000)!=0; const bool alt=(GetKeyState(VK_MENU)&0x8000)!=0; + if(key==VK_F1 && !ctrl && !alt && !((GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) + { + PostMessageW(window,filesHelpRequest,0,0); + return true; + } if(embedded) { if(!ctrl && !alt && !(GetKeyState(VK_SHIFT)&0x8000) && key==VK_F6 && quickKind==QuickKind::html) @@ -3043,7 +3053,7 @@ void TextWindow::command(UINT id) case lexerAuto: language = automatic; installLexer(); return; case lexerPlain: language = {}; installLexer(); return; case options: - search.style.options(window,previewWanted?AppearanceArea::markdown:edit?AppearanceArea::editor:AppearanceArea::viewer); + search.style.options(window,appearanceArea()); SetFocus(editor); return; default: @@ -3556,6 +3566,13 @@ void previewQuickViewFile(HWND window,const std::filesystem::path &path) preview->second->previewFile(path); } +std::optional textWindowAppearanceArea(HWND window) +{ + const auto entry=textWindows.find(window); + if(entry==textWindows.end()) return {}; + return entry->second->appearanceArea(); +} + void previewQuickViewText(HWND window,const std::wstring &title,std::string_view contents,bool diff) { if(const auto preview=textWindows.find(window);preview!=textWindows.end()) diff --git a/src/files_text_window.h b/src/files_text_window.h index 20c33f8..e84bc74 100644 --- a/src/files_text_window.h +++ b/src/files_text_window.h @@ -130,4 +130,5 @@ void textWindowOwnerClosed(); void standaloneFilesWindowOpened(); void standaloneFilesWindowClosed(); bool cycleTextWindows(HWND current,bool reverse); +std::optional textWindowAppearanceArea(HWND window); } From e852fde4f46e230e20cfb527c7daaf53548ebeb8 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 23:35:15 +0200 Subject: [PATCH 48/61] Open recent Files diagnostics in a safe native viewer Refs #132 --- FILES-UI.md | 2 +- resources/files.rc | 14 ++++ src/files_help.h | 2 +- src/files_help.inl | 7 +- src/files_log_view.inl | 177 +++++++++++++++++++++++++++++++++++++++++ src/files_main.cpp | 8 +- src/platform.cpp | 35 ++++++++ src/platform.h | 1 + 8 files changed, 241 insertions(+), 5 deletions(-) create mode 100644 src/files_log_view.inl diff --git a/FILES-UI.md b/FILES-UI.md index 4032daf..6d5907e 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -635,7 +635,7 @@ Warning і початковий фокус на No. розміру, а список має однаковий внутрішній відступ зліва і справа. - Тайм-аут запиту дисків відображається як Connection timed out. Якщо ввімкнено Write log, Files записує помилки запитів пар і дисків в окремий - журнал `data/kswitcher-files.log`. Системні помилки містять код Windows. + журнал `data/kswitcher-files.log`. Системні помилки містять код Windows. Commands → Files log відкриває до 200 останніх записів поточного або попереднього журналу. Refresh оновлює список. Copy selected або Ctrl+C копіює дату й безпечний опис вибраного запису. Довільні текстові деталі приховано. - Застосовані налаштування Files одразу підхоплюють інші відкриті вікна. Apply зберігає поля, змінені в поточній чернетці. Якщо два вікна одночасно diff --git a/resources/files.rc b/resources/files.rc index 0445bd6..816e3fc 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -214,6 +214,20 @@ BEGIN DEFPUSHBUTTON "&Close", IDOK, 403, 216, 56, 16 END +619 DIALOGEX 0, 0, 435, 211 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Files log" +FONT 9, "Segoe UI" +BEGIN + LTEXT "&Log", -1, 9, 12, 40, 11 + COMBOBOX 680, 51, 9, 115, 70, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL + LTEXT "", 681, 9, 31, 415, 28 + LISTBOX 682, 9, 62, 417, 117, LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_HSCROLL | WS_TABSTOP + PUSHBUTTON "&Copy selected", 683, 9, 187, 90, 15 + PUSHBUTTON "&Refresh", 684, 107, 187, 66, 15 + DEFPUSHBUTTON "Close", IDOK, 370, 187, 56, 15 +END + 101 DIALOGEX 0, 0, 397, 310 STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN CAPTION "KSwitcher Files Options" diff --git a/src/files_help.h b/src/files_help.h index 6aef6a6..7884c19 100644 --- a/src/files_help.h +++ b/src/files_help.h @@ -8,6 +8,6 @@ inline constexpr UINT filesHelpRequest=WM_APP+273; enum class FilesHelpTopic { panels, menus, navigation, find, transfer, deleteFiles, archive, space, properties, connections, - terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, count + terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, log, count }; } diff --git a/src/files_help.inl b/src/files_help.inl index 257c1be..5f0ccff 100644 --- a/src/files_help.inl +++ b/src/files_help.inl @@ -69,7 +69,10 @@ constexpr struct L"Viewer and Editor can use System (Windows). Assign either a stock or named palette to each Windows mode under Appearance → System themes."}, {L"Import and export settings",L"json portable backup restore transfer option groups", L"Select the saved settings groups to include in an export. The supported groups cover colors and file styles, panel layout and keyboard schemes.\r\n\r\n" - L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."} + L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."}, + {L"Files log",L"diagnostic journal error logging rotate copy record", + L"Open Files log from Commands to see recent entries. Switch between the current and previous rotated log, or use Refresh to read newer entries.\r\n\r\n" + L"Select an entry to copy its timestamp and summary. The viewer shows only supported diagnostic details."} }; static_assert(std::size(filesHelpTopics)==static_cast(FilesHelpTopic::count)); @@ -185,6 +188,7 @@ FilesHelpTopic filesMenuHelpTopic() case 19: return FilesHelpTopic::terminal; case 20: return FilesHelpTopic::keys; case 21: return FilesHelpTopic::appearance; + case 23: return FilesHelpTopic::log; default: return FilesHelpTopic::menus; } } @@ -229,6 +233,7 @@ std::optional filesHelpForWindow(HWND root,HWND target) case 608: return FilesHelpTopic::appearance; case 615: case 616: return FilesHelpTopic::keys; case 617: return FilesHelpTopic::portability; + case 619: return FilesHelpTopic::log; case 604: case 607: if(const auto owner=GetWindow(root,GW_OWNER);owner && owner!=root) return filesHelpForWindow(owner,owner); diff --git a/src/files_log_view.inl b/src/files_log_view.inl new file mode 100644 index 0000000..0a053cc --- /dev/null +++ b/src/files_log_view.inl @@ -0,0 +1,177 @@ +constexpr int filesLogSource=680,filesLogStatus=681,filesLogEntries=682,filesLogCopy=683,filesLogRefresh=684; +constexpr size_t filesLogEntryLimit=200,filesLogReadLimit=256*1024; + +std::optional filesLogError(std::string_view message,std::string_view marker) +{ + const auto last=message.rfind(marker); + if(last==message.npos) return {}; + const auto value=message.substr(last+marker.size()); + unsigned error{}; + const auto parsed=std::from_chars(value.data(),value.data()+value.size(),error); + if(parsed.ec!=std::errc{} || parsed.ptr!=value.data()+value.size()) return {}; + return error; +} + +std::wstring safeFilesLogEntry(std::string_view line) +{ + if(line.ends_with('\r')) line.remove_suffix(1); + std::wstring stamp; + constexpr std::string_view format="0000-00-00 00:00:00 "; + if(line.size()>=format.size()) + { + bool valid=true; + for(size_t i=0;i='0' && line[i]<='9'):line[i]==format[i]; + if(valid) + { + stamp=ks::wide(std::string(line.substr(0,format.size()-1)))+L" · "; + line.remove_prefix(format.size()); + } + } + + // Only fixed descriptions and numeric Windows result codes cross into the UI or clipboard. + std::wstring text; + std::optional error; + if(line=="LAN Files peer lookup failed: local KSwitcher window not found") + text=L"LAN peer lookup failed. KSwitcher is unavailable."; + else if(line.starts_with("LAN Files peer lookup failed: delivered=")) + { + text=L"LAN peer lookup failed"; + error=filesLogError(line,", Windows error="); + } + else if(line=="LAN Files drive query failed: unexpected error") + text=L"LAN drive query failed. Unexpected error."; + else if(line.starts_with("LAN Files drive query for ")) + { + text=L"LAN drive query failed"; + error=filesLogError(line,") failed: Windows error "); + if(error==WSAETIMEDOUT) text=L"LAN drive query timed out"; + } + else text=L"Diagnostic entry · details hidden"; + if(error && *error) text+=L" (Windows error "+std::to_wstring(*error)+L")"; + return stamp+text; +} + +std::vector recentFilesLogEntries(const ks::Bytes &bytes) +{ + std::vector entries; + if(bytes.empty()) return entries; + const std::string_view text(reinterpret_cast(bytes.data()),bytes.size()); + auto end=text.size(); + while(end && entries.size() entries; +}; + +void refreshFilesLog(HWND dialog,FilesLogDraft &draft) +{ + const bool previous=SendDlgItemMessageW(dialog,filesLogSource,CB_GETCURSEL,0,0)==1; + const auto list=GetDlgItem(dialog,filesLogEntries); + SendMessageW(list,LB_RESETCONTENT,0,0); + SendMessageW(list,LB_SETHORIZONTALEXTENT,0,0); + draft.entries.clear(); + try + { + if(const auto data=ks::readActiveLogTail(previous,filesLogReadLimit)) + { + draft.entries=recentFilesLogEntries(*data); + SetDlgItemTextW(dialog,filesLogStatus,draft.entries.empty()?L"The Files log has no entries.": + L"Most recent first. Select an entry to copy its timestamp and description."); + } + else SetDlgItemTextW(dialog,filesLogStatus,previous?L"No previous Files log is available yet.": + L"No Files log yet. Entries appear when Write log is enabled and Files records a problem."); + } + catch(const std::exception &) + { + SetDlgItemTextW(dialog,filesLogStatus,L"Could not read the Files log. Use Refresh to try again."); + } + int width=0; + const auto dc=GetDC(list); + const auto font=reinterpret_cast(SendMessageW(list,WM_GETFONT,0,0)); + const auto oldFont=dc && font?SelectObject(dc,font):nullptr; + for(const auto &entry:draft.entries) + { + SendMessageW(list,LB_ADDSTRING,0,reinterpret_cast(entry.c_str())); + if(dc) + { + SIZE extent{}; + GetTextExtentPoint32W(dc,entry.c_str(),static_cast(entry.size()),&extent); + width=std::max(width,static_cast(extent.cx)+12); + } + } + if(oldFont) SelectObject(dc,oldFont); + if(dc) ReleaseDC(list,dc); + if(width) SendMessageW(list,LB_SETHORIZONTALEXTENT,width,0); + if(!draft.entries.empty()) SendMessageW(list,LB_SETCURSEL,0,0); + EnableWindow(GetDlgItem(dialog,filesLogCopy),!draft.entries.empty()); +} + +LRESULT CALLBACK filesLogListKeys(HWND list,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + if(message==WM_KEYDOWN && wp=='C' && (GetKeyState(VK_CONTROL)&0x8000) && + !((GetKeyState(VK_MENU)|GetKeyState(VK_SHIFT)|GetKeyState(VK_LWIN)|GetKeyState(VK_RWIN))&0x8000)) + { + if(!(lp&(1LL<<30))) SendMessageW(GetParent(list),WM_COMMAND,MAKEWPARAM(filesLogCopy,BN_CLICKED),0); + return 0; + } + return DefSubclassProc(list,message,wp,lp); +} + +INT_PTR CALLBACK filesLogDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + auto &draft=*reinterpret_cast(lp); + SetWindowLongPtrW(dialog,DWLP_USER,lp); + for(const auto name:{L"Current",L"Previous"}) + SendDlgItemMessageW(dialog,filesLogSource,CB_ADDSTRING,0,reinterpret_cast(name)); + SendDlgItemMessageW(dialog,filesLogSource,CB_SETCURSEL,0,0); + SetWindowSubclass(GetDlgItem(dialog,filesLogEntries),filesLogListKeys,1,0); + refreshFilesLog(dialog,draft); + return TRUE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL))) + { + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND) return FALSE; + auto &draft=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); + if(LOWORD(wp)==filesLogRefresh || (LOWORD(wp)==filesLogSource && HIWORD(wp)==CBN_SELCHANGE)) + { + refreshFilesLog(dialog,draft); + return TRUE; + } + if(LOWORD(wp)==filesLogCopy) + { + const auto row=SendDlgItemMessageW(dialog,filesLogEntries,LB_GETCURSEL,0,0); + if(row>=0 && static_cast(row)(&draft),false,false); + dialog.runModal(); +} diff --git a/src/files_main.cpp b/src/files_main.cpp index 4c45980..4d24f1f 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -3940,6 +3941,7 @@ bool gitChangesAvailable(const Panel &panel); void openGitChanges(HWND owner,const Panel &panel); void showEnvironmentPanel(HWND owner); void showFilesHelp(HWND owner,ks::files::FilesHelpTopic topic); +void showFilesLog(HWND owner); void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending=nullptr); void showCommandHistory(HWND owner); @@ -3997,6 +3999,7 @@ void selectDrive() else if(menuIndex==2 && row==20) editFilesKeySchemes(owner,FilesKey::Refresh); else if(menuIndex==2 && row==21) editFilesAppearance(owner,terminalVisible?AppearanceArea::terminal:AppearanceArea::panels); else if(menuIndex==2 && row==22) showFilesHelp(owner,terminalVisible?ks::files::FilesHelpTopic::terminal:ks::files::FilesHelpTopic::panels); + else if(menuIndex==2 && row==23) showFilesLog(owner); else if(menuIndex==1 && row==4) createArchive(owner,panels[active]); else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]); else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]); @@ -8346,7 +8349,7 @@ void openMenu(HWND window, int index) filesKeyMenuLabel(FilesKey::FullPath),L"Space Analyzer",filesKeyMenuLabel(FilesKey::HexView), L"Viewer bookmarks…",L"Processes…",L"Git Changes…",L"Environment Variables…",filesKeyMenuLabel(FilesKey::Swap), filesKeyMenuLabel(FilesKey::History),L"Keyboard shortcuts…", - terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1"}; + terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1",L"Files log…"}; } const auto &panel=panels[active]; const bool remoteResults=remoteSearchResults(panel); @@ -8393,7 +8396,7 @@ void openMenu(HWND window, int index) } if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10); if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7}); - commandActions.insert(commandActions.end(),{-1,19,20,21,22}); + commandActions.insert(commandActions.end(),{-1,19,20,21,23,22}); } else for(size_t i=0;i(i)); @@ -9461,6 +9464,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) return DefWindowProcW(window, message, wp, lp); } +#include "files_log_view.inl" #include "files_help.inl" } diff --git a/src/platform.cpp b/src/platform.cpp index fd9f044..7e01680 100644 --- a/src/platform.cpp +++ b/src/platform.cpp @@ -899,6 +899,41 @@ void setLoggingEnabled(bool enabled) if (!enabled) diagnosticBuffer.clear(); } +std::optional readActiveLogTail(bool previous,size_t byteLimit) +{ + std::lock_guard lock(logGate); + auto path=logDirectory()/logFilename; + if(previous) path+=L".1"; + const auto raw=CreateFileW(path.c_str(),GENERIC_READ,FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE, + nullptr,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,nullptr); + if(raw==INVALID_HANDLE_VALUE) + { + const auto error=GetLastError(); + if(error==ERROR_FILE_NOT_FOUND || error==ERROR_PATH_NOT_FOUND) return {}; + throw std::runtime_error("Cannot open the diagnostic log"); + } + const std::unique_ptr file(raw,CloseHandle); + LARGE_INTEGER size{}; + if(!GetFileSizeEx(raw,&size) || size.QuadPart<0) throw std::runtime_error("Cannot measure the diagnostic log"); + const auto limit=std::min(byteLimit,2*1024*1024); + if(!limit || !size.QuadPart) return Bytes{}; + const auto offset=std::max(0,size.QuadPart-static_cast(limit)); + LARGE_INTEGER position{}; + position.QuadPart=offset?offset-1:0; + if(!SetFilePointerEx(raw,position,nullptr,FILE_BEGIN)) throw std::runtime_error("Cannot seek in the diagnostic log"); + Bytes contents(static_cast(size.QuadPart-position.QuadPart)); + DWORD read{}; + if(!ReadFile(raw,contents.data(),static_cast(contents.size()),&read,nullptr)) + throw std::runtime_error("Cannot read the diagnostic log"); + contents.resize(read); + if(offset && !contents.empty()) + { + const auto newline=std::find(contents.begin(),contents.end(),'\n'); + contents.erase(contents.begin(),newline==contents.end()?newline:std::next(newline)); + } + return contents; +} + std::wstring readDiagnosticLog(bool previous) { std::lock_guard lock(logGate); diff --git a/src/platform.h b/src/platform.h index 7e0b1e4..7060e7f 100644 --- a/src/platform.h +++ b/src/platform.h @@ -107,5 +107,6 @@ void expireDiagnostics(ULONGLONG now); void diagnosticEvent(const std::wstring &message, bool problem = false); void diagnosticOperation(const std::string &json); std::wstring readDiagnosticLog(bool previous); +std::optional readActiveLogTail(bool previous,size_t byteLimit); void clearDiagnosticLog(bool previous); } // namespace ks From e8bef944749fec300ba0bc6902737b2ced4d7455 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 23:46:44 +0200 Subject: [PATCH 49/61] Serve opt-in read-only Files MCP on loopback Refs #134 --- CMakeLists.txt | 13 +- FILES-UI.md | 2 + resources/files.rc | 17 ++ src/files_help.h | 2 +- src/files_help.inl | 7 +- src/files_main.cpp | 13 +- src/files_mcp.cpp | 384 +++++++++++++++++++++++++++++++++++++++++++ src/files_mcp.h | 33 ++++ src/files_mcp_ui.inl | 223 +++++++++++++++++++++++++ tests/files_mcp.cpp | 144 ++++++++++++++++ 10 files changed, 833 insertions(+), 5 deletions(-) create mode 100644 src/files_mcp.cpp create mode 100644 src/files_mcp.h create mode 100644 src/files_mcp_ui.inl create mode 100644 tests/files_mcp.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e71276..9a2d967 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -6,7 +6,8 @@ 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 src/files_archive.cpp src/files_git_changes.cpp resources/files.rc) + src/files_text_document.cpp src/files_text_language.cpp src/files_archive.cpp src/files_git_changes.cpp + src/files_mcp.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" @@ -185,6 +186,16 @@ if(NOT MSVC) target_link_options(KSwitcherFilesModalTests PRIVATE -static) endif() add_test(NAME files-modal-dialog COMMAND KSwitcherFilesModalTests) +add_executable(KSwitcherFilesMcpTests tests/files_mcp.cpp src/files_mcp.cpp) +target_include_directories(KSwitcherFilesMcpTests PRIVATE src) +target_link_libraries(KSwitcherFilesMcpTests PRIVATE kscore) +if(MSVC) + set_property(TARGET KSwitcherFilesMcpTests PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +else() + target_link_options(KSwitcherFilesMcpTests PRIVATE -static) +endif() +add_test(NAME files-mcp COMMAND KSwitcherFilesMcpTests) +set_tests_properties(files-mcp PROPERTIES TIMEOUT 30) add_executable(KSwitcherLanTests tests/lan.cpp) target_link_libraries(KSwitcherLanTests PRIVATE kscore) if(MSVC) diff --git a/FILES-UI.md b/FILES-UI.md index 6d5907e..65c31b9 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -741,6 +741,8 @@ Warning і початковий фокус на No. - При перенесенні вікна між моніторами з різним DPI оновлюй шрифт, висоту рядків панелей і компонування відкритого прогресу копіювання. Перевір перенесення під час активного копіювання. - Для власних діалогів і списків Far використовуй спільні метрики та малювання подвійної рамки. Еталон Delete задає 8 px від краю тла до першої лінії та 14 px від внутрішньої лінії до бічної межі вмісту при 96 DPI. Обидва відступи масштабуються за DPI. Вертикальний відступ враховує висоту заголовка та нижніх підказок. Діалоги й списки зберігають свою палітру та поведінку. +- Commands → Files MCP за замовчуванням зупинений. Start запускає MCP Streamable HTTP на `127.0.0.1` з випадковим портом. Клієнту потрібні Endpoint і `Authorization: Bearer `. Show token показує токен, Copy token копіює його. Stop і вихід із програми Files відкликають токен. Закриття діалогу залишає сервер активним, і меню показує Files MCP (running). Кожен старт створює новий токен. +- MCP має три інструменти для читання. `get_panels` повертає стан поточних локальних панелей, курсор і сторінку записів. `search_files` фільтрує назви або відносні шляхи поточного списку чи наявних результатів Find. `get_file_metadata` повертає кешовані атрибути, тип, розмір і час зміни для вже показаного елемента. Для продовження списку клієнт передає `nextOffset` як `offset`. Вміст файлів, віддалені панелі, архіви й операції запису не входять до цього API. Запити з браузерним Origin відхиляються. - F1 відкриває вбудовану офлайн-довідку для панелі, вибраного пункту меню чи поточного діалогу. Пошук фільтрує теми за назвою й текстом. Esc закриває довідку та повертає фокус. У командному рядку з назвою команди F1 зберігає перехід до її довідки Windows. Загальна довідка також доступна через Commands → Help. - Options → Import JSON / Export JSON переносить вибрані групи збережених параметрів Files. Окремо доступні кольори панелей і порівняння разом зі стилями файлів, режими й компонування панелей та іменовані схеми клавіш. Перед заміною відмінних схем з однаковою назвою Files запитує підтвердження. Імпорт спочатку оновлює чернетку Options. Apply або OK зберігає зміни, Cancel відкидає їх. Формат містить лише ці параметри. Невідомі поля і групи пропускаються. - Commands → Keyboard shortcuts відкриває іменовані схеми для команд файлових панелей та історії команд. У схемі можна задати кілька клавіш, вибрати основну, вилучити прив’язку, скопіювати схему під новим іменем, перемкнути чи скинути її. OK зберігає активну схему. Меню показує всі прив’язки, нижній ряд і текстові підказки відображають основну. Діалог відхиляє дублікати в контекстах, що перетинаються, і клавіші, зайняті навігацією. Попередні прив’язки історії та порівняння завантажуються як схема Previous settings. diff --git a/resources/files.rc b/resources/files.rc index 816e3fc..5af5a3e 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -228,6 +228,23 @@ BEGIN DEFPUSHBUTTON "Close", IDOK, 370, 187, 56, 15 END +620 DIALOGEX 0, 0, 395, 152 +STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU +CAPTION "Files MCP" +FONT 9, "Segoe UI" +BEGIN + LTEXT "", 690, 9, 9, 376, 12 + LTEXT "Read-only access to local panes, Find results and file metadata.", -1, 9, 26, 376, 13 + LTEXT "&Endpoint", -1, 9, 49, 72, 12 + EDITTEXT 691, 83, 46, 302, 15, ES_READONLY | ES_AUTOHSCROLL + LTEXT "Session &token", -1, 9, 72, 72, 12 + EDITTEXT 692, 83, 69, 302, 15, ES_READONLY | ES_AUTOHSCROLL + AUTOCHECKBOX "Sho&w token", 694, 83, 94, 81, 13 + PUSHBUTTON "&Copy token", 695, 169, 91, 72, 16 + PUSHBUTTON "&Start", 693, 9, 126, 64, 16 + DEFPUSHBUTTON "Close", IDOK, 329, 126, 56, 16 +END + 101 DIALOGEX 0, 0, 397, 310 STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_CLIPCHILDREN CAPTION "KSwitcher Files Options" diff --git a/src/files_help.h b/src/files_help.h index 7884c19..e7c748c 100644 --- a/src/files_help.h +++ b/src/files_help.h @@ -8,6 +8,6 @@ inline constexpr UINT filesHelpRequest=WM_APP+273; enum class FilesHelpTopic { panels, menus, navigation, find, transfer, deleteFiles, archive, space, properties, connections, - terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, log, count + terminal, viewer, editor, markdown, images, comparison, git, environment, options, keys, appearance, portability, log, mcp, count }; } diff --git a/src/files_help.inl b/src/files_help.inl index 5f0ccff..82439d6 100644 --- a/src/files_help.inl +++ b/src/files_help.inl @@ -72,7 +72,10 @@ constexpr struct L"Import stages chosen groups in Options. Files asks before replacing differing schemes with the same name. Apply saves the new values."}, {L"Files log",L"diagnostic journal error logging rotate copy record", L"Open Files log from Commands to see recent entries. Switch between the current and previous rotated log, or use Refresh to read newer entries.\r\n\r\n" - L"Select an entry to copy its timestamp and summary. The viewer shows only supported diagnostic details."} + L"Select an entry to copy its timestamp and summary. The viewer shows only supported diagnostic details."}, + {L"Files MCP",L"local loopback bearer authorization model context protocol read only search token", + L"Open Commands → Files MCP and select Start. Configure the client with the displayed loopback endpoint and use the session token as the bearer credential.\r\n\r\n" + L"The client can read current local panes, search their displayed entries and read cached file metadata. Stop revokes the session token."} }; static_assert(std::size(filesHelpTopics)==static_cast(FilesHelpTopic::count)); @@ -189,6 +192,7 @@ FilesHelpTopic filesMenuHelpTopic() case 20: return FilesHelpTopic::keys; case 21: return FilesHelpTopic::appearance; case 23: return FilesHelpTopic::log; + case 24: return FilesHelpTopic::mcp; default: return FilesHelpTopic::menus; } } @@ -234,6 +238,7 @@ std::optional filesHelpForWindow(HWND root,HWND target) case 615: case 616: return FilesHelpTopic::keys; case 617: return FilesHelpTopic::portability; case 619: return FilesHelpTopic::log; + case 620: return FilesHelpTopic::mcp; case 604: case 607: if(const auto owner=GetWindow(root,GW_OWNER);owner && owner!=root) return filesHelpForWindow(owner,owner); diff --git a/src/files_main.cpp b/src/files_main.cpp index 4d24f1f..8b91d91 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -51,6 +51,7 @@ #include "files_text_preferences.h" #include "files_appearance.h" #include "files_help.h" +#include "files_mcp.h" #include "files_menu_paint.h" #include "files_dropdown_paint.h" #include "files_scrollbar.h" @@ -3942,6 +3943,7 @@ void openGitChanges(HWND owner,const Panel &panel); void showEnvironmentPanel(HWND owner); void showFilesHelp(HWND owner,ks::files::FilesHelpTopic topic); void showFilesLog(HWND owner); +void showFilesMcp(HWND owner); void editFilesKeySchemes(HWND owner,FilesKey initial,FilesKeySettings *pending=nullptr); void showCommandHistory(HWND owner); @@ -4000,6 +4002,7 @@ void selectDrive() else if(menuIndex==2 && row==21) editFilesAppearance(owner,terminalVisible?AppearanceArea::terminal:AppearanceArea::panels); else if(menuIndex==2 && row==22) showFilesHelp(owner,terminalVisible?ks::files::FilesHelpTopic::terminal:ks::files::FilesHelpTopic::panels); else if(menuIndex==2 && row==23) showFilesLog(owner); + else if(menuIndex==2 && row==24) showFilesMcp(owner); else if(menuIndex==1 && row==4) createArchive(owner,panels[active]); else if(menuIndex==1 && row==5) showPanelItemProperties(owner,panels[active]); else if(menuIndex==1 && row==6) showPanelLockProcesses(owner,panels[active]); @@ -8292,6 +8295,7 @@ struct OptionsWriteLock #include "files_panel_columns_dialog.inl" #include "files_space_analyzer.inl" #include "files_environment.inl" +#include "files_mcp_ui.inl" void openMenu(HWND window, int index) { @@ -8349,7 +8353,8 @@ void openMenu(HWND window, int index) filesKeyMenuLabel(FilesKey::FullPath),L"Space Analyzer",filesKeyMenuLabel(FilesKey::HexView), L"Viewer bookmarks…",L"Processes…",L"Git Changes…",L"Environment Variables…",filesKeyMenuLabel(FilesKey::Swap), filesKeyMenuLabel(FilesKey::History),L"Keyboard shortcuts…", - terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1",L"Files log…"}; + terminalVisible?L"Terminal appearance…":L"Panel appearance…",L"Help…\tF1",L"Files log…", + filesMcp.port()?L"Files MCP (running)…":L"Files MCP…"}; } const auto &panel=panels[active]; const bool remoteResults=remoteSearchResults(panel); @@ -8396,7 +8401,7 @@ void openMenu(HWND window, int index) } if(quickViewWindow || (!panels[active].peer && !panels[active].ftp)) commandActions.push_back(10); if(panels[active].peer) commandActions.insert(commandActions.end(),{-1,6,7}); - commandActions.insert(commandActions.end(),{-1,19,20,21,23,22}); + commandActions.insert(commandActions.end(),{-1,19,20,21,23,24,22}); } else for(size_t i=0;i(i)); @@ -8628,6 +8633,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } switch (message) { + case ks::files::filesMcpQueryMessage: + filesMcp.answer(readFilesMcpTool); + return 0; case WM_SETFOCUS: restoreCommandFocus(); return 0; @@ -9436,6 +9444,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) DestroyWindow(window); return 0; case WM_DESTROY: + filesMcp.stop(); pendingPanelDrop.reset(); closeGitChanges(window,false); for(auto &panel:panels) diff --git a/src/files_mcp.cpp b/src/files_mcp.cpp new file mode 100644 index 0000000..d600d0a --- /dev/null +++ b/src/files_mcp.cpp @@ -0,0 +1,384 @@ +#include "lan_network.h" +#include "files_mcp.h" +#include "lan_pairing.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ks::files +{ +namespace +{ +using Json=FilesMcpServer::Json; +using Clock=std::chrono::steady_clock; +using namespace std::chrono_literals; +constexpr size_t maxHeaders=8192,maxRequest=16*1024,maxResponse=512*1024; +constexpr std::string_view latestProtocol="2025-11-25"; + +bool supportedProtocol(std::string_view version) +{ + return version==latestProtocol || version=="2025-06-18" || version=="2025-03-26"; +} + +bool readySocket(SOCKET socket,bool write,std::stop_token stop,Clock::time_point deadline) +{ + while(!stop.stop_requested() && Clock::now()0; + } + return false; +} + +bool appendSocket(SOCKET socket,std::string &data,std::stop_token stop,Clock::time_point deadline) +{ + char buffer[4096]; + if(!readySocket(socket,false,stop,deadline)) return false; + const auto count=recv(socket,buffer,sizeof(buffer),0); + if(count<=0) return false; + data.append(buffer,count); + return true; +} + +void sendSocket(SOCKET socket,std::string_view bytes,std::stop_token stop) +{ + const auto deadline=Clock::now()+2s; + while(!bytes.empty() && readySocket(socket,true,stop,deadline)) + { + const auto count=send(socket,bytes.data(),static_cast(bytes.size()),0); + if(count<=0) return; + bytes.remove_prefix(count); + } +} + +std::string lowerAscii(std::string_view text) +{ + std::string result(text); + for(auto &ch:result) + if(ch>='A' && ch<='Z') ch=static_cast(ch-'A'+'a'); + return result; +} + +std::string_view trimHeader(std::string_view text) +{ + const auto first=text.find_first_not_of(" \t"); + return first==text.npos?std::string_view{}:text.substr(first,text.find_last_not_of(" \t")-first+1); +} + +struct HttpRequest +{ + std::string_view method,path; + std::map> headers; + + std::string_view header(std::string_view field) const + { + const auto found=headers.find(field); + return found==headers.end()?std::string_view{}:found->second; + } +}; + +std::optional parseHeaders(std::string_view data) +{ + HttpRequest request; + auto end=data.find("\r\n"); + const auto line=data.substr(0,end); + const auto first=line.find(' '),second=first==line.npos?line.npos:line.find(' ',first+1); + if(end==data.npos || !first || second==line.npos || line.substr(second+1)!="HTTP/1.1") return {}; + request.method=line.substr(0,first); + request.path=line.substr(first+1,second-first-1); + data.remove_prefix(end+2); + while(!data.empty()) + { + end=data.find("\r\n"); + const auto header=data.substr(0,end); + const auto colon=header.find(':'); + if(!colon || colon==header.npos) return {}; + const auto name=lowerAscii(header.substr(0,colon)); + const auto value=trimHeader(header.substr(colon+1)); + if(!std::ranges::all_of(name,[](char ch) + {return (ch>='a' && ch<='z') || (ch>='0' && ch<='9') || ch=='-' || ch=='_';}) || + !std::ranges::all_of(value,[](unsigned char ch){return ch=='\t' || (ch>=32 && ch<127);}) || + !request.headers.emplace(name,value).second) + return {}; + if(end==data.npos) break; + data.remove_prefix(end+2); + } + return request; +} + +bool hasSessionToken(std::string_view authorization,std::string_view token) +{ + if(authorization.size()!=token.size()+7 || lowerAscii(authorization.substr(0,7))!="bearer ") return false; + unsigned difference=0; + for(size_t i=0;i(authorization[i+7]^token[i]); + return difference==0; +} + +struct HttpReply +{ + const char *status; + std::string body; + const char *headers=""; +}; + +HttpReply jsonReply(const char *status,Json body) +{ + return {status,body.dump(-1,' ',false,Json::error_handler_t::replace)}; +} + +HttpReply rpcError(const char *status,const Json &id,int code,const char *message) +{ + return jsonReply(status,{{"jsonrpc","2.0"},{"id",id},{"error",{{"code",code},{"message",message}}}}); +} + +const Json &mcpTools() +{ + static const auto tools=Json::parse(R"({"tools":[ + {"name":"get_panels","description":"Read the two Files panes and their current local listings, selections and Find state.", + "inputSchema":{"type":"object","properties":{"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"additionalProperties":false}, + "annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}}, + {"name":"search_files","description":"Search the current local listing or existing Find results by name or relative path.", + "inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"query":{"type":"string","minLength":1,"maxLength":128},"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":50}},"required":["query"],"additionalProperties":false}, + "annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}}, + {"name":"get_file_metadata","description":"Read cached metadata for a relative path already listed in a current local pane.", + "inputSchema":{"type":"object","properties":{"side":{"type":"string","enum":["active","left","right"]},"path":{"type":"string","minLength":1,"maxLength":2048}},"required":["path"],"additionalProperties":false}, + "annotations":{"readOnlyHint":true,"destructiveHint":false,"openWorldHint":false}} + ]})"); + return tools; +} + +Json toolResult(const Json &data,bool error=false) +{ + const auto text=error?data.get():data.dump(-1,' ',false,Json::error_handler_t::replace); + Json result{{"content",Json::array({{{"type","text"},{"text",text}}})},{"isError",error}}; + if(!error) result["structuredContent"]=data; + return result; +} + +template +HttpReply handleRpc(std::string_view body,const Read &read) +{ + Json message,id; + try + { + message=Json::parse(body,[](int depth,Json::parse_event_t,Json &) + { + if(depth>24) throw std::runtime_error("Request nesting limit"); + return true; + }); + } + catch(const std::exception &) {return rpcError("400 Bad Request",nullptr,-32700,"Invalid JSON");} + if(!message.is_object() || message.value("jsonrpc",Json())!="2.0" || + !message.contains("method") || !message["method"].is_string()) + return rpcError("400 Bad Request",nullptr,-32600,"Invalid request"); + const auto &method=message["method"].get_ref(); + if(!message.contains("id")) + { + if(method=="notifications/initialized" || method=="notifications/cancelled") return {"202 Accepted",{}}; + return rpcError("400 Bad Request",nullptr,-32600,"Unsupported notification"); + } + id=message["id"]; + if(!id.is_number_integer() && (!id.is_string() || id.get_ref().size()>256)) + return rpcError("400 Bad Request",nullptr,-32600,"Invalid request id"); + auto params=message.value("params",Json::object()); + if(!params.is_object()) return rpcError("200 OK",id,-32602,"Invalid parameters"); + Json result; + if(method=="initialize") + { + if(!params.contains("protocolVersion") || !params["protocolVersion"].is_string()) + return rpcError("200 OK",id,-32602,"Protocol version is required"); + const auto version=params["protocolVersion"].get(); + result={{"protocolVersion",supportedProtocol(version)?version:std::string(latestProtocol)}, + {"capabilities",{{"tools",Json::object()}}}, + {"serverInfo",{{"name","kswitcher-files"},{"version","1.0.0"}}}, + {"instructions","Inspect the current local listings and cached metadata. Search uses the Files panels' current results."}}; + } + else if(method=="ping") result=Json::object(); + else if(method=="tools/list") result=mcpTools(); + else if(method=="tools/call") + { + if(!params.contains("name") || !params["name"].is_string()) + return rpcError("200 OK",id,-32602,"Tool name is required"); + const auto &name=params["name"].get_ref(); + const auto args=params.value("arguments",Json::object()); + if(!args.is_object() || !std::ranges::any_of(mcpTools()["tools"],[&](const auto &tool) + {return tool["name"]==name;})) + return rpcError("200 OK",id,-32602,"Unknown tool or invalid arguments"); + auto data=read(name,args); + const auto failed=data.contains("error"); + result=failed?toolResult(data.at("error"),true):toolResult(data); + } + else return rpcError("200 OK",id,-32601,"Method not found"); + auto answer=jsonReply("200 OK",{{"jsonrpc","2.0"},{"id",id},{"result",std::move(result)}}); + return answer.body.size()<=maxResponse?std::move(answer):rpcError("200 OK",id,-32603,"Response is too large"); +} + +template +HttpReply handleHttp(SOCKET socket,unsigned port,std::string_view token,std::stop_token stop,const Read &read) +{ + std::string bytes; + const auto deadline=Clock::now()+2s; + size_t end{}; + while((end=bytes.find("\r\n\r\n"))==bytes.npos) + { + if(bytes.size()>=maxHeaders) return {"431 Request Header Fields Too Large",{}}; + if(!appendSocket(socket,bytes,stop,deadline)) return {"408 Request Timeout",{}}; + } + if(end+4>maxHeaders) return {"431 Request Header Fields Too Large",{}}; + // Header fields refer into bytes. Parse before appending any further data. + const auto request=parseHeaders(std::string_view(bytes).substr(0,end+2)); + if(!request) return {"400 Bad Request",{}}; + if(request->headers.contains("origin") || request->header("host")!="127.0.0.1:"+std::to_string(port)) + return {"403 Forbidden",{}}; + if(!hasSessionToken(request->header("authorization"),token)) + return {"401 Unauthorized",{},"WWW-Authenticate: Bearer\r\n"}; + if(request->path!="/mcp") return {"404 Not Found",{}}; + if(request->method!="POST") return {"405 Method Not Allowed",{},"Allow: POST\r\n"}; + if(request->headers.contains("transfer-encoding") || + (request->headers.contains("mcp-protocol-version") && !supportedProtocol(request->header("mcp-protocol-version")))) + return {"400 Bad Request",{}}; + const auto type=request->header("content-type"); + if(lowerAscii(trimHeader(type.substr(0,type.find(';'))))!="application/json") return {"415 Unsupported Media Type",{}}; + const auto length=request->header("content-length"); + size_t count{}; + if(length.empty()) return {"411 Length Required",{}}; + const auto converted=std::from_chars(length.data(),length.data()+length.size(),count); + if(converted.ec!=std::errc{} || converted.ptr!=length.data()+length.size()) return {"400 Bad Request",{}}; + if(count>maxRequest) return {"413 Content Too Large",{}}; + const auto start=end+4; + while(bytes.size()-start result; + std::atomic_bool cancelled{}; + }; + + lan::Network network; + lan::WinSocket listener; + unsigned port{}; + std::string token=lan::randomHex(32); + HWND owner{}; + std::mutex gate; + std::shared_ptr pending; + std::jthread worker; + + explicit Session(HWND window):owner(window) + { + listener.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); + BOOL exclusive=TRUE; + u_long nonblocking=1; + sockaddr_in address{}; + address.sin_family=AF_INET; + address.sin_addr.s_addr=htonl(INADDR_LOOPBACK); + int size=sizeof(address); + if(listener.value==INVALID_SOCKET || setsockopt(listener.value,SOL_SOCKET,SO_EXCLUSIVEADDRUSE, + reinterpret_cast(&exclusive),sizeof(exclusive)) || + ioctlsocket(listener.value,FIONBIO,&nonblocking) || + bind(listener.value,reinterpret_cast(&address),sizeof(address)) || + listen(listener.value,4) || getsockname(listener.value,reinterpret_cast(&address),&size)) + lan::socketError(); + port=ntohs(address.sin_port); + worker=std::jthread([this](std::stop_token stop){run(stop);}); + } + + ~Session() + { + worker.request_stop(); + if(worker.joinable()) worker.join(); + SecureZeroMemory(token.data(),token.size()); + } + + Json requestUi(std::string_view name,const Json &arguments,std::stop_token stop) + { + auto query=std::make_shared(); + query->name=name; + query->arguments=arguments; + auto result=query->result.get_future(); + { + std::lock_guard lock(gate); + pending=query; + } + const auto deadline=Clock::now()+2s; + if(PostMessageW(owner,filesMcpQueryMessage,0,0)) + while(!stop.stop_requested() && Clock::now()cancelled=true; + std::lock_guard lock(gate); + if(pending==query) pending.reset(); + return {{"error","Files did not answer in time."}}; + } + + void run(std::stop_token stop) + { + while(!stop.stop_requested()) + { + if(!readySocket(listener.value,false,stop,Clock::now()+100ms)) continue; + sockaddr_in peer{}; + int peerSize=sizeof(peer); + lan::WinSocket client; + client.value=accept(listener.value,reinterpret_cast(&peer),&peerSize); + u_long nonblocking=1; + if(client.value==INVALID_SOCKET || peer.sin_family!=AF_INET || + peer.sin_addr.s_addr!=htonl(INADDR_LOOPBACK) || ioctlsocket(client.value,FIONBIO,&nonblocking)) + continue; + HttpReply reply{"500 Internal Server Error",{}}; + try + { + reply=handleHttp(client.value,port,token,stop,[&](std::string_view name,const Json ¶ms) + {return requestUi(name,params,stop);}); + } + catch(const std::exception &) {} + const auto header=std::string("HTTP/1.1 ")+reply.status+"\r\nConnection: close\r\n" + "Cache-Control: no-store\r\nContent-Type: application/json\r\n"+reply.headers+ + "Content-Length: "+std::to_string(reply.body.size())+"\r\n\r\n"; + sendSocket(client.value,header+reply.body,stop); + } + } +}; + +FilesMcpServer::FilesMcpServer()=default; +FilesMcpServer::~FilesMcpServer()=default; + +void FilesMcpServer::start(HWND owner) +{ + if(!session) session=std::make_unique(owner); +} + +void FilesMcpServer::stop() {session.reset();} +unsigned FilesMcpServer::port() const {return session?session->port:0;} +std::string_view FilesMcpServer::token() const {return session?std::string_view(session->token):std::string_view{};} + +void FilesMcpServer::answer(const ReadTool &read) +{ + if(!session) return; + std::shared_ptr query; + { + std::lock_guard lock(session->gate); + query=std::exchange(session->pending,{}); + } + if(!query || query->cancelled) return; + try {query->result.set_value(read(query->name,query->arguments));} + catch(const std::exception &) {query->result.set_value({{"error","Files could not read the requested state."}});} +} +} diff --git a/src/files_mcp.h b/src/files_mcp.h new file mode 100644 index 0000000..0a4be41 --- /dev/null +++ b/src/files_mcp.h @@ -0,0 +1,33 @@ +#pragma once + +#include "../vendor/json.hpp" +#include +#include +#include +#include + +namespace ks::files +{ +inline constexpr UINT filesMcpQueryMessage=WM_APP+274; + +class FilesMcpServer +{ +public: + using Json=nlohmann::json; + using ReadTool=std::function; + FilesMcpServer(); + ~FilesMcpServer(); + FilesMcpServer(const FilesMcpServer &)=delete; + FilesMcpServer &operator=(const FilesMcpServer &)=delete; + + void start(HWND owner); + void stop(); + unsigned port() const; + std::string_view token() const; + void answer(const ReadTool &read); + +private: + struct Session; + std::unique_ptr session; +}; +} diff --git a/src/files_mcp_ui.inl b/src/files_mcp_ui.inl new file mode 100644 index 0000000..695d51f --- /dev/null +++ b/src/files_mcp_ui.inl @@ -0,0 +1,223 @@ +ks::files::FilesMcpServer filesMcp; +constexpr int filesMcpStatus=690,filesMcpEndpoint=691,filesMcpToken=692,filesMcpToggle=693, + filesMcpShowToken=694,filesMcpCopyToken=695; +constexpr size_t maxMcpRows=50,maxMcpSearchScan=10000; + +std::string mcpSide(int side) {return side==0?"left":"right";} + +bool mcpLocalPanel(const Panel &panel) +{ + return !panel.peer && !panel.ftp && !panel.archive && ks::files::isLocalDocumentPath(panel.directory); +} + +std::optional mcpRelativePath(const Panel &panel,size_t row) +{ + if(row>=panel.rows.size() || row>=panel.sizes.size() || panel.sizes[row]==L"Up") return {}; + const auto relative=panel.rows[row].lexically_relative(panel.directory); + if(relative.empty() || relative.has_root_path()) return {}; + for(const auto &part:relative) + if(!ks::files::validWindowsFileName(part.native())) return {}; + const auto path=relative.generic_wstring(); + if(path.size()>2048) return {}; + return path; +} + +Json mcpFileItem(const Panel &panel,size_t row,const std::wstring &relative) +{ + Json item{{"path",ks::utf8(relative)},{"marked",rowsecond; + const bool directory=(info.attributes&FILE_ATTRIBUTE_DIRECTORY)!=0; + item["metadataAvailable"]=true; + item["kind"]=directory?"directory":"file"; + item["attributes"]=info.attributes; + item["reparsePoint"]=(info.attributes&FILE_ATTRIBUTE_REPARSE_POINT)!=0; + if(!directory) item["sizeBytes"]=info.size; + if(info.modified) + { + const FILETIME time{static_cast(info.modified),static_cast(info.modified>>32)}; + SYSTEMTIME utc{}; + if(FileTimeToSystemTime(&time,&utc)) + { + wchar_t date[32]{}; + swprintf_s(date,L"%04u-%02u-%02uT%02u:%02u:%02uZ",utc.wYear,utc.wMonth,utc.wDay, + utc.wHour,utc.wMinute,utc.wSecond); + item["modifiedUtc"]=ks::utf8(date); + } + } + return item; +} + +std::optional mcpPageValue(const Json &args,const char *key,size_t fallback,size_t maximum) +{ + if(!args.contains(key)) return fallback; + const auto &value=args.at(key); + if(!value.is_number_unsigned() || value>maximum) return {}; + return value.get(); +} + +bool mcpArgumentNames(const Json &arguments,std::initializer_list accepted) +{ + for(auto field=arguments.begin();field!=arguments.end();++field) + if(std::ranges::find(accepted,std::string_view(field.key()))==accepted.end()) return false; + return true; +} + +std::optional mcpArgumentSide(const Json &arguments) +{ + if(!arguments.contains("side") || arguments.at("side")=="active") return active; + if(arguments.at("side")=="left") return 0; + if(arguments.at("side")=="right") return 1; + return {}; +} + +Json mcpPanelPage(const Panel &panel,size_t offset,size_t limit,std::wstring_view query={}) +{ + Json entries=Json::array(); + size_t row=std::min(offset,panel.rows.size()); + const auto scannedEnd=row+std::min(maxMcpSearchScan,panel.rows.size()-row); + for(;row()) return result; + result["directory"]=ks::utf8(panel.directory.native()); + result["mode"]=ks::utf8(panelModeNames[static_cast(panel.mode)]); + result["scanning"]=panel.scanRequest.has_value(); + const auto selected=currentPanelRow(panel); + if(selected!=LB_ERR) + if(const auto path=mcpRelativePath(panel,static_cast(selected))) result["cursor"]=ks::utf8(*path); + const auto *pending=panel.scanRequest && panel.scanRequest->find?&*panel.scanRequest->find:nullptr; + if(pending || panel.findOrigin) + { + const auto &find=pending?*pending:panel.findOrigin->options; + result["find"]={{"mask",ks::utf8(find.mask)},{"includeHidden",find.includeHidden}, + {"running",pending!=nullptr},{"error",pending?0:panel.findOrigin->error}}; + } + result.update(mcpPanelPage(panel,offset,limit)); + return result; +} + +Json readFilesMcpTool(std::string_view tool,const Json &arguments) +{ + const auto offset=mcpPageValue(arguments,"offset",0,2147483647); + const auto limit=mcpPageValue(arguments,"limit",25,maxMcpRows); + if(!offset || !limit || !*limit) return {{"error","Invalid page offset or limit."}}; + if(tool=="get_panels") + { + if(!mcpArgumentNames(arguments,{"offset","limit"})) return {{"error","Unknown pane argument."}}; + return {{"active",mcpSide(active)},{"panels",Json::array( + {mcpPanelState(0,*offset,*limit),mcpPanelState(1,*offset,*limit)})}}; + } + const auto side=mcpArgumentSide(arguments); + if(!side) return {{"error","Choose an active, left or right pane."}}; + const auto &panel=panels[*side]; + if(!mcpLocalPanel(panel)) return {{"error","This pane is not a local filesystem listing."}}; + if(tool=="search_files") + { + if(!mcpArgumentNames(arguments,{"side","query","offset","limit"}) || !arguments.contains("query") || + !arguments["query"].is_string() || arguments["query"].get_ref().size()>512) + return {{"error","Enter a search query of 1 to 128 characters."}}; + auto query=ks::wide(arguments["query"].get_ref()); + if(query.empty() || query.size()>128 || query.find_first_of(L"\r\n")!=query.npos || + query.find(L'\0')!=query.npos) return {{"error","Enter a search query of 1 to 128 characters."}}; + auto result=mcpPanelPage(panel,*offset,*limit,ks::lower(std::move(query))); + result["side"]=mcpSide(*side); + result["scope"]=panel.findOrigin?"find-results":"current-listing"; + return result; + } + if(tool!="get_file_metadata" || !mcpArgumentNames(arguments,{"side","path"}) || + !arguments.contains("path") || !arguments["path"].is_string() || + arguments["path"].get_ref().size()>8192) + return {{"error","Choose a relative path from the current pane."}}; + auto relative=fs::path(ks::wide(arguments["path"].get_ref())); + if(relative.empty() || relative.has_root_path() || relative.native().size()>2048) + return {{"error","Choose a relative path from the current pane."}}; + for(const auto &part:relative) + if(!ks::files::validWindowsFileName(part.native())) + return {{"error","Choose a relative path from the current pane."}}; + relative.make_preferred(); + const auto path=panel.directory/relative; + const auto found=std::ranges::find(panel.rows,path); + if(found==panel.rows.end()) return {{"error","The file is not in the current pane."}}; + const auto row=static_cast(found-panel.rows.begin()); + const auto listed=mcpRelativePath(panel,row); + if(!listed) return {{"error","The file is not in the current pane."}}; + return mcpFileItem(panel,row,*listed); +} + +void updateFilesMcpDialog(HWND dialog) +{ + const auto port=filesMcp.port(); + const auto endpoint=port?L"http://127.0.0.1:"+std::to_wstring(port)+L"/mcp":L""; + SetDlgItemTextW(dialog,filesMcpEndpoint,endpoint.c_str()); + SetDlgItemTextW(dialog,filesMcpToggle,port?L"&Stop":L"&Start"); + EnableWindow(GetDlgItem(dialog,filesMcpShowToken),port!=0); + EnableWindow(GetDlgItem(dialog,filesMcpCopyToken),port!=0); + if(!port) CheckDlgButton(dialog,filesMcpShowToken,BST_UNCHECKED); + const auto token=port && IsDlgButtonChecked(dialog,filesMcpShowToken)==BST_CHECKED? + ks::wide(std::string(filesMcp.token())):L""; + SetDlgItemTextW(dialog,filesMcpToken,token.c_str()); + SetDlgItemTextW(dialog,filesMcpStatus,port? + L"Running on this computer. Stop to revoke the session token.":L"Stopped."); +} + +INT_PTR CALLBACK filesMcpDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_INITDIALOG) + { + SetWindowLongPtrW(dialog,DWLP_USER,lp); + updateFilesMcpDialog(dialog); + return TRUE; + } + if(message==WM_CLOSE || (message==WM_COMMAND && (LOWORD(wp)==IDOK || LOWORD(wp)==IDCANCEL))) + { + SetDlgItemTextW(dialog,filesMcpToken,L""); + FilesModalDialog::finish(dialog,IDCANCEL); + return TRUE; + } + if(message!=WM_COMMAND) return FALSE; + switch(LOWORD(wp)) + { + case filesMcpToggle: + try + { + if(filesMcp.port()) filesMcp.stop(); + else filesMcp.start(reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER))); + updateFilesMcpDialog(dialog); + } + catch(const std::exception &) + { + SetDlgItemTextW(dialog,filesMcpStatus,L"Could not start the local MCP listener."); + } + return TRUE; + case filesMcpShowToken: + updateFilesMcpDialog(dialog); + return TRUE; + case filesMcpCopyToken: + if(filesMcp.port() && copyFilesText(dialog,ks::wide(std::string(filesMcp.token())),L"Could not copy the token.")) + SetDlgItemTextW(dialog,filesMcpStatus,L"Session token copied."); + return TRUE; + } + return FALSE; +} + +void showFilesMcp(HWND owner) +{ + FilesModalDialog dialog(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(620),owner,filesMcpDialog, + reinterpret_cast(owner),false,false); + dialog.runModal(); +} diff --git a/tests/files_mcp.cpp b/tests/files_mcp.cpp new file mode 100644 index 0000000..5400f04 --- /dev/null +++ b/tests/files_mcp.cpp @@ -0,0 +1,144 @@ +#include "lan_network.h" +#include "files_mcp.h" +#include +#include +#include +#include + +namespace +{ +using Server=ks::files::FilesMcpServer; +using Json=Server::Json; +using namespace std::chrono_literals; + +void expect(bool condition,const char *message) +{ + if(!condition) throw std::runtime_error(message); +} + +bool connectLoopback(SOCKET socket,unsigned port) +{ + sockaddr_in address{}; + address.sin_family=AF_INET; + address.sin_addr.s_addr=htonl(INADDR_LOOPBACK); + address.sin_port=htons(static_cast(port)); + return connect(socket,reinterpret_cast(&address),sizeof(address))==0; +} + +std::string post(unsigned port,const std::string &token,const Json &message, + std::string_view extra={},std::string_view host={}) +{ + ks::lan::WinSocket client; + client.value=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); + const DWORD timeout=4000; + expect(client.value!=INVALID_SOCKET && + !setsockopt(client.value,SOL_SOCKET,SO_RCVTIMEO,reinterpret_cast(&timeout),sizeof(timeout)) && + connectLoopback(client.value,port),"Could not connect to fixture listener"); + const auto body=message.dump(); + const auto authority=host.empty()?"127.0.0.1:"+std::to_string(port):std::string(host); + const auto bytes="POST /mcp HTTP/1.1\r\nHost: "+authority+"\r\nContent-Type: application/json\r\n" + "Accept: application/json, text/event-stream\r\n"+ + (token.empty()?std::string{}:"Authorization: Bearer "+token+"\r\n")+ + std::string(extra)+"Content-Length: "+std::to_string(body.size())+"\r\n\r\n"+body; + expect(send(client.value,bytes.data(),static_cast(bytes.size()),0)==static_cast(bytes.size()), + "Could not send fixture request"); + std::string response; + char buffer[4096]; + for(;;) + { + const int count=recv(client.value,buffer,sizeof(buffer),0); + expect(count>=0,"Fixture request timed out"); + if(!count) break; + response.append(buffer,count); + expect(response.size()<1024*1024,"Oversized fixture response"); + } + return response; +} + +Json content(const std::string &response) +{ + const auto end=response.find("\r\n\r\n"); + expect(end!=response.npos,"No HTTP headers"); + return Json::parse(response.substr(end+4)); +} + +Json request(std::string_view method,Json params=Json::object()) +{ + return {{"jsonrpc","2.0"},{"id",4},{"method",method},{"params",std::move(params)}}; +} +} + +int main() +{ + try + { + ks::lan::Network network; + const auto owner=CreateWindowExW(0,L"STATIC",L"Files MCP fixture",0,0,0,0,0, + HWND_MESSAGE,nullptr,GetModuleHandleW(nullptr),nullptr); + expect(owner!=nullptr,"Could not create fixture owner window"); + Server server; + expect(!server.port() && server.token().empty(),"The listener is enabled by default"); + server.start(owner); + const auto port=server.port(); + const auto token=std::string(server.token()); + expect(port && token.size()==64,"The session does not have a listener and token"); + const auto ping=request("ping"); + expect(post(port,{},ping).starts_with("HTTP/1.1 401"),"An unauthenticated request was accepted"); + expect(post(port,std::string(64,'0'),ping).starts_with("HTTP/1.1 401"),"A wrong token was accepted"); + expect(post(port,token,ping,"Origin: https://example.invalid\r\n").starts_with("HTTP/1.1 403"), + "A browser origin was accepted"); + expect(post(port,token,ping,{},"other.invalid").starts_with("HTTP/1.1 403"), + "An unexpected Host was accepted"); + expect(post(port,token,ping,"Content-Length: 1\r\n").starts_with("HTTP/1.1 400"), + "An ambiguous message length was accepted"); + const auto initialized=content(post(port,token,request("initialize",{{"protocolVersion","2025-11-25"}}))); + expect(initialized.at("result").at("protocolVersion")=="2025-11-25","Wrong protocol version"); + const Json notification{{"jsonrpc","2.0"},{"method","notifications/initialized"}}; + expect(post(port,token,notification).starts_with("HTTP/1.1 202"),"Initialization notification did not succeed"); + const auto listed=content(post(port,token,request("tools/list"))); + const auto &tools=listed.at("result").at("tools"); + expect(tools.size()==3,"The listener advertised unexpected capabilities"); + for(const auto &tool:tools) expect(tool.at("annotations").at("readOnlyHint")==true,"A tool is not read-only"); + const auto unknown=content(post(port,token,request("tools/call",{{"name","write_file"}}))); + expect(unknown.at("error").at("code")==-32602,"An unlisted tool was accepted"); + + auto pending=std::async(std::launch::async,[&] + { + return content(post(port,token,request("tools/call", + {{"name","get_panels"},{"arguments",{{"limit",3}}}}))); + }); + const auto deadline=std::chrono::steady_clock::now()+3s; + while(pending.wait_for(1ms)!=std::future_status::ready && std::chrono::steady_clock::now() Date: Thu, 26 Nov 2026 00:01:52 +0200 Subject: [PATCH 50/61] Release KSwitcher v0.8.0 --- CMakeLists.txt | 2 +- Release/README.md | 16 ++++++ Release/SHA256SUMS.txt | 2 +- Release/release-files.json | 101 +++++++++++++++++++++---------------- resources/app.rc | 6 +-- src/update.h | 2 +- 6 files changed, 80 insertions(+), 49 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 9a2d967..1d0124e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.7.4 LANGUAGES C CXX RC) +project(KSwitcher VERSION 0.8.0 LANGUAGES C CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() diff --git a/Release/README.md b/Release/README.md index 9121243..0fe6f17 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,21 @@ # Latest Windows release +## v0.8.0 — 2026-11-26 + +- **Files panels and search.** Find files recursively on local, FTP, SFTP and paired LAN panes. Work with results directly, navigate with breadcrumbs and history, recall recent folders, and configure sorting, filters, columns and panel layout. File clipboard and drag and drop integrate with Windows. +- **Storage and transfers.** Inspect folder sizes and disk usage with the tree, treemap and sunburst. Browse, extract, create and update ZIP and 7z archives. Copy and Move provide masks, multiple destinations and preservation options. +- **Viewing and editing.** Quick View supports text, Markdown, offline HTML, symbolic binary and images. Use Hex Viewer, line bookmarks, unified comparison, change-block application and Undo. Edit PNG/JPEG images with rotate and crop, and opt in to restoring local document windows after a restart. +- **Connections and Windows tools.** Browse saved FTP, SFTP and SMB connections, use the SSH terminal and jump hosts, inspect properties and locking processes, review and stage Git changes, commit the reviewed index, and inspect environment variables. +- **Customize and automate.** Use named keyboard schemes, separate area scales, Windows light and dark palettes, selective JSON settings transfer, offline F1 help, and the Files log. The optional loopback MCP exposes pane state, existing Find results and cached metadata with a per-session token. + +**Українською.** + +- **Панелі та пошук.** Рекурсивний пошук у локальних, FTP, SFTP і спарених LAN-панелях. Результати підтримують файлові операції. Доступні навігаційний шлях, історія, нещодавні папки, сортування, фільтри, колонки й налаштування панелей. Файловий буфер і перетягування працюють із Windows. +- **Сховище й перенесення.** Дерево, карта та сонячна діаграма показують використання диска. ZIP і 7z можна переглядати, розпаковувати, створювати й оновлювати. Копіювання й переміщення підтримують маски, кілька папок призначення та збереження атрибутів за вибором. +- **Перегляд і редагування.** Quick View підтримує текст, Markdown, офлайн-HTML, символьний перегляд бінарних даних і зображення. Доступні Hex Viewer, закладки рядків, об’єднане порівняння, застосування блоків змін і Undo. PNG/JPEG можна повертати й обрізати. Відновлення локальних вікон після перезапуску вмикається в Options. +- **Підключення та інструменти Windows.** Збережені підключення FTP, SFTP і SMB, SSH-термінал і проміжні вузли, властивості файлів, процеси, що їх блокують, Git Changes із підготовкою та комітом змін, перегляд і редагування змінних середовища. +- **Налаштування й автоматизація.** Іменовані схеми клавіш, окремий масштаб областей, світла й темна палітри Windows, вибіркове перенесення налаштувань через JSON, офлайн-довідка F1 і журнал Files. Опційний локальний MCP читає стан панелей, наявні результати Find і кешовані метадані за токеном сесії. + ## v0.7.4 — 2026-11-25 - **Settings → Sync → Google Drive** supports automatic synchronization and a dated list of manual backups. Only one automatic provider is active per PC. Restore a selected backup into the Settings draft and review it before pressing **Apply** or **Save**. diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index 176bb76..a9b881b 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -0209951cbe8c5a202dba12a807895ce7146dc6640f96704f6a4aa9afaa4fd3af KSwitcher-win-x64.zip +3d1d0d0a1c9ad671c949e0744987c94642125ccb2f479d3126509250c1fca541 KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index fb2d48f..7b94f5f 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,166 +1,181 @@ { - "version": "0.7.4", - "schema": 1, "files": [ { - "size": 3082752, - "sha256": "31a41c6ecc3387fc9f2b3f228ed64fa916d723654c02dc19bbbb558f94def4b8", + "sha256": "48fb46c472b1a3e689ff7a594f2ba728abee1b0ae2163333901179b624c23fe1", + "size": 3192832, "path": "KSwitcher.exe" }, { - "size": 2832384, - "sha256": "b993c050a96215aa63be97e9f05764ead13fcaf4b68fbb99f3d2f9a7d49a629a", + "sha256": "cf6f71169c79bb915c633765a4d56e6048e9a2c84ff877226158e9a27c8183ee", + "size": 2892800, "path": "KSwitcher.Config.exe" }, { - "size": 3187712, - "sha256": "eff5921b9067e0f4805c83d3cea10ddaa32b0b4e29f408b71b1004f78754afb9", + "sha256": "79ec0555f9a2668fd284dd73663e2a2aecbc5833dba39e2b02a45b88ad1cae3d", + "size": 3193344, "path": "KSwitcher.Screenshot.exe" }, { - "size": 4409344, - "sha256": "569d016d1eff9519cd33aa848723cea0365cbebe9333ed390245d098c4074d8e", + "sha256": "ebe481402fadc09f60afef4dc7ece293d2709c0f3931154d474fbc9a12c7d6a6", + "size": 5967872, "path": "KSwitcher.Files.exe" }, { - "size": 194912, "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6", + "size": 194912, "path": "WebView2Loader.dll" }, { - "size": 1103, "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f", + "size": 1103, "path": "terminal/addon-fit-LICENSE.txt" }, { - "size": 1521, "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527", + "size": 1521, "path": "terminal/addon-fit.js" }, { - "size": 527, "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef", + "size": 527, "path": "terminal/index.html" }, { - "size": 1073, "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473", + "size": 1073, "path": "terminal/markdown-it-LICENSE.txt" }, { - "size": 100786, "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e", + "size": 100786, "path": "terminal/markdown-it.js" }, { - "size": 3599, - "sha256": "b83ae50c2ada2aa6efcb02016ab54461fc9de5653111f976a51945ee0afd2094", + "sha256": "2576d0c897ffa7e78eb73fc065cd438af164b5dd332cc59083a53ac692fd575f", + "size": 3740, "path": "terminal/markdown.html" }, { - "size": 17575, - "sha256": "9a48dc026dbd3970a88c34775836534d795b90765a381fce3f2a7be9640d44c8", + "sha256": "1eaf9a8a63ec5a62eb4e710cd413bf6893dbc9eaf7dbf4898927fb44afa08bbc", + "size": 18318, "path": "terminal/markdown.js" }, { - "size": 1089, "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80", + "size": 1089, "path": "terminal/mermaid-LICENSE.txt" }, { - "size": 5537838, "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3", + "size": 5537838, "path": "terminal/mermaid.js" }, { - "size": 5065, - "sha256": "8268049507da54079422db2b4d90b41cd0a1e99b5946b675173ea3543de27f0b", + "sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7", + "size": 6627, "path": "terminal/terminal.js" }, { - "size": 1261, "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd", + "size": 1261, "path": "terminal/xterm-LICENSE.txt" }, { - "size": 7112, "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6", + "size": 7112, "path": "terminal/xterm.css" }, { - "size": 488663, "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972", + "size": 488663, "path": "terminal/xterm.js" }, { - "size": 4401, "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c", + "size": 4401, "path": "LICENSE" }, { - "size": 1096, "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831", + "size": 1096, "path": "json-LICENSE.txt" }, { - "size": 883, "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625", + "size": 883, "path": "files-text-license.txt" }, { - "size": 105515, + "sha256": "0b1d38528f1da5acccfb02634a91e3aa753547e137ccd1eebd0873fef2a9dd74", + "size": 4880, + "path": "files-archive-license.txt" + }, + { + "sha256": "c94d49ba533db63c368a49a7e630ac7e947634cb6dc87cfaab7627272cc3e3e7", + "size": 2994, + "path": "files-image-license.txt" + }, + { + "sha256": "05894358228417bb0c524b5c800119b1d47ac0de3477e7cd1abe7a6b41580809", + "size": 2024, + "path": "files-sftp-license.txt" + }, + { "sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01", + "size": 105515, "path": "README.md" }, { - "size": 12804, - "sha256": "f5bfc48e44af14dd6c45f56f689b4034ef1f7bdaca02f9d15ebc32af387366cf", + "sha256": "435ace9c718e14e4c391462ffea3a893c9b6622e9a8b861a7dab0492faf61469", + "size": 16474, "path": "LAN-PREVIEW.md" }, { - "size": 732485, "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9", + "size": 732485, "path": "dictionaries/en.txt" }, { - "size": 20566, "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5", + "size": 20566, "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt" }, { - "size": 2265, "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311", + "size": 2265, "path": "dictionaries/README.md" }, { - "size": 1109134, "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849", + "size": 1109134, "path": "dictionaries/ru.txt" }, { - "size": 1280, "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408", + "size": 1280, "path": "dictionaries/sources.json" }, { - "size": 940799, "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf", + "size": 940799, "path": "dictionaries/uk.txt" }, { - "size": 993, "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a", + "size": 993, "path": "tools/README.txt" }, { + "sha256": "d4de0a3606267a1c2585412e1288d3be782786720ff1f2ccd9b2217e053bc11b", "size": 133120, - "sha256": "ba891b6cc5d35d26520fa9ad34e136124e90ed10e0cff2f25dedadd0b48fb88e", "path": "tools/StayHere.exe" }, { - "size": 2796, "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413", + "size": 2796, "path": "tools/StayHere-README.md" } - ] + ], + "schema": 1, + "version": "0.8.0" } diff --git a/resources/app.rc b/resources/app.rc index df4f180..2900618 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -14,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur" 1 RT_MANIFEST "app.manifest" 201 RCDATA "update.ps1" 1 VERSIONINFO - FILEVERSION 0,7,4,0 - PRODUCTVERSION 0,7,4,0 + FILEVERSION 0,8,0,0 + PRODUCTVERSION 0,8,0,0 FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN @@ -25,7 +25,7 @@ BEGIN BEGIN VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility" VALUE "ProductName", "KSwitcher" - VALUE "FileVersion", "0.7.4" + VALUE "FileVersion", "0.8.0" END END BLOCK "VarFileInfo" diff --git a/src/update.h b/src/update.h index 13be1ef..03c5aab 100644 --- a/src/update.h +++ b/src/update.h @@ -2,7 +2,7 @@ #include "platform.h" namespace ks { -inline constexpr wchar_t AppVersion[] = L"0.7.4"; +inline constexpr wchar_t AppVersion[] = L"0.8.0"; inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; From 9b5cff122d88c0e001123988d85ea987a6904205 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Thu, 26 Nov 2026 00:25:22 +0200 Subject: [PATCH 51/61] Show SMB connections and shares in the file panel Refs #109 --- FILES-UI.md | 15 +- resources/files.rc | 17 -- src/files_compare.inl | 2 +- src/files_context_menu.inl | 24 ++- src/files_help.inl | 2 +- src/files_main.cpp | 158 ++++++++++++--- src/files_panel_recovery.inl | 6 + src/files_panel_rows.inl | 6 +- src/files_properties.inl | 2 +- src/files_smb.inl | 381 ++++++++++++++++------------------- tests/files_smb_password.ps1 | 63 ++++-- 11 files changed, 398 insertions(+), 278 deletions(-) diff --git a/FILES-UI.md b/FILES-UI.md index 65c31b9..52a01ad 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -111,12 +111,15 @@ Warning і початковий фокус на No. підтримувати атомарне перейменування OpenSSH. Якщо сервер відмовляє в заміні, Files показує причину й зберігає попередній файл. -- **SMB** у меню джерел обох панелей відкриває збережені підключення. - **New** додає назву й сервер або повний UNC-шлях. **Open** для сервера - показує видимі дискові шари. Відомий прихований шар можна додати як - повний UNC-шлях. Вибір шару або відкриття профілю з UNC-папкою переходить - до цієї папки в панелі, з якої викликали меню. -- Для SMB діють дозволи Windows. **Sign in** використовує вказаний +- **SMB** у меню джерел показує збережені підключення у вибраній панелі. + **Shift+F4** додає профіль із сервером або повним UNC-шляхом. + **F4** редагує профіль, **F8** запитує підтвердження видалення. + **Enter** або подвійний клік відкриває профіль. Сервер показує видимі + дискові шари в тій самій панелі, а шар або профіль із повним UNC-шляхом + відкриває папку. Відомий прихований шар можна додати як повний UNC-шлях. + **Esc** або рядок `..` повертає зі списку шарів до профілів. + **Esc** зі списку профілів повертає попередню папку. +- Для SMB діють дозволи Windows. **Sign in** у контекстному меню профілю використовує вказаний обліковий запис. Прапорець **Remember in Windows Credential Manager** типово вимкнений. Коли його ввімкнено, після успішного підключення Windows зберігає облікові дані для цього профілю. **Remove** видаляє профіль і diff --git a/resources/files.rc b/resources/files.rc index 5af5a3e..c950503 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -623,23 +623,6 @@ BEGIN CONTROL "&Cancel", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 147, 59, 80, 17 END -121 DIALOGEX 0, 0, 430, 192 -STYLE DS_SETFONT | DS_CENTER | WS_POPUP -CAPTION "SMB connections" -FONT 10, "Consolas" -BEGIN - LTEXT "", 540, 16, 16, 398, 12, SS_ENDELLIPSIS | SS_NOPREFIX - CONTROL "", 541, "ListBox", LBS_OWNERDRAWFIXED | LBS_HASSTRINGS | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_VSCROLL | WS_TABSTOP, 16, 31, 398, 103 - LTEXT "", 542, 16, 140, 398, 13, SS_ENDELLIPSIS | SS_NOPREFIX - LTEXT "", 543, 10, 159, 1, 1, NOT WS_VISIBLE - CONTROL "&Open", IDOK, "Button", BS_OWNERDRAW | WS_TABSTOP, 19, 166, 56, 17 - CONTROL "&New", 544, "Button", BS_OWNERDRAW | WS_TABSTOP, 82, 166, 56, 17 - CONTROL "&Edit", 545, "Button", BS_OWNERDRAW | WS_TABSTOP, 145, 166, 56, 17 - CONTROL "Re&move", 546, "Button", BS_OWNERDRAW | WS_TABSTOP, 208, 166, 56, 17 - CONTROL "&Sign in", 547, "Button", BS_OWNERDRAW | WS_TABSTOP, 271, 166, 60, 17 - CONTROL "&Close", IDCANCEL, "Button", BS_OWNERDRAW | WS_TABSTOP, 338, 166, 56, 17 -END - 122 DIALOGEX 0, 0, 355, 113 STYLE DS_SETFONT | DS_CENTER | WS_POPUP CAPTION "SMB connection" diff --git a/src/files_compare.inl b/src/files_compare.inl index 97df201..b659784 100644 --- a/src/files_compare.inl +++ b/src/files_compare.inl @@ -1230,7 +1230,7 @@ bool selectedComparisonFiles(CompareFile (&files)[2]) 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(panel.archive || transferProfileList(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder") + if(panel.archive || connectionList(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(); diff --git a/src/files_context_menu.inl b/src/files_context_menu.inl index 4fe3658..a6944ed 100644 --- a/src/files_context_menu.inl +++ b/src/files_context_menu.inl @@ -94,7 +94,23 @@ void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen) if(!popup.handle) return; constexpr UINT openItem=1,findItems=2,newProfile=3,properties=4; const auto add=[&](UINT id,const wchar_t *label){AppendMenuW(popup.handle,MF_STRING,id,label);}; - if(transferProfileList(panel)) + if(panel.smb) + { + if(panel.smb->server.empty()) + { + if(row!=LB_ERR) + { + add(openItem,L"Connect"); + add(112,L"Edit connection"); + add(smbSignInCommand,L"Sign in"); + add(117,L"Remove connection"); + } + add(newProfile,L"New connection"); + } + else if(row!=LB_ERR) add(openItem,L"Open share"); + add(110,L"Refresh panel"); + } + else if(transferProfileList(panel)) { if(row!=LB_ERR) { @@ -129,7 +145,11 @@ void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen) screen.x,screen.y,owner,nullptr)); if(command==openItem) enter(panel); else if(command==findItems) findPanelFiles(owner,panel); - else if(command==newProfile) editTransferProfile(panel,true); + else if(command==newProfile) + { + if(panel.smb) editSmbProfile(panel,true); + else editTransferProfile(panel,true); + } else if(command==properties) showPanelItemProperties(owner,panel); else if(command) SendMessageW(owner,WM_COMMAND,MAKEWPARAM(command,BN_CLICKED),0); } diff --git a/src/files_help.inl b/src/files_help.inl index 82439d6..b1c2124 100644 --- a/src/files_help.inl +++ b/src/files_help.inl @@ -32,7 +32,7 @@ constexpr struct L"Properties shows available file details and Windows attributes. The Windows context menu exposes actions supplied by the file type and the operating system.\r\n\r\n" L"Use Locking processes for selected local items to see processes with open handles. Save any work in the owning program before closing it."}, {L"Network connections",L"ftp sftp smb lan ssh host authentication credentials password remote", - L"The drive picker opens FTP, SFTP and SMB connection profiles, as well as paired LAN computers. Create a profile with its protocol, host and starting folder.\r\n\r\n" + L"The drive picker opens FTP, SFTP and SMB connection profiles, as well as paired LAN computers. SMB profiles and server shares appear in the selected file panel. Press Shift+F4 to add a profile or Enter to open the selected profile or share. Press Esc to go back. Sign in is in the profile context menu.\r\n\r\n" L"Check the remote server identity when connecting. If a listing is interrupted, use the Refresh command shown in the pane's status line to retry."}, {L"Command line and terminal",L"powershell ssh console history windows command f1", L"Type a PowerShell command and press Enter to run it in the active pane's context. Ctrl+O switches between the file panes and terminal output. Previous command and Command history use the active keyboard scheme.\r\n\r\n" diff --git a/src/files_main.cpp b/src/files_main.cpp index 8b91d91..67bde20 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -584,6 +584,16 @@ struct RemotePanelLocation TransferProtocol protocol{}; }; +namespace smb { struct PendingConnection; } + +struct SmbPanelListing +{ + std::string serverId; + std::wstring server; + std::vector> rows; + fs::path returnSelection; +}; + struct Panel { HWND path{}, list{}, heading{}; @@ -591,6 +601,8 @@ struct Panel FolderNavigation navigation; std::optional peer; std::optional ftp; + std::optional smb; + std::shared_ptr smbPending; std::optional archive; struct DirectoryWatch { @@ -645,6 +657,7 @@ struct Panel std::optional archive; unsigned reconnectAttempt{}; fs::path fallbackSelection; + std::optional smb; }; struct RemoteRetry { @@ -711,6 +724,21 @@ bool transferProfileList(const Panel &panel) return panel.ftp && panel.ftp->name.empty(); } +bool connectionList(const Panel &panel) +{ + return panel.smb || transferProfileList(panel); +} + +void showSmbProfiles(Panel &panel); +void refreshSmbPanel(Panel &panel); +void enterSmbPanel(Panel &panel); +void backSmbPanel(Panel &panel); +void editSmbProfile(Panel &panel,bool create); +void removeSmbProfile(Panel &panel); +void signInSmbProfile(Panel &panel); +void cancelSmbConnection(Panel &panel); +constexpr int smbSignInCommand=547; + FolderLocation folderLocation(const Panel &panel,const fs::path &directory) { if(panel.ftp) return {directory,transferFolderProvider(panel.ftp->protocol),panel.ftp->id,panel.ftp->name}; @@ -720,6 +748,7 @@ FolderLocation folderLocation(const Panel &panel,const fs::path &directory) std::wstring panelLocation(const Panel &panel) { + if(panel.smb) return panel.smb->server.empty()?L"SMB":L"SMB · "+panel.smb->server; if(panel.ftp) return transferProfileList(panel)?transferProtocolName(panel.ftp->protocol):panel.ftp->name+L" · "+ftpPath(panel.directory); return (panel.peer?panel.peer->name+L" · ":std::wstring{})+panel.directory.native(); @@ -736,7 +765,7 @@ DWORD effectivePanelColumns(const Panel &panel) bool hasPanelColumns(const Panel &panel) { - return detailedPanel(panel) && !panel.findOrigin && !transferProfileList(panel); + return detailedPanel(panel) && !panel.findOrigin && !connectionList(panel); } std::wstring panelCaption(const Panel &panel) @@ -2236,6 +2265,7 @@ LRESULT currentPanelRow(const Panel &panel) std::vector selectedPanelPaths(const Panel &panel) { std::vector paths; + if(panel.smb) return paths; std::set directories; visitPanelMarks(panel,[&](const fs::path &path,const FolderEntryMetadata &entry) { paths.push_back(path); @@ -2308,7 +2338,7 @@ void copyPanelNames(HWND owner) void copyPanelFiles(HWND owner,const Panel &panel) { - if(panel.peer || panel.ftp || panel.archive) + if(panel.peer || panel.ftp || panel.archive || panel.smb) { setStatus(L"File clipboard copy requires local files."); return; @@ -2357,6 +2387,7 @@ bool retryRemotePanel(Panel &panel,bool automatic=false,const fs::path &fallback void refreshPanel(Panel &panel) { + if(panel.smb) {refreshSmbPanel(panel);return;} cancelFolderSizes(panel); if(!panel.view.automaticSizes) panel.folderSizes.clear(); updateSelectionSummary(panel); @@ -2382,7 +2413,7 @@ std::wstring powerShellPath(const fs::path &path) void insertCurrentPanelPath(bool nameOnly = false) { const auto &panel=panels[active]; - if(panel.ftp || panel.archive) return; + if(panel.ftp || panel.smb || panel.archive) return; const auto row=currentPanelRow(panel); if(row==LB_ERR) return; const bool up=panel.sizes[row]==L"Up"; @@ -2570,6 +2601,7 @@ bool showCommandOutput(HWND owner,const Panel &panel) if(panel.ftp && panel.ftp->protocol==TransferProtocol::sftp && !panel.ftp->id.empty()) return startSshTerminal(owner,panel); closeSshPrompt(owner); + if(panel.smb) return ensureTerminalView(owner); if(panel.archive) return startTerminal(owner,panel.archive->file.parent_path()); return panel.peer || panel.ftp?ensureTerminalView(owner):startTerminal(owner,panel.directory); } @@ -2609,6 +2641,11 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value) setStatus(L"Shell commands require a local or LAN folder."); return false; } + if(panel.smb) + { + setStatus(L"Open a folder before running a shell command."); + return false; + } if(panel.ftp) { if(panel.ftp->protocol==TransferProtocol::sftp && !panel.ftp->id.empty()) @@ -2893,6 +2930,15 @@ void showFileDetails(const Panel &panel) L" · Enter: Go · Esc: Back"); return; } + if(panel.smb) + { + if(panel.smbPending) setStatus(L"Connecting to SMB… Esc Cancel"); + else if(!panel.smb->server.empty()) + setStatus(panel.rows.size()<=1?L"No visible shares Esc Back":L"Enter Open share Esc Back"); + else if(panel.rows.empty()) setStatus(L"Shift+F4 New connection Esc Back"); + else setStatus(L"Enter Connect Shift+F4 New Right-click for Edit, Remove or Sign in"); + return; + } if(transferProfileList(panel)) { setStatus(transferProfiles(panel.ftp->protocol).rows.empty()?L"Shift+F4 New connection": @@ -3123,7 +3169,9 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul auto &peer=request.peer; const auto previousDirectory=samePanelSource(panel,peer,request.ftp)?panel.directory:fs::path{}; const auto provider=peer?FolderProvider::lan:request.ftp?transferFolderProvider(request.ftp->protocol):FolderProvider::local; - const bool sameDirectory=sameFolderPath(previousDirectory,directory,provider); + const bool sameDirectory=request.smb || panel.smb? + request.smb && panel.smb && request.smb->serverId==panel.smb->serverId: + sameFolderPath(previousDirectory,directory,provider); auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=scan; const bool partial=error==ERROR_CANCELLED; if(error==ERROR_CONNECTION_ABORTED && request.find && panel.findOrigin && sameDirectory && files.empty() && @@ -3194,7 +3242,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul if(panel.marked[i]) markedPaths.insert(panel.rows[i]); } const bool finding=request.find.has_value(); - const bool viewChanged=finding!=panel.findOrigin.has_value(); + const bool viewChanged=finding!=panel.findOrigin.has_value() || request.smb.has_value()!=panel.smb.has_value(); if(finding) { if(!panel.findOrigin) @@ -3224,24 +3272,25 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul if(mark.parent_path()==folderPathWithoutSeparator(directory)) markedPaths.insert(mark); panel.listReturnMarks.clear(); } - const bool rememberFolder=!sameDirectory && !partial && (!panel.directory.empty() || peer || request.ftp); + const bool rememberFolder=!sameDirectory && !partial && (!panel.directory.empty() || panel.smb || peer || request.ftp); panel.directory = directory; panel.peer=std::move(peer); panel.ftp=std::move(request.ftp); panel.archive=std::move(request.archive); + panel.smb=std::move(request.smb); if(panel.archive) panel.archive->entries=std::move(archiveEntries); if(!sameDirectory) { cancelFolderSizes(panel); panel.folderSizes.clear(); } - if(partial || finding || panel.archive) panel.watch.reset(); + if(partial || finding || panel.archive || panel.smb) panel.watch.reset(); else if(!sameDirectory || panel.watch.handle==INVALID_HANDLE_VALUE) { panel.watch.reset(); std::swap(panel.watch.handle,nextWatch.handle); } - const bool profiles=transferProfileList(panel); + const bool profiles=connectionList(panel); if(!finding && !panel.archive && !profiles) { auto location=folderLocation(panel,directory); @@ -3265,7 +3314,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul const auto parent=finding?fs::path{}:panel.archive?directory.parent_path(): panelParentPath(directory,!panel.peer && !panel.ftp); const bool hasParent=!parent.empty(); - const auto rowCount=profiles?transferProfiles(panel.ftp->protocol).rows.size():finding?files.size(): + const auto rowCount=panel.smb?panel.smb->rows.size():profiles?transferProfiles(panel.ftp->protocol).rows.size():finding?files.size(): renderTree?panel.tree.branches.at(panel.tree.root).ordered.size()+hasParent:ordered.size()+hasParent; PanelRowsUpdate rows(panel,rowCount); const auto add=[&](const fs::path &path,const std::wstring &label,bool folder) @@ -3273,7 +3322,11 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul const bool marked=markedPaths.contains(path); if(rows.add(path,label,folder,marked) && marked) panel.filteredMarks.erase(path); }; - if(profiles) + if(panel.smb) + { + for(const auto &[path,label]:panel.smb->rows) rows.add(path,label,false,false,path==L".."); + } + else if(profiles) { const auto &connections=transferProfiles(panel.ftp->protocol).rows; for(size_t i=0;i> scanDirectoryInBackground(HWND o std::packaged_task()> task( [request=std::move(request),view=std::move(view),columns,entries=std::move(entries),stop] { + if(request.smb) + { + auto result=std::make_unique(); + result->opened=true; + return result; + } auto result=scanDirectory(request,*entries,stop); if(result->opened && !request.find) { @@ -3380,9 +3439,10 @@ void startDirectoryScan(Panel &panel) void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional peer, fs::path selection={},fs::path fallback={},std::optional ftp={}, std::optional navigationPosition={},std::optional archive={}, - unsigned reconnectAttempt=0,fs::path fallbackSelection={}) + unsigned reconnectAttempt=0,fs::path fallbackSelection={},std::optional smb={}) { - if(directory.empty() && !ftp) return; + if(directory.empty() && !ftp && !smb) return; + cancelSmbConnection(panel); panel.remoteRetry.reset(); if(!panel.view.revealedFile.empty() && (panel.view.revealedFile.parent_path()!=folderPathWithoutSeparator(directory) || @@ -3391,7 +3451,7 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti cancelFolderSizes(panel); panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback), std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition, - std::move(archive),reconnectAttempt,std::move(fallbackSelection)}; + std::move(archive),reconnectAttempt,std::move(fallbackSelection),std::move(smb)}; if(panel.scan.valid()) { panel.scanSuperseded=true; @@ -3925,7 +3985,6 @@ LRESULT smbDriveRow() {return lanDrivePicker?-1:sftpDriveRow()+1;} LRESULT recentDriveRow() {return lanDrivePicker?-1:smbDriveRow()+1;} LRESULT lanHeaderRow() {return recentDriveRow()+1;} void showRecentFolders(int side); -void showSmbProfiles(Panel &panel); bool driveSourceRow(LRESULT row) { @@ -4555,7 +4614,7 @@ void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb void openSelectedWithSystem(const Panel &panel) { - if(panel.ftp || panel.archive) return; + if(panel.ftp || panel.smb || panel.archive) return; const auto row=currentPanelRow(panel); if(row==LB_ERR) return; if(panel.peer) @@ -4591,7 +4650,7 @@ void refreshQuickView(const Panel &panel) { if(!quickViewWindow || &panel!=&panels[quickViewSource]) return; const auto row=currentPanelRow(panel); - const bool file=!panel.peer && !panel.ftp && !panel.archive && row!=LB_ERR && + const bool file=!panel.peer && !panel.ftp && !panel.smb && !panel.archive && row!=LB_ERR && panel.sizes[row]!=L"Folder" && panel.sizes[row]!=L"Up"; const auto path=file?panel.rows[row]:fs::path{}; if(file && ks::files::isImagePath(path) && !quickImageWindow) @@ -4677,7 +4736,7 @@ void openArchiveText(const Panel &panel,const fs::path &path,bool hex=false) void openSelectedText(const Panel &panel, bool edit, bool external,bool hex) { - if(transferProfileList(panel)) return; + if(connectionList(panel)) return; const auto row=currentPanelRow(panel); if(row==LB_ERR || panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") return; if(panel.archive) @@ -4714,6 +4773,7 @@ void openSelectedText(const Panel &panel, bool edit, bool external,bool hex) void enter(Panel &panel) { + if(panel.smb) {enterSmbPanel(panel);return;} const auto row=currentPanelRow(panel); if(row!=LB_ERR) { @@ -6779,6 +6839,11 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve { const auto sourceFtp=source.ftp; const bool ftpRename=move && sourceFtp && !transferProfileList(source); + if(source.smb || (destination.smb && !ftpRename && !renameHere)) + { + setStatus(L"Open a folder before copying or moving files."); + return; + } 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(); @@ -7527,7 +7592,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) bool pastePanelFiles(HWND owner,Panel &panel) { if(!IsClipboardFormatAvailable(CF_HDROP)) return false; - if(panel.peer || panel.ftp || panel.findOrigin) + if(panel.peer || panel.ftp || panel.smb || panel.findOrigin) { setStatus(L"Open a local folder before pasting files."); return true; @@ -7979,6 +8044,11 @@ void runFilesKeyCommand(HWND owner,int side,FilesKey command) case FilesKey::Edit: { const bool edit=command==FilesKey::Edit; + if(panel.smb) + { + if(edit) editSmbProfile(panel,false); + break; + } if(transferProfileList(panel)) { if(edit) editTransferProfile(panel,false); @@ -7991,7 +8061,10 @@ void runFilesKeyCommand(HWND owner,int side,FilesKey command) case FilesKey::Copy: case FilesKey::Move: copySelection(owner,panel,panels[1-side],command==FilesKey::Move); break; case FilesKey::Mkdir: makeFolder(owner,panel); break; - case FilesKey::Delete: deleteSelection(owner,panel,false); break; + case FilesKey::Delete: + if(panel.smb) removeSmbProfile(panel); + else deleteSelection(owner,panel,false); + break; case FilesKey::Exit: SendMessageW(owner,WM_CLOSE,0,0); break; case FilesKey::Compare: compareSelectedFiles(owner); break; case FilesKey::Previous: recallPreviousCommand(); break; @@ -8052,7 +8125,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT { auto &panel=panels[index]; const auto row=panelRowAt(window,screen,SendMessageW(window,LB_GETTOPINDEX,0,0),panel.rows.size()); - if(row!=LB_ERR && panel.sizes[row]!=L"Up" && !transferProfileList(panel)) + if(row!=LB_ERR && panel.sizes[row]!=L"Up" && !connectionList(panel)) { closePanelSearch(); SetFocus(window); @@ -8513,7 +8586,8 @@ void searchPanelByPrefix(HWND window,wchar_t character) { if(panel.sizes[row]==L"Up") continue; const auto *profiles=transferProfileList(panel)?&transferProfiles(panel.ftp->protocol).rows:nullptr; - const auto name=profiles && rowsize()?(*profiles)[row].name:panel.rows[row].filename().native(); + const auto name=panel.smb && rowrows.size()?panel.smb->rows[row].second: + profiles && rowsize()?(*profiles)[row].name:panel.rows[row].filename().native(); if(name.size()=firstDriveButton && LOWORD(wp)<=moreDriveButton) { const auto id=LOWORD(wp); @@ -9430,15 +9511,25 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) ks::files::saveLocalDocumentSession(schemeKey,restoreDocuments); for(int i=0;i<2;++i) { - saveFtpPanelLocation(panels[i],i); - const auto path=(panels[i].archive?panels[i].archive->file.parent_path():panels[i].directory).native(); - if(!panels[i].peer && !panels[i].ftp && !path.empty()) + const auto &panel=panels[i]; + saveFtpPanelLocation(panel,i); + if(panel.peer || panel.ftp) continue; + auto path=(panel.archive?panel.archive->file.parent_path():panel.directory).native(); + const auto row=currentPanelRow(panel); + auto cursor=panel.archive?panel.archive->file.native(): + row==LB_ERR?std::wstring{}:panel.rows[row].native(); + if(panel.smb) + { + if(panel.navigation.history.empty()) continue; + const auto &previous=panel.navigation.history[panel.navigation.current]; + if(previous.provider!=FolderProvider::local) continue; + path=previous.directory.native(); + cursor=panel.smb->returnSelection.native(); + } + if(!path.empty()) RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelPathKeys[i],REG_SZ,path.c_str(), static_cast((path.size()+1)*sizeof(wchar_t))); - const auto row=SendMessageW(panels[i].list,LB_GETCURSEL,0,0); - const auto cursor=panels[i].archive?panels[i].archive->file.native(): - row>=0 && static_cast(row)((cursor.size()+1)*sizeof(wchar_t))); } DestroyWindow(window); @@ -9454,6 +9545,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) for(auto &panel:panels) { panel.scanStop.request_stop(); + cancelSmbConnection(panel); stopTreeBranches(panel); panel.watch.reset(); } @@ -9606,6 +9698,11 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) if(!panel.scanSuperseded) stopDirectoryScan(); continue; } + if(panel.smb && !panel.scanRequest && !GetWindowTextLengthW(terminalInput)) + { + backSmbPanel(panel); + continue; + } if(panel.archive && !panel.scanRequest) { parentArchive(panel); @@ -9719,7 +9816,8 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window)) { auto &panel=panels[active]; - if(transferProfileList(panel)) editTransferProfile(panel,true); + if(panel.smb) editSmbProfile(panel,true); + else if(transferProfileList(panel)) editTransferProfile(panel,true); else openOrCreateText(window,panel); } continue; diff --git a/src/files_panel_recovery.inl b/src/files_panel_recovery.inl index f02d7d7..b6d5509 100644 --- a/src/files_panel_recovery.inl +++ b/src/files_panel_recovery.inl @@ -124,6 +124,12 @@ void saveFtpPanelLocation(const Panel &panel,int index) location=panel.remoteRetry->location; else if(panel.scanRequest && panel.scanRequest->ftp && panel.scanRequest->ftp->protocol==TransferProtocol::ftp) location={panel.scanRequest->directory,panel.scanRequest->selection,panel.scanRequest->ftp->id}; + else if(panel.smb && !panel.navigation.history.empty()) + { + const auto &previous=panel.navigation.history[panel.navigation.current]; + if(previous.provider==FolderProvider::ftp) + location={previous.directory,panel.smb->returnSelection,previous.id}; + } const auto key=ftpPanelLocationKeys[index]; if(location.ftpProfile.empty() || !isFtpFolderPath(location.directory)) diff --git a/src/files_panel_rows.inl b/src/files_panel_rows.inl index b067c65..abb1aaa 100644 --- a/src/files_panel_rows.inl +++ b/src/files_panel_rows.inl @@ -2,7 +2,7 @@ class PanelRowsUpdate { public: PanelRowsUpdate(Panel &panel,size_t count) : panel(panel),visible(IsWindowVisible(panel.list)), - profiles(transferProfileList(panel)) + profiles(connectionList(panel)) { if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0); panel.rows.clear(); @@ -35,7 +35,7 @@ public: const auto found=panel.metadata.find(path); const auto entry=up || profiles || found==panel.metadata.end()?FolderEntryMetadata{}:found->second; panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0); - panel.sizes.push_back(profiles?L"":folder?(up?L"Up":L"Folder"):std::to_wstring(entry.size)); + panel.sizes.push_back(up?L"Up":profiles?L"":folder?L"Folder":std::to_wstring(entry.size)); if(!up && !profiles) { auto &longest=panel.longestColumn; @@ -120,7 +120,7 @@ void visitPanelMarks(const Panel &panel,const Visitor &visit) } return; } - if(transferProfileList(panel)) return; + if(connectionList(panel)) return; for(size_t i=0;i profiles; - std::optional server; - std::vector shares; - fs::path chosen; + Profile profile; std::atomic_bool canceled{}; - bool busy{}; + std::promise result; + std::future completion=result.get_future(); }; -void browserControls(HWND dialog,const Browser &browser) +std::optional findProfile(const fs::path &id) { - const auto selected=SendDlgItemMessageW(dialog,list,LB_GETCURSEL,0,0)!=LB_ERR; - EnableWindow(GetDlgItem(dialog,list),!browser.busy); - EnableWindow(GetDlgItem(dialog,IDOK),!browser.busy && selected); - EnableWindow(GetDlgItem(dialog,newProfile),!browser.busy); - for(const auto button:{editProfile,removeProfile,signIn}) - EnableWindow(GetDlgItem(dialog,button),!browser.busy && selected && !browser.server); + const auto profiles=readProfiles(); + const auto match=std::find_if(profiles.begin(),profiles.end(),[&](const auto &profile) { + return ks::wide(profile.id)==id.native(); + }); + return match==profiles.end()?std::nullopt:std::optional{*match}; } -void showRows(HWND dialog,const Browser &browser,LRESULT selection=0) +std::optional selectedProfile(const Panel &panel) { - const auto rows=GetDlgItem(dialog,list); - SendMessageW(rows,LB_RESETCONTENT,0,0); - const auto add=[&](const std::wstring &label){SendMessageW(rows,LB_ADDSTRING,0,reinterpret_cast(label.c_str()));}; - if(browser.server) - { - for(const auto &share:browser.shares) add(share); - SetDlgItemTextW(dialog,summary,(L"Shared folders on "+browser.server->target.server).c_str()); - SetDlgItemTextW(dialog,status,browser.shares.empty()?L"No visible disk shares. A known UNC share can be saved as a profile.":L""); - SetDlgItemTextW(dialog,newProfile,L"&Back"); - for(const auto button:{editProfile,removeProfile,signIn}) ShowWindow(GetDlgItem(dialog,button),SW_HIDE); - layoutDialogButtons(dialog,footer,{IDOK,newProfile,IDCANCEL}); - } - else - { - for(const auto &entry:browser.profiles) add(entry.name+L" · "+profileAddress(entry)); - SetDlgItemTextW(dialog,summary,L"Saved SMB connections"); - SetDlgItemTextW(dialog,status,browser.profiles.empty()?L"Choose New to add a server or UNC folder.":L""); - SetDlgItemTextW(dialog,newProfile,L"&New"); - for(const auto button:{editProfile,removeProfile,signIn}) ShowWindow(GetDlgItem(dialog,button),SW_SHOWNA); - layoutDialogButtons(dialog,footer,{IDOK,newProfile,editProfile,removeProfile,signIn,IDCANCEL}); - } - const auto count=SendMessageW(rows,LB_GETCOUNT,0,0); - if(count>0) SendMessageW(rows,LB_SETCURSEL,std::clamp(selection,0,count-1),0); - browserControls(dialog,browser); - SetFocus(count>0?rows:GetDlgItem(dialog,newProfile)); + if(!panel.smb || !panel.smb->server.empty() || panel.scan.valid() || panel.smbPending) return {}; + const auto row=currentPanelRow(panel); + return row==LB_ERR?std::nullopt:findProfile(panel.rows[row]); } -void openProfile(HWND dialog,Browser &browser,const Profile &profile,bool withLogin) +void openListing(Panel &panel,SmbPanelListing listing,fs::path selection={}) { - Credentials login; + if(panel.smb) listing.returnSelection=panel.smb->returnSelection; + else if(const auto row=currentPanelRow(panel);row!=LB_ERR) listing.returnSelection=panel.rows[row]; + openOn(panel,{},false,{},std::move(selection),{},{},{},{},0,{},std::move(listing)); +} + +void showProfiles(Panel &panel,const std::vector &profiles,fs::path selection={}) +{ + SmbPanelListing listing; + listing.rows.reserve(profiles.size()); + for(const auto &profile:profiles) + listing.rows.emplace_back(ks::wide(profile.id),profile.name+L" · "+profileAddress(profile)); + openListing(panel,std::move(listing),std::move(selection)); +} + +void refreshProfiles(Panel &panel,const std::vector &profiles,fs::path selection={}) +{ + for(auto &other:panels) + if(other.smb && other.smb->server.empty() && !other.smbPending && !other.scan.valid()) + showProfiles(other,profiles,&other==&panel?selection:fs::path{}); +} + +void openProfile(Panel &panel,Profile profile,bool withLogin) +{ + if(panel.smbPending || panel.scan.valid()) return; + const auto owner=GetParent(panel.list); + std::shared_ptr login; if(withLogin) { - LoginPrompt prompt{profile,login}; - if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(123),dialog,loginDialog, + login=std::make_shared(); + LoginPrompt prompt{profile,*login}; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(123),owner,loginDialog, reinterpret_cast(&prompt))!=IDOK) return; } - browser.busy=true; - browser.canceled=false; - browserControls(dialog,browser); - SetFocus(GetDlgItem(dialog,IDCANCEL)); - SetDlgItemTextW(dialog,status,(L"Connecting to "+profile.target.server+L"…").c_str()); - Connection result; + auto pending=std::make_shared(); + pending->profile=std::move(profile); try { - FileOperationUi worker; - worker.run(dialog,browser.canceled,[&]{result=connect(profile,withLogin?&login:nullptr,browser.canceled);}); + std::thread([pending,login=std::move(login),owner] { + Connection connection; + try {connection=connect(pending->profile,login.get(),pending->canceled);} + catch(const std::exception &) {connection.error=ERROR_GEN_FAILURE;} + pending->result.set_value(std::move(connection)); + PostMessageW(owner,directoryScanReady,0,0); + }).detach(); } - catch(const std::exception &) + catch(const std::system_error &error) { - result.error=ERROR_GEN_FAILURE; - } - browser.busy=false; - browserControls(dialog,browser); - if(browser.canceled) - { - SetDlgItemTextW(dialog,status,L"Connection canceled."); - SetFocus(GetDlgItem(dialog,list)); + setStatus(L"Could not start SMB connection: "+fileError(error)); return; } - if(result.error) - { - auto detail=profileAddress(profile)+L"\r\n\r\n"+errorText(result.error); - if(result.error==ERROR_ACCESS_DENIED || result.error==ERROR_LOGON_FAILURE || - result.error==ERROR_INVALID_PASSWORD || result.error==ERROR_BAD_USERNAME) - detail+=L"\r\n\r\nUse Sign in to try a different account."; - showFilesNotice(dialog,detail.c_str(),L"Could not open SMB connection",{.tone=FilesNoticeTone::warning}); - SetDlgItemTextW(dialog,status,L"Connection failed. Open to retry or choose Sign in."); - SetFocus(GetDlgItem(dialog,list)); - return; - } - if(result.credentialError) - { - const auto detail=L"Connected, but Windows Credential Manager did not save the account.\r\n\r\n"+ - errorText(result.credentialError); - showFilesNotice(dialog,detail.c_str(),L"SMB sign in",{.tone=FilesNoticeTone::warning}); - } - if(!result.folder.empty()) - { - browser.chosen=std::move(result.folder); - FilesModalDialog::finish(dialog,IDOK); - return; - } - browser.server=profile; - browser.shares=std::move(result.shares); - showRows(dialog,browser); + panel.smbPending=std::move(pending); + if(&panel==&panels[active]) showFileDetails(panel); +} } -INT_PTR CALLBACK browserDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +void cancelSmbConnection(Panel &panel) { - auto *browser=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); - if(message==WM_INITDIALOG) - { - browser=reinterpret_cast(lp); - SetWindowLongPtrW(dialog,DWLP_USER,lp); - prepareCopyDialog(dialog); - layoutDialogContent(dialog,summary); - for(const auto id:{summary,list,status}) - SendDlgItemMessageW(dialog,id,WM_SETFONT,reinterpret_cast(mono),FALSE); - SendDlgItemMessageW(dialog,list,LB_SETITEMHEIGHT,0,textHeight); - installScrollBar(GetDlgItem(dialog,list),dialog); - showRows(dialog,*browser); - return FALSE; - } - if(message==WM_DRAWITEM && wp==list) - { - const auto &item=*reinterpret_cast(lp); - if(item.itemID==UINT(-1)) return TRUE; - const auto length=SendMessageW(item.hwndItem,LB_GETTEXTLEN,item.itemID,0); - if(length==LB_ERR) return TRUE; - std::wstring label(static_cast(length)+1,L'\0'); - SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast(label.data())); - const bool selected=(item.itemState&ODS_SELECTED)!=0; - paintDialogListRow(item.hDC,item.rcItem,label.c_str(),mono,colors[Text], - selected?colors[Selection]:colors[Dialog],dialogRowTextInset(cellWidth),DT_END_ELLIPSIS); - return TRUE; - } - if(const auto painted=paintCopyDialog(dialog,message,wp,lp,L" SMB ",false,{footer},true,GetDlgItem(dialog,list))) - return painted; - if(!browser) return FALSE; - if(closeRequest(message,wp)) - { - if(browser->busy) - { - browser->canceled=true; - SetDlgItemTextW(dialog,status,L"Stopping when Windows returns…"); - } - else FilesModalDialog::finish(dialog,IDCANCEL); - return TRUE; - } - if(message!=WM_COMMAND) return FALSE; - if(browser->busy) return TRUE; - const auto command=LOWORD(wp); - const auto row=SendDlgItemMessageW(dialog,list,LB_GETCURSEL,0,0); - if(command==list && HIWORD(wp)==LBN_SELCHANGE) - { - browserControls(dialog,*browser); - return TRUE; - } - const bool open=command==IDOK || (command==list && HIWORD(wp)==LBN_DBLCLK); - if(browser->server) - { - if(command==newProfile) - { - browser->server.reset(); - browser->shares.clear(); - showRows(dialog,*browser); - } - else if(open && row>=0 && static_cast(row)shares.size()) - { - browser->chosen=fs::path(browser->server->target.server+L"\\"+browser->shares[row]); - FilesModalDialog::finish(dialog,IDOK); - } - return TRUE; - } - const auto *selected=row>=0 && static_cast(row)profiles.size()?&browser->profiles[row]:nullptr; - if(command==newProfile || (command==editProfile && selected)) - { - EditProfile edit{command==newProfile?Profile{}:*selected}; - if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(122),dialog,editDialog, - reinterpret_cast(&edit))==IDOK) - { - browser->profiles=std::move(*edit.saved); - const auto profile=std::find_if(browser->profiles.begin(),browser->profiles.end(),[&](const auto &entry) { - return entry.id==edit.profile.id; - }); - showRows(dialog,*browser,profile-browser->profiles.begin()); - } - return TRUE; - } - if(selected && (open || command==signIn)) - { - openProfile(dialog,*browser,*selected,command==signIn); - return TRUE; - } - if(selected && command==removeProfile) - { - const auto detail=L"Remove "+selected->name+L" and its saved credentials?"; - if(showFilesNotice(dialog,detail.c_str(),L"Remove SMB connection",{.confirm=true})!=IDYES) return TRUE; - DWORD error=ERROR_SUCCESS; - auto updated=updateProfiles([&](auto &profiles) { - const auto row=std::find_if(profiles.begin(),profiles.end(),[&](const auto &entry){return entry.id==selected->id;}); - if(row==profiles.end()) return true; - if((error=deleteCredential(*row))) return false; - profiles.erase(row); - return true; - }); - if(updated) - { - browser->profiles=std::move(*updated); - showRows(dialog,*browser,row); - } - else - { - const auto failure=error?errorText(error):L"Could not remove the saved connection."; - showFilesNotice(dialog,failure.c_str(),L"Remove SMB connection"); - } - return TRUE; - } - return FALSE; -} + if(auto pending=std::exchange(panel.smbPending,{})) pending->canceled=true; } void showSmbProfiles(Panel &panel) { - smb::Browser browser{smb::readProfiles()}; - if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(121),GetParent(panel.list), - smb::browserDialog,reinterpret_cast(&browser))==IDOK) - openOn(panel,browser.chosen,false,{}); + smb::showProfiles(panel,smb::readProfiles()); +} + +void refreshSmbPanel(Panel &panel) +{ + if(panel.scan.valid() || panel.smbPending) return; + if(panel.smb->server.empty()) showSmbProfiles(panel); + else if(auto profile=smb::findProfile(ks::wide(panel.smb->serverId));profile && profile->target.folder.empty()) + smb::openProfile(panel,std::move(*profile),false); + else showSmbProfiles(panel); +} + +void backSmbPanel(Panel &panel) +{ + if(panel.smbPending) + { + cancelSmbConnection(panel); + setStatus(L"SMB connection canceled."); + } + else if(!panel.smb->server.empty()) smb::showProfiles(panel,smb::readProfiles(),ks::wide(panel.smb->serverId)); + else if(!panel.navigation.history.empty()) + { + const auto &location=panel.navigation.history[panel.navigation.current]; + if(location.provider==FolderProvider::local) + openOn(panel,location.directory,false,{},panel.smb->returnSelection); + else openFolderLocation(panel,location,panel.navigation.current); + } +} + +void enterSmbPanel(Panel &panel) +{ + if(panel.scan.valid() || panel.smbPending) return; + if(panel.smb->server.empty()) + { + if(auto profile=smb::selectedProfile(panel)) smb::openProfile(panel,std::move(*profile),false); + return; + } + const auto row=currentPanelRow(panel); + if(row==LB_ERR) return; + const auto &name=panel.rows[row]; + if(name==L"..") backSmbPanel(panel); + else openOn(panel,fs::path(panel.smb->server+L"\\"+name.native()),false,{}); +} + +void editSmbProfile(Panel &panel,bool create) +{ + if(!panel.smb || !panel.smb->server.empty() || panel.smbPending || panel.scan.valid()) return; + const auto profile=create?std::optional{smb::Profile{}}:smb::selectedProfile(panel); + if(!profile) return; + smb::EditProfile edit{*profile}; + if(FilesModalDialog::run(GetModuleHandleW(nullptr),MAKEINTRESOURCEW(122),GetParent(panel.list),smb::editDialog, + reinterpret_cast(&edit))==IDOK) + smb::refreshProfiles(panel,*edit.saved,ks::wide(edit.profile.id)); +} + +void removeSmbProfile(Panel &panel) +{ + const auto selected=smb::selectedProfile(panel); + if(!selected) return; + const auto owner=GetParent(panel.list); + const auto detail=L"Remove "+selected->name+L" and its saved credentials?"; + if(showFilesNotice(owner,detail.c_str(),L"Remove SMB connection",{.confirm=true})!=IDYES) return; + DWORD error=ERROR_SUCCESS; + const auto updated=smb::updateProfiles([&](auto &profiles) { + const auto entry=std::find_if(profiles.begin(),profiles.end(),[&](const auto &profile){return profile.id==selected->id;}); + if(entry==profiles.end()) return true; + if((error=smb::deleteCredential(*entry))) return false; + profiles.erase(entry); + return true; + }); + if(updated) smb::refreshProfiles(panel,*updated); + else + { + const auto failure=error?smb::errorText(error):L"Could not remove the saved connection."; + showFilesNotice(owner,failure.c_str(),L"Remove SMB connection"); + } +} + +void signInSmbProfile(Panel &panel) +{ + if(auto profile=smb::selectedProfile(panel)) smb::openProfile(panel,std::move(*profile),true); +} + +void collectSmbConnections(HWND owner) +{ + for(auto &panel:panels) + { + if(!panel.smbPending || panel.smbPending->completion.wait_for(std::chrono::seconds(0))!=std::future_status::ready) + continue; + auto pending=std::exchange(panel.smbPending,{}); + const auto result=pending->completion.get(); + const auto &profile=pending->profile; + if(result.error) + { + auto detail=smb::profileAddress(profile)+L"\r\n\r\n"+smb::errorText(result.error); + if(result.error==ERROR_ACCESS_DENIED || result.error==ERROR_LOGON_FAILURE || + result.error==ERROR_INVALID_PASSWORD || result.error==ERROR_BAD_USERNAME) + detail+=L"\r\n\r\nUse Sign in to try a different account."; + showFilesNotice(owner,detail.c_str(),L"Could not open SMB connection",{.tone=FilesNoticeTone::warning}); + if(&panel==&panels[active]) showFileDetails(panel); + continue; + } + if(result.credentialError) + { + const auto detail=L"Connected, but Windows Credential Manager did not save the account.\r\n\r\n"+ + smb::errorText(result.credentialError); + showFilesNotice(owner,detail.c_str(),L"SMB sign in",{.tone=FilesNoticeTone::warning}); + } + if(!result.folder.empty()) openOn(panel,result.folder,false,{}); + else + { + SmbPanelListing listing{profile.id,profile.target.server}; + listing.rows.emplace_back(L"..",L".."); + for(const auto &share:result.shares) listing.rows.emplace_back(share,L"["+share+L"]"); + const auto selectFirst=profile.id!=panel.smb->serverId && !result.shares.empty(); + smb::openListing(panel,std::move(listing),selectFirst?fs::path(result.shares.front()):fs::path{}); + } + } } diff --git a/tests/files_smb_password.ps1 b/tests/files_smb_password.ps1 index bef68ac..6546419 100644 --- a/tests/files_smb_password.ps1 +++ b/tests/files_smb_password.ps1 @@ -62,18 +62,53 @@ try { } [void][FilesCommandsUi]::ShowWindow($main, 4) $picker = [FilesCommandsUi]::GetDlgItem($main, 121) - [void][FilesCommandsUi]::Post($main, 0x104, [IntPtr]112, [IntPtr]::Zero) - [void](Wait-For 'Change drive' { [FilesCommandsUi]::IsWindowVisible($picker) }) - $count = [FilesCommandsUi]::Send($picker, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() - $selection = -1 - for ($row = 0; $row -lt $count; ++$row) { - $label = [Text.StringBuilder]::new(256) - [void][FilesCommandsUi]::Read($picker, 393, [IntPtr]$row, $label) - if ($label.ToString() -ceq 'SMB') { $selection = $row; break } + function Read-List([IntPtr]$List) { + $count = [FilesCommandsUi]::Send($List, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() + for ($row = 0; $row -lt $count; ++$row) { + $label = [Text.StringBuilder]::new(256) + [void][FilesCommandsUi]::Read($List, 393, [IntPtr]$row, $label) + $label.ToString() + } } - if ($selection -lt 0) { throw 'SMB was missing from Change drive.' } - [void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$selection, [IntPtr]::Zero) - [void][FilesCommandsUi]::Post($picker, 0x100, [IntPtr]13, [IntPtr]::Zero) + function Same-Rows($First, $Second) { + ($First -join [char]10) -ceq ($Second -join [char]10) + } + function Open-Smb([int]$Side) { + $menu = if ($Side -eq 0) { 130 } else { 134 } + [void][FilesCommandsUi]::Post($main, 0x111, [IntPtr]$menu, [IntPtr]::Zero) + [void](Wait-For "Change drive in panel ${Side}'s menu" { + [FilesCommandsUi]::IsWindowVisible($picker) -and [bool]((Read-List $picker) -like '*Change drive*') + }) + $options = @(Read-List $picker) + $selection = [array]::IndexOf($options, ($options -like '*Change drive*' | Select-Object -First 1)) + [void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$selection, [IntPtr]::Zero) + [void][FilesCommandsUi]::Post($main, 0x111, [IntPtr](0x20000 + 121), $picker) + [void](Wait-For "SMB in panel ${Side}'s source picker" { + [FilesCommandsUi]::IsWindowVisible($picker) -and (Read-List $picker) -contains 'SMB' + }) + $selection = [array]::IndexOf(@(Read-List $picker), 'SMB') + if ($selection -lt 0) { throw 'SMB was missing from Change drive.' } + [void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$selection, [IntPtr]::Zero) + [void][FilesCommandsUi]::Post($main, 0x111, [IntPtr](0x20000 + 121), $picker) + } + $left = [FilesCommandsUi]::GetDlgItem($main, 102) + $right = [FilesCommandsUi]::GetDlgItem($main, 103) + [void](Wait-For 'both local panels' { @(Read-List $left).Count -gt 0 -and @(Read-List $right).Count -gt 0 }) + $leftBefore = @(Read-List $left) + $rightBefore = @(Read-List $right) + Open-Smb 0 + [void](Wait-For 'the SMB profile in the left file panel' { + (Read-List $left) -like 'Render fixture*' + }) + if (!(Same-Rows $rightBefore @(Read-List $right))) { throw 'Opening SMB on the left changed the right panel.' } + [void][FilesCommandsUi]::Post($left, 0x100, [IntPtr]27, [IntPtr]::Zero) + [void](Wait-For 'Escape to return to the left folder' { Same-Rows $leftBefore @(Read-List $left) }) + Open-Smb 1 + [void](Wait-For 'the SMB profile in the right file panel' { + (Read-List $right) -like 'Render fixture*' + }) + if (!(Same-Rows $leftBefore @(Read-List $left))) { throw 'Opening SMB on the right changed the left panel.' } + function Find-DialogControl([int]$Id) { $dialog = [IntPtr]::Zero while (($dialog = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $dialog, '#32770', [NullString]::Value)) -ne [IntPtr]::Zero) { @@ -85,8 +120,8 @@ try { } } } - $browser, $signIn = Wait-For 'the SMB Sign in command' { Find-DialogControl 547 } - [void][FilesCommandsUi]::Post($browser, 0x111, [IntPtr]547, $signIn) + if (Find-DialogControl 541) { throw 'SMB displayed a separate browser over the file panels.' } + [void][FilesCommandsUi]::Post($main, 0x111, [IntPtr]547, [IntPtr]::Zero) $dialog, $password = Wait-For 'the SMB password field' { Find-DialogControl 559 } $empty = Render-Password $password Set-Password $password 'WWWWWWWW' @@ -100,7 +135,7 @@ try { if ([FilesCommandsUi]::Send($remember, 0xf0, [IntPtr]::Zero, [IntPtr]::Zero) -ne [IntPtr]::Zero) { throw 'Remember in Windows Credential Manager must be unchecked by default.' } - 'Verified password masking and the default credential-saving choice.' + 'Verified SMB in both file panels, Escape navigation, password masking and the default credential-saving choice.' } finally { if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() } foreach ($name in $names) { From da914168e83428dc9f162295258368f263f77113 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Thu, 26 Nov 2026 00:34:53 +0200 Subject: [PATCH 52/61] Open Recent folders in the selected file panel Refs #88 --- CMakeLists.txt | 5 + FILES-UI.md | 13 +- src/files_compare.inl | 2 +- src/files_context_menu.inl | 15 +- src/files_help.inl | 2 +- src/files_main.cpp | 200 +++++++++++++++++---------- src/files_panel_recovery.inl | 12 +- src/files_panel_rows.inl | 12 +- src/files_path_navigation.inl | 68 +++++---- src/files_properties.inl | 2 +- src/files_smb.inl | 42 ++---- tests/files_commands_ui.ps1 | 35 +++++ tests/files_recent_folders_panel.ps1 | 167 ++++++++++++++++++++++ tests/files_smb_password.ps1 | 47 ++----- 14 files changed, 434 insertions(+), 188 deletions(-) create mode 100644 tests/files_recent_folders_panel.ps1 diff --git a/CMakeLists.txt b/CMakeLists.txt index 1d0124e..7a4d090 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -239,6 +239,11 @@ add_test(NAME files-smb-password -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_smb_password.ps1" -Executable "$") set_tests_properties(files-smb-password PROPERTIES RUN_SERIAL TRUE TIMEOUT 30) +add_test(NAME files-recent-folders-panel + COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass + -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_recent_folders_panel.ps1" + -Executable "$") +set_tests_properties(files-recent-folders-panel PROPERTIES RUN_SERIAL TRUE TIMEOUT 35) add_test(NAME files-space-analyzer-layout COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_layout.ps1" diff --git a/FILES-UI.md b/FILES-UI.md index 52a01ad..bd4a220 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -709,12 +709,13 @@ Warning і початковий фокус на No. показують перший кадр. Пошкоджені та надто великі файли показують повідомлення. - **Change drive → Recent folders** у меню Alt+F1 або Alt+F2 показує - останні відвідані локальні, FTP, SFTP та LAN-папки. Повторний візит підіймає - один запис угору, порядок зберігається після перезапуску. Enter або клік - відкриває шлях у панелі, з якої викликали меню. Віддалені записи містять - шлях і ідентифікатор збереженого FTP- чи SFTP-профілю або спареного ПК. Паролі - зберігаються в захищених налаштуваннях профілів. Delete прибирає вибраний - запис із недавніх. + останні відвідані локальні, FTP, SFTP та LAN-папки у вибраній панелі. + **Enter** або подвійний клік відкриває папку в тій самій панелі. + **Delete** прибирає запис із недавніх. **Esc** повертає попередню папку. + Повторний візит підіймає один запис угору, порядок зберігається після + перезапуску. Віддалені записи містять шлях і ідентифікатор збереженого + FTP- чи SFTP-профілю або спареного ПК. Паролі зберігаються в захищених + налаштуваннях профілів. - Кнопки ← та → переходять назад і вперед в історії відповідної панелі, зокрема між локальними, FTP, SFTP та LAN-папками. Стрілка ↑, Alt+↑ та рядок `..` diff --git a/src/files_compare.inl b/src/files_compare.inl index b659784..0eac243 100644 --- a/src/files_compare.inl +++ b/src/files_compare.inl @@ -1230,7 +1230,7 @@ bool selectedComparisonFiles(CompareFile (&files)[2]) 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(panel.archive || connectionList(panel) || row==panel.rows.end() || panel.sizes[row-panel.rows.begin()]==L"Folder") + if(panel.archive || panelListsLocations(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(); diff --git a/src/files_context_menu.inl b/src/files_context_menu.inl index a6944ed..21b7c2d 100644 --- a/src/files_context_menu.inl +++ b/src/files_context_menu.inl @@ -94,9 +94,18 @@ void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen) if(!popup.handle) return; constexpr UINT openItem=1,findItems=2,newProfile=3,properties=4; const auto add=[&](UINT id,const wchar_t *label){AppendMenuW(popup.handle,MF_STRING,id,label);}; - if(panel.smb) + if(recentFolderList(panel)) { - if(panel.smb->server.empty()) + if(row!=LB_ERR) + { + add(openItem,L"Open folder"); + add(117,L"Remove from recent"); + } + add(110,L"Refresh panel"); + } + else if(panel.listing) + { + if(panel.listing->smb->server.empty()) { if(row!=LB_ERR) { @@ -147,7 +156,7 @@ void showFilesPanelContext(Panel &panel,LRESULT row,POINT screen) else if(command==findItems) findPanelFiles(owner,panel); else if(command==newProfile) { - if(panel.smb) editSmbProfile(panel,true); + if(panel.listing) editSmbProfile(panel,true); else editTransferProfile(panel,true); } else if(command==properties) showPanelItemProperties(owner,panel); diff --git a/src/files_help.inl b/src/files_help.inl index b1c2124..2339619 100644 --- a/src/files_help.inl +++ b/src/files_help.inl @@ -11,7 +11,7 @@ constexpr struct L"Press F9 to show the menu bar. Use the arrow keys to move between categories and entries. Press Enter to run the highlighted command.\r\n\r\n" L"Press F1 on a menu item for its topic. Commands → Keyboard shortcuts lists the active scheme and lets you assign extra bindings."}, {L"Locations and navigation",L"folder path history breadcrumbs drives recent bookmark directory unc", - L"Use the breadcrumb in a local or remote pane to jump to an ancestor. The folder history keeps earlier locations for that pane. Recent folders are available from the drive picker.\r\n\r\n" + L"Use the breadcrumb in a local or remote pane to jump to an ancestor. The folder history keeps earlier locations for that pane. Choose Recent folders in Change drive to see recent locations in that panel. Enter opens the selected folder, Delete removes it from recent folders, and Esc restores the previous folder.\r\n\r\n" L"Folder shortcuts open frequently used locations. In the default scheme Ctrl+0–9 recalls a digit and Ctrl+Shift+0–9 adds the current folder."}, {L"Find files",L"search filter mask results alt f7 paths subfolders", L"Find files searches from the active folder, including subfolders. Supply a filename mask such as *.md. The results show their locations and can be opened or used in file operations.\r\n\r\n" diff --git a/src/files_main.cpp b/src/files_main.cpp index 67bde20..7a3f965 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -586,10 +586,16 @@ struct RemotePanelLocation namespace smb { struct PendingConnection; } -struct SmbPanelListing +struct SmbListing { std::string serverId; std::wstring server; +}; + +struct PanelListing +{ + std::optional smb; + std::vector recent; std::vector> rows; fs::path returnSelection; }; @@ -601,7 +607,7 @@ struct Panel FolderNavigation navigation; std::optional peer; std::optional ftp; - std::optional smb; + std::optional listing; std::shared_ptr smbPending; std::optional archive; struct DirectoryWatch @@ -657,7 +663,7 @@ struct Panel std::optional archive; unsigned reconnectAttempt{}; fs::path fallbackSelection; - std::optional smb; + std::optional listing; }; struct RemoteRetry { @@ -724,11 +730,26 @@ bool transferProfileList(const Panel &panel) return panel.ftp && panel.ftp->name.empty(); } -bool connectionList(const Panel &panel) +bool recentFolderList(const Panel &panel) { - return panel.smb || transferProfileList(panel); + return panel.listing && !panel.listing->smb; } +bool panelListsLocations(const Panel &panel) +{ + return panel.listing || transferProfileList(panel); +} + +bool samePanelListing(const PanelListing &first,const PanelListing &second) +{ + if(first.smb.has_value()!=second.smb.has_value()) return false; + return !first.smb || first.smb->serverId==second.smb->serverId; +} + +void showRecentFolders(Panel &panel); +void openRecentFolder(Panel &panel); +void removeRecentFolder(Panel &panel); + void showSmbProfiles(Panel &panel); void refreshSmbPanel(Panel &panel); void enterSmbPanel(Panel &panel); @@ -748,7 +769,12 @@ FolderLocation folderLocation(const Panel &panel,const fs::path &directory) std::wstring panelLocation(const Panel &panel) { - if(panel.smb) return panel.smb->server.empty()?L"SMB":L"SMB · "+panel.smb->server; + if(recentFolderList(panel)) return L"Recent folders"; + if(panel.listing) + { + const auto &server=panel.listing->smb->server; + return server.empty()?L"SMB":L"SMB · "+server; + } if(panel.ftp) return transferProfileList(panel)?transferProtocolName(panel.ftp->protocol):panel.ftp->name+L" · "+ftpPath(panel.directory); return (panel.peer?panel.peer->name+L" · ":std::wstring{})+panel.directory.native(); @@ -765,7 +791,7 @@ DWORD effectivePanelColumns(const Panel &panel) bool hasPanelColumns(const Panel &panel) { - return detailedPanel(panel) && !panel.findOrigin && !connectionList(panel); + return detailedPanel(panel) && !panel.findOrigin && !panelListsLocations(panel); } std::wstring panelCaption(const Panel &panel) @@ -860,7 +886,6 @@ struct FolderPicker { const wchar_t *caption; std::vector locations; - bool recent{}; }; std::optional folderPicker; constexpr int defaultSizeWidth=6, defaultFontPoints=110; @@ -2265,7 +2290,7 @@ LRESULT currentPanelRow(const Panel &panel) std::vector selectedPanelPaths(const Panel &panel) { std::vector paths; - if(panel.smb) return paths; + if(panel.listing) return paths; std::set directories; visitPanelMarks(panel,[&](const fs::path &path,const FolderEntryMetadata &entry) { paths.push_back(path); @@ -2338,7 +2363,7 @@ void copyPanelNames(HWND owner) void copyPanelFiles(HWND owner,const Panel &panel) { - if(panel.peer || panel.ftp || panel.archive || panel.smb) + if(panel.peer || panel.ftp || panel.archive || panel.listing) { setStatus(L"File clipboard copy requires local files."); return; @@ -2356,7 +2381,7 @@ void copyPanelFiles(HWND owner,const Panel &panel) void copyFullPanelPath(HWND owner,const Panel &panel) { const auto row=currentPanelRow(panel); - if(row==LB_ERR || panel.sizes[row]==L"Up" || transferProfileList(panel)) return; + if(row==LB_ERR || panel.sizes[row]==L"Up" || panelListsLocations(panel)) return; const auto &path=panel.rows[row]; auto value=path.native(); if(panel.ftp) @@ -2387,7 +2412,12 @@ bool retryRemotePanel(Panel &panel,bool automatic=false,const fs::path &fallback void refreshPanel(Panel &panel) { - if(panel.smb) {refreshSmbPanel(panel);return;} + if(recentFolderList(panel)) + { + if(!retryRemotePanel(panel)) showRecentFolders(panel); + return; + } + if(panel.listing) {refreshSmbPanel(panel);return;} cancelFolderSizes(panel); if(!panel.view.automaticSizes) panel.folderSizes.clear(); updateSelectionSummary(panel); @@ -2413,7 +2443,7 @@ std::wstring powerShellPath(const fs::path &path) void insertCurrentPanelPath(bool nameOnly = false) { const auto &panel=panels[active]; - if(panel.ftp || panel.smb || panel.archive) return; + if(panel.ftp || panel.listing || panel.archive) return; const auto row=currentPanelRow(panel); if(row==LB_ERR) return; const bool up=panel.sizes[row]==L"Up"; @@ -2601,7 +2631,7 @@ bool showCommandOutput(HWND owner,const Panel &panel) if(panel.ftp && panel.ftp->protocol==TransferProtocol::sftp && !panel.ftp->id.empty()) return startSshTerminal(owner,panel); closeSshPrompt(owner); - if(panel.smb) return ensureTerminalView(owner); + if(panel.listing) return ensureTerminalView(owner); if(panel.archive) return startTerminal(owner,panel.archive->file.parent_path()); return panel.peer || panel.ftp?ensureTerminalView(owner):startTerminal(owner,panel.directory); } @@ -2641,7 +2671,7 @@ bool submitTerminalCommand(const Panel &panel,const std::wstring &value) setStatus(L"Shell commands require a local or LAN folder."); return false; } - if(panel.smb) + if(panel.listing) { setStatus(L"Open a folder before running a shell command."); return false; @@ -2930,10 +2960,15 @@ void showFileDetails(const Panel &panel) L" · Enter: Go · Esc: Back"); return; } - if(panel.smb) + if(recentFolderList(panel)) + { + setStatus(panel.rows.empty()?L"No recent folders Esc Back":L"Enter Open folder Delete Remove from recent Esc Back"); + return; + } + if(panel.listing) { if(panel.smbPending) setStatus(L"Connecting to SMB… Esc Cancel"); - else if(!panel.smb->server.empty()) + else if(!panel.listing->smb->server.empty()) setStatus(panel.rows.size()<=1?L"No visible shares Esc Back":L"Enter Open share Esc Back"); else if(panel.rows.empty()) setStatus(L"Shift+F4 New connection Esc Back"); else setStatus(L"Enter Connect Shift+F4 New Right-click for Edit, Remove or Sign in"); @@ -3169,8 +3204,8 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul auto &peer=request.peer; const auto previousDirectory=samePanelSource(panel,peer,request.ftp)?panel.directory:fs::path{}; const auto provider=peer?FolderProvider::lan:request.ftp?transferFolderProvider(request.ftp->protocol):FolderProvider::local; - const bool sameDirectory=request.smb || panel.smb? - request.smb && panel.smb && request.smb->serverId==panel.smb->serverId: + const bool sameDirectory=request.listing || panel.listing? + request.listing && panel.listing && samePanelListing(*panel.listing,*request.listing): sameFolderPath(previousDirectory,directory,provider); auto &[nextWatch,folders,files,metadata,error,opened,failure,ftpInitialDirectory,ordered,columnMetadata,archiveEntries]=scan; const bool partial=error==ERROR_CANCELLED; @@ -3242,7 +3277,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul if(panel.marked[i]) markedPaths.insert(panel.rows[i]); } const bool finding=request.find.has_value(); - const bool viewChanged=finding!=panel.findOrigin.has_value() || request.smb.has_value()!=panel.smb.has_value(); + const bool viewChanged=finding!=panel.findOrigin.has_value() || request.listing.has_value()!=panel.listing.has_value(); if(finding) { if(!panel.findOrigin) @@ -3272,32 +3307,34 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul if(mark.parent_path()==folderPathWithoutSeparator(directory)) markedPaths.insert(mark); panel.listReturnMarks.clear(); } - const bool rememberFolder=!sameDirectory && !partial && (!panel.directory.empty() || panel.smb || peer || request.ftp); + const bool returningFromListing=panel.listing && request.navigationPosition==panel.navigation.current; + const bool rememberFolder=!sameDirectory && !partial && !returningFromListing && + (!panel.directory.empty() || panel.listing || peer || request.ftp); panel.directory = directory; panel.peer=std::move(peer); panel.ftp=std::move(request.ftp); panel.archive=std::move(request.archive); - panel.smb=std::move(request.smb); + panel.listing=std::move(request.listing); if(panel.archive) panel.archive->entries=std::move(archiveEntries); if(!sameDirectory) { cancelFolderSizes(panel); panel.folderSizes.clear(); } - if(partial || finding || panel.archive || panel.smb) panel.watch.reset(); + if(partial || finding || panel.archive || panel.listing) panel.watch.reset(); else if(!sameDirectory || panel.watch.handle==INVALID_HANDLE_VALUE) { panel.watch.reset(); std::swap(panel.watch.handle,nextWatch.handle); } - const bool profiles=connectionList(panel); - if(!finding && !panel.archive && !profiles) + const bool locationList=panelListsLocations(panel); + if(!finding && !panel.archive && !locationList) { auto location=folderLocation(panel,directory); if(rememberFolder) updateRecentFolders(location,true); panel.navigation.opened(std::move(location),request.navigationPosition); } - const bool renderTree=panel.view.tree && !finding && !profiles && !panel.archive; + const bool renderTree=panel.view.tree && !finding && !locationList && !panel.archive; panel.filteredMarks.clear(); if(renderTree) replaceTreeRoot(panel,scan,sameDirectory,markedPaths); else @@ -3314,7 +3351,7 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul const auto parent=finding?fs::path{}:panel.archive?directory.parent_path(): panelParentPath(directory,!panel.peer && !panel.ftp); const bool hasParent=!parent.empty(); - const auto rowCount=panel.smb?panel.smb->rows.size():profiles?transferProfiles(panel.ftp->protocol).rows.size():finding?files.size(): + const auto rowCount=panel.listing?panel.listing->rows.size():locationList?transferProfiles(panel.ftp->protocol).rows.size():finding?files.size(): renderTree?panel.tree.branches.at(panel.tree.root).ordered.size()+hasParent:ordered.size()+hasParent; PanelRowsUpdate rows(panel,rowCount); const auto add=[&](const fs::path &path,const std::wstring &label,bool folder) @@ -3322,11 +3359,11 @@ bool applyDirectoryScan(Panel &panel,Panel::ScanRequest request,Panel::ScanResul const bool marked=markedPaths.contains(path); if(rows.add(path,label,folder,marked) && marked) panel.filteredMarks.erase(path); }; - if(panel.smb) + if(panel.listing) { - for(const auto &[path,label]:panel.smb->rows) rows.add(path,label,false,false,path==L".."); + for(const auto &[path,label]:panel.listing->rows) rows.add(path,label,false,false,path==L".."); } - else if(profiles) + else if(locationList) { const auto &connections=transferProfiles(panel.ftp->protocol).rows; for(size_t i=0;i> scanDirectoryInBackground(HWND o std::packaged_task()> task( [request=std::move(request),view=std::move(view),columns,entries=std::move(entries),stop] { - if(request.smb) + if(request.listing) { auto result=std::make_unique(); result->opened=true; @@ -3439,9 +3476,9 @@ void startDirectoryScan(Panel &panel) void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::optional peer, fs::path selection={},fs::path fallback={},std::optional ftp={}, std::optional navigationPosition={},std::optional archive={}, - unsigned reconnectAttempt=0,fs::path fallbackSelection={},std::optional smb={}) + unsigned reconnectAttempt=0,fs::path fallbackSelection={},std::optional listing={}) { - if(directory.empty() && !ftp && !smb) return; + if(directory.empty() && !ftp && !listing) return; cancelSmbConnection(panel); panel.remoteRetry.reset(); if(!panel.view.revealedFile.empty() && @@ -3451,7 +3488,7 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti cancelFolderSizes(panel); panel.scanRequest=Panel::ScanRequest{directory,std::move(selection),std::move(fallback), std::move(peer),offerElevation,statusRevision,{},std::move(ftp),{},navigationPosition, - std::move(archive),reconnectAttempt,std::move(fallbackSelection),std::move(smb)}; + std::move(archive),reconnectAttempt,std::move(fallbackSelection),std::move(listing)}; if(panel.scan.valid()) { panel.scanSuperseded=true; @@ -3463,6 +3500,20 @@ void openOn(Panel &panel,const fs::path &directory,bool offerElevation,std::opti #include "files_panel_recovery.inl" +void openPanelListing(Panel &panel,PanelListing listing,fs::path selection={}) +{ + if(panel.listing) listing.returnSelection=panel.listing->returnSelection; + else if(const auto row=currentPanelRow(panel);row!=LB_ERR) listing.returnSelection=panel.rows[row]; + openOn(panel,{},false,{},std::move(selection),{},{},{},{},0,{},std::move(listing)); +} + +void closePanelListing(Panel &panel) +{ + if(panel.navigation.history.empty()) return; + const auto position=panel.navigation.current; + openFolderLocation(panel,panel.navigation.history[position],position,panel.listing->returnSelection); +} + void collectDirectoryScans() { for(auto &panel:panels) @@ -3984,7 +4035,6 @@ LRESULT sftpDriveRow() {return lanDrivePicker?-1:ftpDriveRow()+1;} LRESULT smbDriveRow() {return lanDrivePicker?-1:sftpDriveRow()+1;} LRESULT recentDriveRow() {return lanDrivePicker?-1:smbDriveRow()+1;} LRESULT lanHeaderRow() {return recentDriveRow()+1;} -void showRecentFolders(int side); bool driveSourceRow(LRESULT row) { @@ -4089,7 +4139,11 @@ void selectDrive() activatePanel(pickerPanel); showSmbProfiles(panels[pickerPanel]); } - else if(row==recentDriveRow()) showRecentFolders(pickerPanel); + else if(row==recentDriveRow()) + { + activatePanel(pickerPanel); + showRecentFolders(panels[pickerPanel]); + } else if(remote!=remoteDriveRows.end()) { const auto &choice=remote->second; @@ -4100,26 +4154,6 @@ void selectDrive() LRESULT CALLBACK pickerKeys(HWND window, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR) { - if(folderPicker && folderPicker->recent && msg==WM_KEYDOWN && wp==VK_DELETE) - { - const auto row=SendMessageW(window,LB_GETCURSEL,0,0); - if(!selectablePickerRow(row)) return 0; - auto &paths=folderPicker->locations; - if(!updateRecentFolders(paths[row],false)) - { - setStatus(L"Could not remove the recent folder."); - return 0; - } - paths.erase(paths.begin()+row); - SendMessageW(window,LB_DELETESTRING,row,0); - if(paths.empty()) - { - hidePicker(); - setStatus(L"No recent folders."); - } - else SendMessageW(window,LB_SETCURSEL,std::min(row,static_cast(paths.size()-1)),0); - return 0; - } if(folderPicker && msg==WM_LBUTTONUP) { const auto hit=SendMessageW(window,LB_ITEMFROMPOINT,0,lp); @@ -4614,7 +4648,7 @@ void openPanelFile(const Panel &panel, const fs::path &file, const wchar_t *verb void openSelectedWithSystem(const Panel &panel) { - if(panel.ftp || panel.smb || panel.archive) return; + if(panel.ftp || panel.listing || panel.archive) return; const auto row=currentPanelRow(panel); if(row==LB_ERR) return; if(panel.peer) @@ -4650,7 +4684,7 @@ void refreshQuickView(const Panel &panel) { if(!quickViewWindow || &panel!=&panels[quickViewSource]) return; const auto row=currentPanelRow(panel); - const bool file=!panel.peer && !panel.ftp && !panel.smb && !panel.archive && row!=LB_ERR && + const bool file=!panel.peer && !panel.ftp && !panel.listing && !panel.archive && row!=LB_ERR && panel.sizes[row]!=L"Folder" && panel.sizes[row]!=L"Up"; const auto path=file?panel.rows[row]:fs::path{}; if(file && ks::files::isImagePath(path) && !quickImageWindow) @@ -4736,7 +4770,7 @@ void openArchiveText(const Panel &panel,const fs::path &path,bool hex=false) void openSelectedText(const Panel &panel, bool edit, bool external,bool hex) { - if(connectionList(panel)) return; + if(panelListsLocations(panel)) return; const auto row=currentPanelRow(panel); if(row==LB_ERR || panel.sizes[row]==L"Folder" || panel.sizes[row]==L"Up") return; if(panel.archive) @@ -4773,7 +4807,8 @@ void openSelectedText(const Panel &panel, bool edit, bool external,bool hex) void enter(Panel &panel) { - if(panel.smb) {enterSmbPanel(panel);return;} + if(recentFolderList(panel)) {openRecentFolder(panel);return;} + if(panel.listing) {enterSmbPanel(panel);return;} const auto row=currentPanelRow(panel); if(row!=LB_ERR) { @@ -6839,7 +6874,7 @@ void copySelection(HWND owner,Panel &source,Panel &destination,bool move,std::ve { const auto sourceFtp=source.ftp; const bool ftpRename=move && sourceFtp && !transferProfileList(source); - if(source.smb || (destination.smb && !ftpRename && !renameHere)) + if(source.listing || (destination.listing && !ftpRename && !renameHere)) { setStatus(L"Open a folder before copying or moving files."); return; @@ -7355,7 +7390,7 @@ void deleteSelection(HWND owner,Panel &panel,bool permanent) setStatus(L"Wait for the search to finish."); return; } - if(transferProfileList(panel)) return; + if(panelListsLocations(panel)) return; if(copyInProgress) return; const auto ftp=panel.ftp; permanent=permanent || ftp.has_value(); @@ -7592,7 +7627,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.smb || panel.findOrigin) + if(panel.peer || panel.ftp || panel.listing || panel.findOrigin) { setStatus(L"Open a local folder before pasting files."); return true; @@ -8044,7 +8079,8 @@ void runFilesKeyCommand(HWND owner,int side,FilesKey command) case FilesKey::Edit: { const bool edit=command==FilesKey::Edit; - if(panel.smb) + if(recentFolderList(panel)) break; + if(panel.listing) { if(edit) editSmbProfile(panel,false); break; @@ -8062,7 +8098,8 @@ void runFilesKeyCommand(HWND owner,int side,FilesKey command) case FilesKey::Move: copySelection(owner,panel,panels[1-side],command==FilesKey::Move); break; case FilesKey::Mkdir: makeFolder(owner,panel); break; case FilesKey::Delete: - if(panel.smb) removeSmbProfile(panel); + if(recentFolderList(panel)) removeRecentFolder(panel); + else if(panel.listing) removeSmbProfile(panel); else deleteSelection(owner,panel,false); break; case FilesKey::Exit: SendMessageW(owner,WM_CLOSE,0,0); break; @@ -8125,7 +8162,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT { auto &panel=panels[index]; const auto row=panelRowAt(window,screen,SendMessageW(window,LB_GETTOPINDEX,0,0),panel.rows.size()); - if(row!=LB_ERR && panel.sizes[row]!=L"Up" && !connectionList(panel)) + if(row!=LB_ERR && panel.sizes[row]!=L"Up" && !panelListsLocations(panel)) { closePanelSearch(); SetFocus(window); @@ -8586,7 +8623,7 @@ void searchPanelByPrefix(HWND window,wchar_t character) { if(panel.sizes[row]==L"Up") continue; const auto *profiles=transferProfileList(panel)?&transferProfiles(panel.ftp->protocol).rows:nullptr; - const auto name=panel.smb && rowrows.size()?panel.smb->rows[row].second: + const auto name=panel.listing && rowrows.size()?panel.listing->rows[row].second: profiles && rowsize()?(*profiles)[row].name:panel.rows[row].filename().native(); if(name.size()caption,teal,colors[Text],mono, - folderPicker->recent?L"Del Remove":nullptr); + paintDialogFrameCaptions(item.hDC,item.rcItem,box,folderPicker->caption,teal,colors[Text],mono); const auto list=item.hwndItem==pickerFrame?picker:completionList; paintScrollPosition(item.hwndItem,item.hDC,list,colors[Dialog]); DeleteObject(border); @@ -9518,13 +9554,13 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) const auto row=currentPanelRow(panel); auto cursor=panel.archive?panel.archive->file.native(): row==LB_ERR?std::wstring{}:panel.rows[row].native(); - if(panel.smb) + if(panel.listing) { if(panel.navigation.history.empty()) continue; const auto &previous=panel.navigation.history[panel.navigation.current]; if(previous.provider!=FolderProvider::local) continue; path=previous.directory.native(); - cursor=panel.smb->returnSelection.native(); + cursor=panel.listing->returnSelection.native(); } if(!path.empty()) RegSetKeyValueW(HKEY_CURRENT_USER,schemeKey,panelPathKeys[i],REG_SZ,path.c_str(), @@ -9688,6 +9724,16 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) continue; } if(!copyInProgress && handlePanelSearchKey(window,message)) continue; + if(message.message==WM_KEYDOWN && message.wParam==VK_DELETE && !terminalVisible && + !(GetKeyState(VK_CONTROL)&0x8000) && !(GetKeyState(VK_SHIFT)&0x8000) && + !(GetKeyState(VK_MENU)&0x8000) && commandLineAvailable(window) && + (message.hwnd==panels[active].list || + (message.hwnd==terminalInput && !GetWindowTextLengthW(terminalInput))) && + recentFolderList(panels[active])) + { + if(!(message.lParam&(1LL<<30))) removeRecentFolder(panels[active]); + continue; + } if(message.message==WM_KEYDOWN && message.wParam==VK_ESCAPE && !terminalVisible && commandLineAvailable(window) && (message.hwnd==terminalInput || message.hwnd==panels[0].list || message.hwnd==panels[1].list)) @@ -9698,9 +9744,10 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) if(!panel.scanSuperseded) stopDirectoryScan(); continue; } - if(panel.smb && !panel.scanRequest && !GetWindowTextLengthW(terminalInput)) + if(panel.listing && !panel.scanRequest && !GetWindowTextLengthW(terminalInput)) { - backSmbPanel(panel); + if(recentFolderList(panel)) closePanelListing(panel); + else backSmbPanel(panel); continue; } if(panel.archive && !panel.scanRequest) @@ -9816,7 +9863,8 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) if(!(message.lParam & (1LL<<30)) && commandLineAvailable(window)) { auto &panel=panels[active]; - if(panel.smb) editSmbProfile(panel,true); + if(recentFolderList(panel)) continue; + if(panel.listing) editSmbProfile(panel,true); else if(transferProfileList(panel)) editTransferProfile(panel,true); else openOrCreateText(window,panel); } diff --git a/src/files_panel_recovery.inl b/src/files_panel_recovery.inl index b6d5509..e85c479 100644 --- a/src/files_panel_recovery.inl +++ b/src/files_panel_recovery.inl @@ -58,20 +58,20 @@ bool retryRemotePanel(Panel &panel,bool automatic,const fs::path &fallback) return true; } -void openFolderLocation(Panel &panel,const FolderLocation &location,std::optional position={}) +void openFolderLocation(Panel &panel,const FolderLocation &location,std::optional position={},fs::path selection={}) { if(location.directory.empty()) return; if(location.provider==FolderProvider::local) { - openOn(panel,location.directory,true,{},{},{},{},position); + openOn(panel,location.directory,true,{},std::move(selection),{},{},position); return; } if(location.sameSource(folderLocation(panel,panel.directory))) { - openOn(panel,location.directory,false,panel.peer,{},{},panel.ftp,position); + openOn(panel,location.directory,false,panel.peer,std::move(selection),{},panel.ftp,position); return; } - RemotePanelLocation remote{location.directory,{},{},{},position}; + RemotePanelLocation remote{location.directory,std::move(selection),{},{},position}; if(isTransferFolder(location.provider)) { remote.ftpProfile=location.id; @@ -124,11 +124,11 @@ void saveFtpPanelLocation(const Panel &panel,int index) location=panel.remoteRetry->location; else if(panel.scanRequest && panel.scanRequest->ftp && panel.scanRequest->ftp->protocol==TransferProtocol::ftp) location={panel.scanRequest->directory,panel.scanRequest->selection,panel.scanRequest->ftp->id}; - else if(panel.smb && !panel.navigation.history.empty()) + else if(panel.listing && !panel.navigation.history.empty()) { const auto &previous=panel.navigation.history[panel.navigation.current]; if(previous.provider==FolderProvider::ftp) - location={previous.directory,panel.smb->returnSelection,previous.id}; + location={previous.directory,panel.listing->returnSelection,previous.id}; } const auto key=ftpPanelLocationKeys[index]; diff --git a/src/files_panel_rows.inl b/src/files_panel_rows.inl index abb1aaa..13ceec8 100644 --- a/src/files_panel_rows.inl +++ b/src/files_panel_rows.inl @@ -2,7 +2,7 @@ class PanelRowsUpdate { public: PanelRowsUpdate(Panel &panel,size_t count) : panel(panel),visible(IsWindowVisible(panel.list)), - profiles(connectionList(panel)) + locationList(panelListsLocations(panel)) { if(visible) SendMessageW(panel.list,WM_SETREDRAW,FALSE,0); panel.rows.clear(); @@ -33,10 +33,10 @@ public: } panel.marked.push_back(!up && marked); const auto found=panel.metadata.find(path); - const auto entry=up || profiles || found==panel.metadata.end()?FolderEntryMetadata{}:found->second; + const auto entry=up || locationList || found==panel.metadata.end()?FolderEntryMetadata{}:found->second; panel.dimmed.push_back((entry.attributes&(FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_HIDDEN))!=0); - panel.sizes.push_back(up?L"Up":profiles?L"":folder?L"Folder":std::to_wstring(entry.size)); - if(!up && !profiles) + panel.sizes.push_back(up?L"Up":locationList?L"":folder?L"Folder":std::to_wstring(entry.size)); + if(!up && !locationList) { auto &longest=panel.longestColumn; longest[sizeColumn]=std::max(longest[sizeColumn],panel.sizes.back().size()); @@ -63,7 +63,7 @@ public: private: Panel &panel; - bool visible,profiles; + bool visible,locationList; }; bool treePanelActive(const Panel &panel) @@ -120,7 +120,7 @@ void visitPanelMarks(const Panel &panel,const Visitor &visit) } return; } - if(connectionList(panel)) return; + if(panelListsLocations(panel)) return; for(size_t i=0;i locations, - RECT anchor,bool recent=false) + RECT anchor) { hidePicker(); showMenu(false); commandPicker=false; pickerPanel=side; - folderPicker=FolderPicker{caption,std::move(locations),recent}; + folderPicker=FolderPicker{caption,std::move(locations)}; SendMessageW(picker,LB_RESETCONTENT,0,0); size_t longest=wcslen(caption); for(const auto &location:folderPicker->locations) { auto label=isTransferFolder(location.provider)?ftpPath(location.directory):location.directory.native(); - if(recent && location.provider!=FolderProvider::local) - { - const auto &source=location.label; - const auto kind=isTransferFolder(location.provider)?transferProtocolName(folderTransferProtocol(location.provider)):L"LAN"; - label=std::wstring(kind)+L" · "+(source.empty()?std::wstring{}:source+L" · ")+label; - } longest=std::max(longest,label.size()); SendMessageW(picker,LB_ADDSTRING,0,reinterpret_cast(label.c_str())); } @@ -356,26 +350,52 @@ void showFolderPicker(HWND owner,int side,const wchar_t *caption,std::vectorname; + label=ftpPath(location.directory); + } + if(!location.label.empty()) label=location.label+L" · "+label; + label=std::wstring(kind)+L" · "+label; + } + listing.rows.emplace_back(std::to_wstring(i),std::move(label)); + } + openPanelListing(panel,std::move(listing)); +} + +void openRecentFolder(Panel &panel) +{ + const auto row=currentPanelRow(panel); + if(row!=LB_ERR && !panel.scan.valid()) + openFolderLocation(panel,panel.listing->recent[row]); +} + +void removeRecentFolder(Panel &panel) +{ + const auto row=currentPanelRow(panel); + if(row==LB_ERR || panel.scan.valid()) return; + if(!updateRecentFolders(panel.listing->recent[row],false)) + { + setStatus(L"Could not remove the recent folder."); return; } - const auto owner=GetParent(picker); - RECT anchor{}; - GetWindowRect(panels[side].path,&anchor); - MapWindowPoints(nullptr,owner,reinterpret_cast(&anchor),2); - for(auto &location:locations) - { - if(!isTransferFolder(location.provider)) continue; - const auto protocol=folderTransferProtocol(location.provider); - if(loadTransferProfiles(protocol)) - if(const auto *profile=findTransferProfile(location.id,protocol)) location.label=profile->name; - } - showFolderPicker(owner,side,L"Recent folders",std::move(locations),anchor,true); + for(auto &other:panels) + if(recentFolderList(other) && !other.scan.valid()) showRecentFolders(other); } void showHiddenPathParts(HWND window,int side,const PathPart &part) diff --git a/src/files_properties.inl b/src/files_properties.inl index 360aa44..00a8311 100644 --- a/src/files_properties.inl +++ b/src/files_properties.inl @@ -129,7 +129,7 @@ void showReadOnlyProperties(HWND owner,const ItemProperties &properties,const st bool panelItemPropertiesAvailable(const Panel &panel) { const auto row=currentPanelRow(panel); - return row!=LB_ERR && panel.sizes[row]!=L"Up" && !connectionList(panel); + return row!=LB_ERR && panel.sizes[row]!=L"Up" && !panelListsLocations(panel); } void showSourceItemProperties(HWND owner,const Panel &panel,const fs::path &path,ItemProperties properties) diff --git a/src/files_smb.inl b/src/files_smb.inl index 756233d..753e25f 100644 --- a/src/files_smb.inl +++ b/src/files_smb.inl @@ -418,31 +418,24 @@ std::optional findProfile(const fs::path &id) std::optional selectedProfile(const Panel &panel) { - if(!panel.smb || !panel.smb->server.empty() || panel.scan.valid() || panel.smbPending) return {}; + if(!panel.listing || !panel.listing->smb || !panel.listing->smb->server.empty() || panel.scan.valid() || panel.smbPending) return {}; const auto row=currentPanelRow(panel); return row==LB_ERR?std::nullopt:findProfile(panel.rows[row]); } -void openListing(Panel &panel,SmbPanelListing listing,fs::path selection={}) -{ - if(panel.smb) listing.returnSelection=panel.smb->returnSelection; - else if(const auto row=currentPanelRow(panel);row!=LB_ERR) listing.returnSelection=panel.rows[row]; - openOn(panel,{},false,{},std::move(selection),{},{},{},{},0,{},std::move(listing)); -} - void showProfiles(Panel &panel,const std::vector &profiles,fs::path selection={}) { - SmbPanelListing listing; + PanelListing listing{SmbListing{}}; listing.rows.reserve(profiles.size()); for(const auto &profile:profiles) listing.rows.emplace_back(ks::wide(profile.id),profile.name+L" · "+profileAddress(profile)); - openListing(panel,std::move(listing),std::move(selection)); + openPanelListing(panel,std::move(listing),std::move(selection)); } void refreshProfiles(Panel &panel,const std::vector &profiles,fs::path selection={}) { for(auto &other:panels) - if(other.smb && other.smb->server.empty() && !other.smbPending && !other.scan.valid()) + if(other.listing && other.listing->smb && other.listing->smb->server.empty() && !other.smbPending && !other.scan.valid()) showProfiles(other,profiles,&other==&panel?selection:fs::path{}); } @@ -493,8 +486,8 @@ void showSmbProfiles(Panel &panel) void refreshSmbPanel(Panel &panel) { if(panel.scan.valid() || panel.smbPending) return; - if(panel.smb->server.empty()) showSmbProfiles(panel); - else if(auto profile=smb::findProfile(ks::wide(panel.smb->serverId));profile && profile->target.folder.empty()) + if(panel.listing->smb->server.empty()) showSmbProfiles(panel); + else if(auto profile=smb::findProfile(ks::wide(panel.listing->smb->serverId));profile && profile->target.folder.empty()) smb::openProfile(panel,std::move(*profile),false); else showSmbProfiles(panel); } @@ -506,20 +499,15 @@ void backSmbPanel(Panel &panel) cancelSmbConnection(panel); setStatus(L"SMB connection canceled."); } - else if(!panel.smb->server.empty()) smb::showProfiles(panel,smb::readProfiles(),ks::wide(panel.smb->serverId)); - else if(!panel.navigation.history.empty()) - { - const auto &location=panel.navigation.history[panel.navigation.current]; - if(location.provider==FolderProvider::local) - openOn(panel,location.directory,false,{},panel.smb->returnSelection); - else openFolderLocation(panel,location,panel.navigation.current); - } + else if(!panel.listing->smb->server.empty()) + smb::showProfiles(panel,smb::readProfiles(),ks::wide(panel.listing->smb->serverId)); + else closePanelListing(panel); } void enterSmbPanel(Panel &panel) { if(panel.scan.valid() || panel.smbPending) return; - if(panel.smb->server.empty()) + if(panel.listing->smb->server.empty()) { if(auto profile=smb::selectedProfile(panel)) smb::openProfile(panel,std::move(*profile),false); return; @@ -528,12 +516,12 @@ void enterSmbPanel(Panel &panel) if(row==LB_ERR) return; const auto &name=panel.rows[row]; if(name==L"..") backSmbPanel(panel); - else openOn(panel,fs::path(panel.smb->server+L"\\"+name.native()),false,{}); + else openOn(panel,fs::path(panel.listing->smb->server+L"\\"+name.native()),false,{}); } void editSmbProfile(Panel &panel,bool create) { - if(!panel.smb || !panel.smb->server.empty() || panel.smbPending || panel.scan.valid()) return; + if(!panel.listing || !panel.listing->smb || !panel.listing->smb->server.empty() || panel.smbPending || panel.scan.valid()) return; const auto profile=create?std::optional{smb::Profile{}}:smb::selectedProfile(panel); if(!profile) return; smb::EditProfile edit{*profile}; @@ -598,11 +586,11 @@ void collectSmbConnections(HWND owner) if(!result.folder.empty()) openOn(panel,result.folder,false,{}); else { - SmbPanelListing listing{profile.id,profile.target.server}; + PanelListing listing{SmbListing{profile.id,profile.target.server}}; listing.rows.emplace_back(L"..",L".."); for(const auto &share:result.shares) listing.rows.emplace_back(share,L"["+share+L"]"); - const auto selectFirst=profile.id!=panel.smb->serverId && !result.shares.empty(); - smb::openListing(panel,std::move(listing),selectFirst?fs::path(result.shares.front()):fs::path{}); + const auto selectFirst=profile.id!=panel.listing->smb->serverId && !result.shares.empty(); + openPanelListing(panel,std::move(listing),selectFirst?fs::path(result.shares.front()):fs::path{}); } } } diff --git a/tests/files_commands_ui.ps1 b/tests/files_commands_ui.ps1 index 09d2eaf..9936666 100644 --- a/tests/files_commands_ui.ps1 +++ b/tests/files_commands_ui.ps1 @@ -48,6 +48,41 @@ function Wait-For([string]$Name, [scriptblock]$Condition) { throw "Timed out waiting for $Name." } +function Read-FilesList([IntPtr]$List) { + $count = [FilesCommandsUi]::Send($List, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() + for ($row = 0; $row -lt $count; ++$row) { + $length = [FilesCommandsUi]::Send($List, 394, [IntPtr]$row, [IntPtr]::Zero).ToInt32() + if ($length -lt 0) { throw "Could not read row $row." } + $label = [Text.StringBuilder]::new($length + 1) + [void][FilesCommandsUi]::Read($List, 393, [IntPtr]$row, $label) + $label.ToString() + } +} + +function Select-FilesListRow([IntPtr]$List, [string]$Label) { + $selection = [array]::IndexOf(@(Read-FilesList $List), $Label) + if ($selection -lt 0) { throw "Missing row '$Label'." } + [void][FilesCommandsUi]::Send($List, 390, [IntPtr]$selection, [IntPtr]::Zero) +} + +function Open-FilesSource([IntPtr]$Window, [int]$Side, [string]$Source) { + $menu = if ($Side -eq 0) { 130 } else { 134 } + $picker = [FilesCommandsUi]::GetDlgItem($Window, 121) + [void][FilesCommandsUi]::Post($Window, 0x111, [IntPtr]$menu, [IntPtr]::Zero) + $entry = Wait-For "Change drive in panel ${Side}'s menu" { + if ([FilesCommandsUi]::IsWindowVisible($picker)) { + Read-FilesList $picker | Where-Object { $_ -like '*Change drive*' } | Select-Object -First 1 + } + } + Select-FilesListRow $picker $entry + [void][FilesCommandsUi]::Post($Window, 0x111, [IntPtr](0x20000 + 121), $picker) + [void](Wait-For "$Source in panel ${Side}'s source picker" { + [FilesCommandsUi]::IsWindowVisible($picker) -and (Read-FilesList $picker) -contains $Source + }) + Select-FilesListRow $picker $Source + [void][FilesCommandsUi]::Post($Window, 0x111, [IntPtr](0x20000 + 121), $picker) +} + function Invoke-FilesCommand([IntPtr]$Window, [string]$LabelPattern) { [void][FilesCommandsUi]::Post($Window, 273, [IntPtr]132, [IntPtr]::Zero) $picker = [FilesCommandsUi]::GetDlgItem($Window, 121) diff --git a/tests/files_recent_folders_panel.ps1 b/tests/files_recent_folders_panel.ps1 new file mode 100644 index 0000000..0cc9c8c --- /dev/null +++ b/tests/files_recent_folders_panel.ps1 @@ -0,0 +1,167 @@ +param( + [Parameter(Mandatory)][string]$Executable, + [string]$PreferenceKey = 'Software\KSwitcher\Files', + [string]$Screenshot, + [int]$FtpPort +) + +$ErrorActionPreference = 'Stop' +. "$PSScriptRoot/files_commands_ui.ps1" + +function Read-Caption([IntPtr]$Control) { + $label = [Text.StringBuilder]::new(1024) + [void][FilesCommandsUi]::Read($Control, 13, [IntPtr]$label.Capacity, $label) + $label.ToString() +} + +function Test-Rows([IntPtr]$List, [string[]]$Expected) { + (@(Read-FilesList $List) -join [char]10) -ceq ($Expected -join [char]10) +} + +function Send-PanelKey([IntPtr]$List, [int]$Key) { + [void][FilesCommandsUi]::Post($List, 0x100, [IntPtr]$Key, [IntPtr]::Zero) +} + +function Save-FilesWindow([IntPtr]$Window, [string]$Destination) { + Add-Type -AssemblyName System.Drawing + $bounds = [FilesCommandsUi+Rect]::new() + if (![FilesCommandsUi]::GetClientRect($Window, [ref]$bounds)) { throw 'Could not locate the Files window.' } + $bitmap = [Drawing.Bitmap]::new($bounds.Right, $bounds.Bottom) + try { + $graphics = [Drawing.Graphics]::FromImage($bitmap) + try { + $dc = $graphics.GetHdc() + try { + if (![FilesCommandsUi]::PrintWindow($Window, $dc, 3)) { throw 'Could not render the Files window.' } + } finally { $graphics.ReleaseHdc($dc) } + } finally { $graphics.Dispose() } + $bitmap.Save($Destination, [Drawing.Imaging.ImageFormat]::Png) + } finally { $bitmap.Dispose() } +} + +$exe = (Resolve-Path -LiteralPath $Executable).Path +$root = [IO.Directory]::CreateTempSubdirectory('ks-recent-folders-').FullName +$preferences = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey($PreferenceKey) +$names = 'RecentFolders', 'FtpProfiles', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', + 'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement' +$saved = @{} +foreach ($name in $names) { + if ($name -in $preferences.GetValueNames()) { + $saved[$name] = @($preferences.GetValue($name), $preferences.GetValueKind($name)) + } +} + +$process = $null +try { + foreach ($folder in 'left', 'right', 'destination', 'remove') { + [void][IO.Directory]::CreateDirectory((Join-Path $root $folder)) + } + $leftFolder = Join-Path $root 'left' + $rightFolder = Join-Path $root 'right' + $destinationFolder = Join-Path $root 'destination' + $removeFolder = Join-Path $root 'remove' + [IO.File]::WriteAllText((Join-Path $leftFolder 'left-marker.txt'), 'left file') + [IO.File]::WriteAllText((Join-Path $rightFolder 'right-marker.txt'), 'right file') + [IO.File]::WriteAllText((Join-Path $destinationFolder 'opened-marker.txt'), 'existing folder') + + $ftpId = [guid]::NewGuid().ToString('N') + if ($FtpPort) { + $ftpProfile = @(@{id=$ftpId; name='Local FTP'; host='127.0.0.1'; port=$FtpPort; user=''; secret=@()}) + $preferences.SetValue('FtpProfiles', [Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $ftpProfile -Compress)), 'Binary') + } + $entries = @($destinationFolder, @{source='ftp'; id=$ftpId; label='Local FTP'; path='\documents'}, $removeFolder) + $ftpLabel = 'FTP · Local FTP · /documents' + $preferences.SetValue('RecentFolders', [Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $entries -Compress)), 'Binary') + $preferences.SetValue('LeftPath', $leftFolder, 'String') + $preferences.SetValue('RightPath', $rightFolder, 'String') + $preferences.SetValue('LeftCursor', (Join-Path $leftFolder 'left-marker.txt'), 'String') + foreach ($name in 'RightCursor', 'LeftFtpLocation', 'RightFtpLocation', 'WindowPlacement') { + $preferences.DeleteValue($name, $false) + } + + $process = Start-Process -FilePath $exe -WindowStyle Hidden -PassThru + $window = Wait-For 'the Files window' { + $candidate = [IntPtr]::Zero + while (($candidate = [FilesCommandsUi]::FindWindowEx([IntPtr]::Zero, $candidate, 'KSwitcher.Files', [NullString]::Value)) -ne [IntPtr]::Zero) { + [uint32]$owner = 0 + [void][FilesCommandsUi]::GetWindowThreadProcessId($candidate, [ref]$owner) + if ($owner -eq $process.Id) { return $candidate } + } + } + if ($Screenshot) { [void][FilesCommandsUi]::SetWindowPos($window, 0, 80, 60, 1380, 720, 20) } + [void][FilesCommandsUi]::ShowWindow($window, 4) + $picker = [FilesCommandsUi]::GetDlgItem($window, 121) + $left = [FilesCommandsUi]::GetDlgItem($window, 102) + $right = [FilesCommandsUi]::GetDlgItem($window, 103) + $leftPath = [FilesCommandsUi]::GetDlgItem($window, 142) + $rightPath = [FilesCommandsUi]::GetDlgItem($window, 143) + [void](Wait-For 'both initial folders' { + (Read-Caption $leftPath) -eq $leftFolder -and (Read-Caption $rightPath) -eq $rightFolder + }) + $leftBefore = @(Read-FilesList $left) + $rightBefore = @(Read-FilesList $right) + + Open-FilesSource $window 0 'Recent folders' + [void](Wait-For 'recent folders in the left panel' { + (Read-Caption $leftPath) -ceq 'Recent folders' -and + (Test-Rows $left @($destinationFolder, $ftpLabel, $removeFolder)) + }) + if ([FilesCommandsUi]::IsWindowVisible($picker) -or !(Test-Rows $right $rightBefore)) { + throw 'Recent folders opened a popup or modified the right panel.' + } + if ($Screenshot) { Save-FilesWindow $window $Screenshot } + + Select-FilesListRow $left $removeFolder + Send-PanelKey $left 46 + [void](Wait-For 'the recent entry to be removed' { Test-Rows $left @($destinationFolder, $ftpLabel) }) + if (!(Test-Path -LiteralPath $removeFolder -PathType Container)) { throw 'Delete removed the underlying folder.' } + Send-PanelKey $left 27 + [void](Wait-For 'Escape to restore the left panel' { + (Read-Caption $leftPath) -eq $leftFolder -and (Test-Rows $left $leftBefore) + }) + $row = [FilesCommandsUi]::Send($left, 392, 0, 0).ToInt32() + if ($row -lt 0 -or $leftBefore[$row] -ne 'left-marker.txt') { throw 'Escape did not restore the file cursor.' } + + Open-FilesSource $window 1 'Recent folders' + [void](Wait-For 'updated recent folders in the right panel' { + (Read-Caption $rightPath) -ceq 'Recent folders' -and (Test-Rows $right @($destinationFolder, $ftpLabel)) + }) + if ([FilesCommandsUi]::IsWindowVisible($picker) -or !(Test-Rows $left $leftBefore)) { + throw 'Recent folders opened a popup or modified the left panel.' + } + Select-FilesListRow $right $destinationFolder + Send-PanelKey $right 13 + [void](Wait-For 'the local folder to open on the right' { + (Read-Caption $rightPath) -eq $destinationFolder -and (Read-FilesList $right) -contains 'opened-marker.txt' + }) + + if ($FtpPort) { + Open-FilesSource $window 0 'Recent folders' + [void](Wait-For 'the FTP recent entry' { (Read-FilesList $left) -contains $ftpLabel }) + Select-FilesListRow $left $ftpLabel + Send-PanelKey $left 13 + [void](Wait-For 'the FTP directory to open on the left' { + (Read-Caption $leftPath) -ceq 'Local FTP · /documents' -and + (Read-FilesList $left) -contains 'ftp-marker.txt' + }) + if ((Read-Caption $rightPath) -ne $destinationFolder) { throw 'Opening FTP modified the right panel.' } + } + + [void][FilesCommandsUi]::Post($window, 16, 0, 0) + if (!$process.WaitForExit(5000)) { throw 'Files did not close.' } + $recorded = [Text.Encoding]::UTF8.GetString($preferences.GetValue('RecentFolders')) | ConvertFrom-Json + if ($recorded -contains $removeFolder) { throw 'The remove action was not persisted.' } + 'Verified in-panel Recent folders, deletion, cursor restoration and folder navigation.' +} finally { + if ($process -and !$process.HasExited) { Stop-Process -Id $process.Id; $process.WaitForExit() } + foreach ($name in $names) { + if ($saved.ContainsKey($name)) { $preferences.SetValue($name, $saved[$name][0], $saved[$name][1]) } + else { $preferences.DeleteValue($name, $false) } + } + $preferences.Dispose() + $temp = (Resolve-Path -LiteralPath ([IO.Path]::GetTempPath())).Path.TrimEnd('\') + $resolved = (Resolve-Path -LiteralPath $root).Path + if ((Split-Path -Parent $resolved) -eq $temp -and (Split-Path -Leaf $resolved) -like 'ks-recent-folders-*') { + Remove-Item -LiteralPath $resolved -Recurse -Force + } +} diff --git a/tests/files_smb_password.ps1 b/tests/files_smb_password.ps1 index 6546419..9414449 100644 --- a/tests/files_smb_password.ps1 +++ b/tests/files_smb_password.ps1 @@ -61,53 +61,26 @@ try { } } [void][FilesCommandsUi]::ShowWindow($main, 4) - $picker = [FilesCommandsUi]::GetDlgItem($main, 121) - function Read-List([IntPtr]$List) { - $count = [FilesCommandsUi]::Send($List, 395, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() - for ($row = 0; $row -lt $count; ++$row) { - $label = [Text.StringBuilder]::new(256) - [void][FilesCommandsUi]::Read($List, 393, [IntPtr]$row, $label) - $label.ToString() - } - } function Same-Rows($First, $Second) { ($First -join [char]10) -ceq ($Second -join [char]10) } - function Open-Smb([int]$Side) { - $menu = if ($Side -eq 0) { 130 } else { 134 } - [void][FilesCommandsUi]::Post($main, 0x111, [IntPtr]$menu, [IntPtr]::Zero) - [void](Wait-For "Change drive in panel ${Side}'s menu" { - [FilesCommandsUi]::IsWindowVisible($picker) -and [bool]((Read-List $picker) -like '*Change drive*') - }) - $options = @(Read-List $picker) - $selection = [array]::IndexOf($options, ($options -like '*Change drive*' | Select-Object -First 1)) - [void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$selection, [IntPtr]::Zero) - [void][FilesCommandsUi]::Post($main, 0x111, [IntPtr](0x20000 + 121), $picker) - [void](Wait-For "SMB in panel ${Side}'s source picker" { - [FilesCommandsUi]::IsWindowVisible($picker) -and (Read-List $picker) -contains 'SMB' - }) - $selection = [array]::IndexOf(@(Read-List $picker), 'SMB') - if ($selection -lt 0) { throw 'SMB was missing from Change drive.' } - [void][FilesCommandsUi]::Send($picker, 390, [IntPtr]$selection, [IntPtr]::Zero) - [void][FilesCommandsUi]::Post($main, 0x111, [IntPtr](0x20000 + 121), $picker) - } $left = [FilesCommandsUi]::GetDlgItem($main, 102) $right = [FilesCommandsUi]::GetDlgItem($main, 103) - [void](Wait-For 'both local panels' { @(Read-List $left).Count -gt 0 -and @(Read-List $right).Count -gt 0 }) - $leftBefore = @(Read-List $left) - $rightBefore = @(Read-List $right) - Open-Smb 0 + [void](Wait-For 'both local panels' { @(Read-FilesList $left).Count -gt 0 -and @(Read-FilesList $right).Count -gt 0 }) + $leftBefore = @(Read-FilesList $left) + $rightBefore = @(Read-FilesList $right) + Open-FilesSource $main 0 'SMB' [void](Wait-For 'the SMB profile in the left file panel' { - (Read-List $left) -like 'Render fixture*' + (Read-FilesList $left) -like 'Render fixture*' }) - if (!(Same-Rows $rightBefore @(Read-List $right))) { throw 'Opening SMB on the left changed the right panel.' } + if (!(Same-Rows $rightBefore @(Read-FilesList $right))) { throw 'Opening SMB on the left changed the right panel.' } [void][FilesCommandsUi]::Post($left, 0x100, [IntPtr]27, [IntPtr]::Zero) - [void](Wait-For 'Escape to return to the left folder' { Same-Rows $leftBefore @(Read-List $left) }) - Open-Smb 1 + [void](Wait-For 'Escape to return to the left folder' { Same-Rows $leftBefore @(Read-FilesList $left) }) + Open-FilesSource $main 1 'SMB' [void](Wait-For 'the SMB profile in the right file panel' { - (Read-List $right) -like 'Render fixture*' + (Read-FilesList $right) -like 'Render fixture*' }) - if (!(Same-Rows $leftBefore @(Read-List $left))) { throw 'Opening SMB on the right changed the left panel.' } + if (!(Same-Rows $leftBefore @(Read-FilesList $left))) { throw 'Opening SMB on the right changed the left panel.' } function Find-DialogControl([int]$Id) { $dialog = [IntPtr]::Zero From 5194e2b621fefa664fb9193b08cd96d97d01a777 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Thu, 26 Nov 2026 00:37:46 +0200 Subject: [PATCH 53/61] Keep long recent folder names readable and stabilize UI checks Refs #88 --- src/files_main.cpp | 6 +++--- tests/files_commands_ui.ps1 | 6 ++---- tests/files_recent_folders_panel.ps1 | 13 ++++++++----- 3 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/files_main.cpp b/src/files_main.cpp index 7a3f965..bf9e0b1 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -9270,9 +9270,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } } auto shortcut=text.find(L'\t'); - if(item.hwndItem==picker && folderPicker) - paintDialogListRow(item.hDC,item.rcItem,text.c_str(),mono,foreground,rowBackground, - dialogRowTextInset(cellWidth),DT_PATH_ELLIPSIS|DT_END_ELLIPSIS); + if((item.hwndItem==picker && folderPicker) || (panelRow && recentFolderList(panels[item.CtlID-102]))) + paintDialogListRow(item.hDC,item.rcItem,text,rowFont?rowFont:mono,foreground,rowBackground, + panelRow?5:dialogRowTextInset(cellWidth),DT_PATH_ELLIPSIS|DT_END_ELLIPSIS); else if(item.hwndItem==picker && commandPicker && item.itemID Date: Thu, 26 Nov 2026 07:51:19 +0200 Subject: [PATCH 54/61] Release KSwitcher v0.8.1 --- CMakeLists.txt | 2 +- Release/README.md | 10 +++ Release/SHA256SUMS.txt | 2 +- Release/release-files.json | 168 ++++++++++++++++++------------------- resources/app.rc | 6 +- src/update.h | 2 +- 6 files changed, 100 insertions(+), 90 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7a4d090..6b951ac 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.8.0 LANGUAGES C CXX RC) +project(KSwitcher VERSION 0.8.1 LANGUAGES C CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() diff --git a/Release/README.md b/Release/README.md index 0fe6f17..5c7cdbc 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,15 @@ # Latest Windows release +## v0.8.1 — 2026-11-26 + +- **SMB.** Saved connections and a server’s shares open in the selected Files panel. Press **Enter** to open a connection or share. **Esc** returns to the previous list or folder. Profile editing and sign-in use their existing dialogs. +- **Recent folders.** The selected panel shows recent local and remote folders. **Enter** opens the entry in that panel, **Delete** removes the history entry, and **Esc** restores the previous folder and cursor. + +**Українською.** + +- **SMB.** Збережені підключення та спільні ресурси сервера відкриваються у вибраній панелі Files. **Enter** відкриває підключення чи ресурс. **Esc** повертає до попереднього списку або папки. Для редагування профілю та входу використовуються окремі діалоги. +- **Recent folders.** Вибрана панель показує нещодавні локальні й віддалені папки. **Enter** відкриває запис у цій панелі, **Delete** прибирає його з історії, а **Esc** відновлює попередню папку й курсор. + ## v0.8.0 — 2026-11-26 - **Files panels and search.** Find files recursively on local, FTP, SFTP and paired LAN panes. Work with results directly, navigate with breadcrumbs and history, recall recent folders, and configure sorting, filters, columns and panel layout. File clipboard and drag and drop integrate with Windows. diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index a9b881b..46b7607 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -3d1d0d0a1c9ad671c949e0744987c94642125ccb2f479d3126509250c1fca541 KSwitcher-win-x64.zip +4f73fa962a4a84ebb7b564fdb5e8cac6baeeff460d3e7147f09d6ded62553021 KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index 7b94f5f..5336f72 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,181 +1,181 @@ { "files": [ { - "sha256": "48fb46c472b1a3e689ff7a594f2ba728abee1b0ae2163333901179b624c23fe1", - "size": 3192832, - "path": "KSwitcher.exe" - }, - { - "sha256": "cf6f71169c79bb915c633765a4d56e6048e9a2c84ff877226158e9a27c8183ee", - "size": 2892800, - "path": "KSwitcher.Config.exe" - }, - { - "sha256": "79ec0555f9a2668fd284dd73663e2a2aecbc5833dba39e2b02a45b88ad1cae3d", "size": 3193344, - "path": "KSwitcher.Screenshot.exe" + "path": "KSwitcher.exe", + "sha256": "ceaeff987356f31cc4e1773b41825fe8bc621d51abd9884964339457b724198f" }, { - "sha256": "ebe481402fadc09f60afef4dc7ece293d2709c0f3931154d474fbc9a12c7d6a6", - "size": 5967872, - "path": "KSwitcher.Files.exe" + "size": 2892800, + "path": "KSwitcher.Config.exe", + "sha256": "d2d8fabbe9758d6744b04014cddc96cd7c87710249e025594861ed7bec508b9b" + }, + { + "size": 3193344, + "path": "KSwitcher.Screenshot.exe", + "sha256": "b2503e613fa203773a6ead05efaf4430fb297d642569ac64927a77acd78f53a8" + }, + { + "size": 5977600, + "path": "KSwitcher.Files.exe", + "sha256": "047d8ba01a3a316ca53c609283dee2638474731390dee74427ea881cc71d3617" }, { - "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6", "size": 194912, - "path": "WebView2Loader.dll" + "path": "WebView2Loader.dll", + "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6" }, { - "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f", "size": 1103, - "path": "terminal/addon-fit-LICENSE.txt" + "path": "terminal/addon-fit-LICENSE.txt", + "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f" }, { - "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527", "size": 1521, - "path": "terminal/addon-fit.js" + "path": "terminal/addon-fit.js", + "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527" }, { - "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef", "size": 527, - "path": "terminal/index.html" + "path": "terminal/index.html", + "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef" }, { - "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473", "size": 1073, - "path": "terminal/markdown-it-LICENSE.txt" + "path": "terminal/markdown-it-LICENSE.txt", + "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473" }, { - "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e", "size": 100786, - "path": "terminal/markdown-it.js" + "path": "terminal/markdown-it.js", + "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e" }, { - "sha256": "2576d0c897ffa7e78eb73fc065cd438af164b5dd332cc59083a53ac692fd575f", - "size": 3740, - "path": "terminal/markdown.html" + "size": 3800, + "path": "terminal/markdown.html", + "sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2" }, { - "sha256": "1eaf9a8a63ec5a62eb4e710cd413bf6893dbc9eaf7dbf4898927fb44afa08bbc", - "size": 18318, - "path": "terminal/markdown.js" + "size": 18721, + "path": "terminal/markdown.js", + "sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96" }, { - "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80", "size": 1089, - "path": "terminal/mermaid-LICENSE.txt" + "path": "terminal/mermaid-LICENSE.txt", + "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80" }, { - "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3", "size": 5537838, - "path": "terminal/mermaid.js" + "path": "terminal/mermaid.js", + "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3" }, { - "sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7", "size": 6627, - "path": "terminal/terminal.js" + "path": "terminal/terminal.js", + "sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7" }, { - "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd", "size": 1261, - "path": "terminal/xterm-LICENSE.txt" + "path": "terminal/xterm-LICENSE.txt", + "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd" }, { - "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6", "size": 7112, - "path": "terminal/xterm.css" + "path": "terminal/xterm.css", + "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6" }, { - "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972", "size": 488663, - "path": "terminal/xterm.js" + "path": "terminal/xterm.js", + "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972" }, { - "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c", "size": 4401, - "path": "LICENSE" + "path": "LICENSE", + "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c" }, { - "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831", "size": 1096, - "path": "json-LICENSE.txt" + "path": "json-LICENSE.txt", + "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831" }, { - "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625", "size": 883, - "path": "files-text-license.txt" + "path": "files-text-license.txt", + "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625" }, { - "sha256": "0b1d38528f1da5acccfb02634a91e3aa753547e137ccd1eebd0873fef2a9dd74", - "size": 4880, - "path": "files-archive-license.txt" + "size": 4990, + "path": "files-archive-license.txt", + "sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d" }, { - "sha256": "c94d49ba533db63c368a49a7e630ac7e947634cb6dc87cfaab7627272cc3e3e7", - "size": 2994, - "path": "files-image-license.txt" + "size": 3044, + "path": "files-image-license.txt", + "sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4" }, { - "sha256": "05894358228417bb0c524b5c800119b1d47ac0de3477e7cd1abe7a6b41580809", - "size": 2024, - "path": "files-sftp-license.txt" + "size": 2064, + "path": "files-sftp-license.txt", + "sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594" }, { - "sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01", "size": 105515, - "path": "README.md" + "path": "README.md", + "sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01" }, { - "sha256": "435ace9c718e14e4c391462ffea3a893c9b6622e9a8b861a7dab0492faf61469", - "size": 16474, - "path": "LAN-PREVIEW.md" + "size": 16722, + "path": "LAN-PREVIEW.md", + "sha256": "917c2f41b3943647fdfafa911d93f72b8c6fb0d08592016ce1a698d256e038bb" }, { - "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9", "size": 732485, - "path": "dictionaries/en.txt" + "path": "dictionaries/en.txt", + "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9" }, { - "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5", "size": 20566, - "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt" + "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt", + "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5" }, { - "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311", "size": 2265, - "path": "dictionaries/README.md" + "path": "dictionaries/README.md", + "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311" }, { - "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849", "size": 1109134, - "path": "dictionaries/ru.txt" + "path": "dictionaries/ru.txt", + "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849" }, { - "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408", "size": 1280, - "path": "dictionaries/sources.json" + "path": "dictionaries/sources.json", + "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408" }, { - "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf", "size": 940799, - "path": "dictionaries/uk.txt" + "path": "dictionaries/uk.txt", + "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf" }, { - "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a", "size": 993, - "path": "tools/README.txt" + "path": "tools/README.txt", + "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a" }, { - "sha256": "d4de0a3606267a1c2585412e1288d3be782786720ff1f2ccd9b2217e053bc11b", "size": 133120, - "path": "tools/StayHere.exe" + "path": "tools/StayHere.exe", + "sha256": "98f657cdd3d5dec5db8b45760edc656e23c362edc9002b6828d2fe4c8b86073b" }, { - "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413", "size": 2796, - "path": "tools/StayHere-README.md" + "path": "tools/StayHere-README.md", + "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413" } ], "schema": 1, - "version": "0.8.0" + "version": "0.8.1" } diff --git a/resources/app.rc b/resources/app.rc index 2900618..936071b 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -14,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur" 1 RT_MANIFEST "app.manifest" 201 RCDATA "update.ps1" 1 VERSIONINFO - FILEVERSION 0,8,0,0 - PRODUCTVERSION 0,8,0,0 + FILEVERSION 0,8,1,0 + PRODUCTVERSION 0,8,1,0 FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN @@ -25,7 +25,7 @@ BEGIN BEGIN VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility" VALUE "ProductName", "KSwitcher" - VALUE "FileVersion", "0.8.0" + VALUE "FileVersion", "0.8.1" END END BLOCK "VarFileInfo" diff --git a/src/update.h b/src/update.h index 03c5aab..291d4b2 100644 --- a/src/update.h +++ b/src/update.h @@ -2,7 +2,7 @@ #include "platform.h" namespace ks { -inline constexpr wchar_t AppVersion[] = L"0.8.0"; +inline constexpr wchar_t AppVersion[] = L"0.8.1"; inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; From aa90645c98383ff63c5447efecb5ab852dd61c47 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Thu, 26 Nov 2026 08:18:46 +0200 Subject: [PATCH 55/61] Show release notes after updating and in Help Refs #196 --- CMakeLists.txt | 3 +- resources/help-guide.md | 2 + resources/help.rc | 1 + resources/resource.h | 1 + src/app.cpp | 28 ++++++- src/app.h | 3 + src/ui.cpp | 1 + src/ui_help.inl | 166 ++++++++++++++++++++++++++++++++++------ tests/input.cpp | 68 ++++++++++++++++ 9 files changed, 244 insertions(+), 29 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 6b951ac..a332ec1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -81,7 +81,8 @@ set_property(SOURCE resources/help.rc APPEND PROPERTY OBJECT_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/resources/help-guide.md" "${CMAKE_CURRENT_SOURCE_DIR}/README.md" "${CMAKE_CURRENT_SOURCE_DIR}/FILES-UI.md" - "${CMAKE_CURRENT_SOURCE_DIR}/LAN-PREVIEW.md") + "${CMAKE_CURRENT_SOURCE_DIR}/LAN-PREVIEW.md" + "${CMAKE_CURRENT_SOURCE_DIR}/Release/README.md") add_executable(KSwitcher WIN32 src/main.cpp src/app.cpp src/screenshot_notifications.cpp src/screenshot_launcher.cpp src/screenshot_activation.cpp src/configuration.cpp src/ui.cpp resources/app.rc resources/help.rc) target_compile_definitions(KSwitcher PRIVATE KS_RESIDENT_APP) target_link_libraries(KSwitcher PRIVATE kscore) diff --git a/resources/help-guide.md b/resources/help-guide.md index 882e619..f0b830b 100644 --- a/resources/help-guide.md +++ b/resources/help-guide.md @@ -58,6 +58,8 @@ Choose Files from the tray. Use the two file panels to browse, move and copy fil Use the tray menu to pause or resume input processing, keep the display awake, pause clipboard history, open the data folder, check for updates or exit. Tools lists supported portable utilities placed in the tools folder. +After a successful update, What's new shows the installed release notes once. Open Help → What's new from the tray to read current and earlier releases offline or open the full release page in Gitea. + If a shortcut stops working, check whether input processing is paused and whether another application owns the binding. If a paired PC is missing, check discovery and access on both computers. Settings → Diagnostics and View log in the tray provide logs. Settings → MCP displays management integration settings. Donate via Monobank opens the project's donation jar in the browser. Choose Help → About KSwitcher to see the running version. diff --git a/resources/help.rc b/resources/help.rc index dea9c6f..4d40b4a 100644 --- a/resources/help.rc +++ b/resources/help.rc @@ -4,3 +4,4 @@ IDR_HELP_GUIDE RCDATA "help-guide.md" IDR_HELP_MANUAL RCDATA "../README.md" IDR_HELP_FILES RCDATA "../FILES-UI.md" IDR_HELP_COMPUTERS RCDATA "../LAN-PREVIEW.md" +IDR_HELP_RELEASES RCDATA "../Release/README.md" diff --git a/resources/resource.h b/resources/resource.h index 51aca3b..a1358b7 100644 --- a/resources/resource.h +++ b/resources/resource.h @@ -14,3 +14,4 @@ #define IDR_HELP_MANUAL 601 #define IDR_HELP_FILES 602 #define IDR_HELP_COMPUTERS 603 +#define IDR_HELP_RELEASES 604 diff --git a/src/app.cpp b/src/app.cpp index cda649f..e3aea52 100644 --- a/src/app.cpp +++ b/src/app.cpp @@ -144,7 +144,7 @@ ULONG_PTR snippetReplayMarker() return reinterpret_cast(&marker); } constexpr int OpenFiles = 25, FilesHotkeyFirst = 0x4B10, FilesHotkeySecond = 0x4B11; -constexpr int ToggleInputProcessing = 26, DonateViaMonobank = 27, OpenHelp = 28, OpenAbout = 16; +constexpr int ToggleInputProcessing = 26, DonateViaMonobank = 27, OpenHelp = 28, OpenWhatsNew = 29, OpenAbout = 16; constexpr wchar_t MonobankDonationUrl[] = L"https://send.monobank.ua/jar/88h2TddKfS"; constexpr int ShortcutProbeId = FilesHotkeySecond + 1; constexpr UINT_PTR PauseDrainTimer = 23; @@ -3269,6 +3269,7 @@ void App::trayMenu() AppendMenuW(menu, MF_SEPARATOR, 0, nullptr); HMENU help = CreatePopupMenu(); AppendMenuW(help, MF_STRING, OpenHelp, L"&User guide"); + AppendMenuW(help, MF_STRING, OpenWhatsNew, whatsNewTitle(GetThreadUILanguage())); AppendMenuW(help, MF_STRING, OpenAbout, L"&About KSwitcher"); AppendMenuW(menu, MF_POPUP, reinterpret_cast(help), L"H&elp"); AppendMenuW(menu, MF_STRING, 17, L"E&xit"); @@ -3333,6 +3334,9 @@ void App::trayMenu() case OpenHelp: showHelp(*this); break; + case OpenWhatsNew: + showWhatsNew(*this, GetThreadUILanguage()); + break; case DonateViaMonobank: if (reinterpret_cast(ShellExecuteW(window, L"open", MonobankDonationUrl, nullptr, nullptr, SW_SHOWNORMAL)) <= 32) throw std::runtime_error("Could not open the Monobank donation page."); @@ -3372,6 +3376,25 @@ void App::trayMenu() report(wide(e.what())); } } +void App::showWhatsNewAfterUpdate() +{ + if (!confirmUpdatedStartup(updateStartupEvent)) return; + log(std::wstring(L"Update completed; running version ") + AppVersion); + try + { + const auto seen = data / L"whats-new-seen.txt"; + const auto version = utf8(AppVersion); + if (std::filesystem::exists(seen) && readFile(seen, 64) == Bytes(version.begin(), version.end())) + return; + showWhatsNew(*this, GetThreadUILanguage()); + atomicWrite(seen, Bytes(version.begin(), version.end())); + } + catch (const std::exception &error) + { + log(L"Could not show release notes: " + wide(error.what())); + } +} + void App::checkUpdate(bool interactive, bool install, const std::wstring &version) { if (updateRunning) return; @@ -3876,8 +3899,6 @@ int App::execute() SetTimer(window, 2, 10000, nullptr); else SetTimer(window, 5, 5000, nullptr); - if (keyboardHook && mouseHook && confirmUpdatedStartup(updateStartupEvent)) - log(std::wstring(L"Update completed; running version ") + AppVersion); if (startCommand) PostMessageW(window, WM_HOTKEY, startCommand, 0); if (!smoke && !isLocalBuild() && settings.autostart) @@ -3885,6 +3906,7 @@ int App::execute() try { notificationRegistration = startScreenshotNotificationRegistration(); } catch(const std::exception &e) { log(L"Screenshot notification registration: "+wide(e.what())); } auto screenshotActivation=startScreenshotActivationListener(); + if (keyboardHook && mouseHook) showWhatsNewAfterUpdate(); MSG msg; while (GetMessageW(&msg, nullptr, 0, 0) > 0) { diff --git a/src/app.h b/src/app.h index dafe852..3ecf84c 100644 --- a/src/app.h +++ b/src/app.h @@ -78,6 +78,7 @@ class App void enqueue(std::function); void enqueueHistorySearch(std::function); void report(const std::wstring &); + void showWhatsNewAfterUpdate(); void trayMenu(); void addTray(); bool registerHotkeys(const Settings &, bool rollback = false); @@ -234,5 +235,7 @@ void showLogs(App &); void showSnippets(App &); void showShortcuts(App &); void showHelp(App &); +const wchar_t *whatsNewTitle(LANGID language); +void showWhatsNew(App &, LANGID language); void showEntry(App &, const std::wstring &); } // namespace ks diff --git a/src/ui.cpp b/src/ui.cpp index d7c653c..bf3407c 100644 --- a/src/ui.cpp +++ b/src/ui.cpp @@ -10,6 +10,7 @@ #include "ui_geometry.h" #include "diagnostics.h" #include "google_drive.h" +#include "update.h" #include #include #include diff --git a/src/ui_help.inl b/src/ui_help.inl index 37d9672..8a2f32d 100644 --- a/src/ui_help.inl +++ b/src/ui_help.inl @@ -1,13 +1,16 @@ namespace { -constexpr int HelpSearch = 810, HelpTopics = 811, HelpTitle = 812, HelpBody = 813; +constexpr int HelpSearch = 810, HelpTopics = 811, HelpTitle = 812, HelpBody = 813, HelpReleaseLink = 814; constexpr int HelpRail = 268, HelpFooter = 56, HelpHeader = 66; constexpr int ShortcutTopic = 0, GuideRoot = 1, GettingStarted = 2; +enum class HelpPage { shortcuts, guide, releases }; + struct HelpTopic { std::wstring title, text; int parent = -1; + std::wstring releaseVersion; }; struct HelpView @@ -19,6 +22,8 @@ struct HelpView UINT dpi{}; int selected{}; bool rebuilding{}; + bool releases{}; + bool ukrainian{}; }; std::wstring helpShortcuts(const App &app) @@ -65,16 +70,19 @@ std::wstring helpText(std::wstring line) return line; } +std::wstring helpResourceText(HINSTANCE instance, int resource) +{ + HRSRC found = FindResourceW(instance, MAKEINTRESOURCEW(resource), RT_RCDATA); + HGLOBAL loaded = found ? LoadResource(instance, found) : nullptr; + const auto *bytes = loaded ? static_cast(LockResource(loaded)) : nullptr; + return bytes ? wide(std::string(bytes, SizeofResource(instance, found))) : std::wstring{}; +} + void addHelpDocument(HelpView &view, int resource, std::wstring title, std::wstring introduction) { const int root = static_cast(view.topics.size()); view.topics.push_back({std::move(title), std::move(introduction)}); - const auto instance = view.app->instance; - HRSRC found = FindResourceW(instance, MAKEINTRESOURCEW(resource), RT_RCDATA); - HGLOBAL loaded = found ? LoadResource(instance, found) : nullptr; - const auto *bytes = loaded ? static_cast(LockResource(loaded)) : nullptr; - if (!bytes) return; - std::wistringstream input(wide(std::string(bytes, SizeofResource(instance, found)))); + std::wistringstream input(helpResourceText(view.app->instance, resource)); std::array ancestors; ancestors.fill(root); int topic = root; @@ -106,12 +114,74 @@ void addHelpDocument(HelpView &view, int resource, std::wstring title, std::wstr } } +int addReleaseTopics(HelpView &view, LANGID language) +{ + view.topics.push_back({whatsNewTitle(language), view.ukrainian + ? L"Виберіть версію, щоб переглянути зміни." + : L"Select a version to read its release notes."}); + std::wistringstream input(helpResourceText(view.app->instance, IDR_HELP_RELEASES)); + constexpr std::wstring_view ukrainianMarker = L"**Українською.**"; + std::wstring version, english, ukrainian; + bool translated = false, withdrawn = false; + int installed = 0; + const auto add = [&] + { + if (version.empty()) return; + auto &text = view.ukrainian && !ukrainian.empty() ? ukrainian : english; + const auto end = text.find_last_not_of(L" \r\n\t"); + if (end == std::wstring::npos) return; + text.resize(end + 1); + if (version == AppVersion) installed = static_cast(view.topics.size()); + auto title = L"v" + version; + if (withdrawn) title += view.ukrainian ? L" (відкликано)" : L" (withdrawn)"; + view.topics.push_back({std::move(title), std::move(text), 0, withdrawn ? std::wstring{} : version}); + }; + for (std::wstring line; std::getline(input, line);) + { + if (line.ends_with(L'\r')) line.pop_back(); + if (line.starts_with(L"## v")) + { + add(); + const auto end = line.find(L' ', 4); + version = line.substr(4, end == line.npos ? line.npos : end - 4); + if (version.empty() || version.find_first_not_of(L"0123456789.") != version.npos) + version.clear(); + english.clear(); + ukrainian.clear(); + translated = false; + withdrawn = line.find(L"(withdrawn") != line.npos; + continue; + } + if (version.empty()) continue; + if (line.starts_with(ukrainianMarker)) + { + translated = true; + const auto start = line.find_first_not_of(L" \t", ukrainianMarker.size()); + line = start == line.npos ? std::wstring{} : line.substr(start); + } + auto &text = translated ? ukrainian : english; + if (text.empty() && line.empty()) continue; + if (line.starts_with(L"- ")) line.replace(0, 1, L"•"); + text += helpText(std::move(line)) + L"\r\n"; + } + add(); + if (!installed) + { + installed = static_cast(view.topics.size()); + view.topics.push_back({std::wstring(L"v") + AppVersion, view.ukrainian + ? L"Нотатки для цієї збірки ще недоступні. Попередні випуски можна переглянути у списку." + : L"Notes for this build are unavailable. Earlier releases are in the list.", 0}); + } + return installed; +} + void showHelpTopic(HWND w, HelpView &view, int index) { view.selected = index; const auto &topic = view.topics[index]; value(w, HelpTitle, topic.title); - value(w, HelpBody, index == ShortcutTopic ? helpShortcuts(*view.app) : topic.text); + value(w, HelpBody, !view.releases && index == ShortcutTopic ? helpShortcuts(*view.app) : topic.text); + ShowWindow(GetDlgItem(w, HelpReleaseLink), topic.releaseVersion.empty() ? SW_HIDE : SW_SHOWNA); SendDlgItemMessageW(w, HelpBody, EM_SETSEL, 0, 0); SendDlgItemMessageW(w, HelpBody, EM_SCROLLCARET, 0, 0); } @@ -122,6 +192,7 @@ void fillHelpTopics(HWND w, HelpView &view) const auto query = lower(value(w, HelpSearch)); std::vector nodes(view.topics.size()); HTREEITEM selected{}; + int selectedIndex{}; view.rebuilding = true; SendMessageW(tree, WM_SETREDRAW, FALSE, 0); TreeView_DeleteAllItems(tree); @@ -137,17 +208,27 @@ void fillHelpTopics(HWND w, HelpView &view) node.item.pszText = const_cast(topic.title.c_str()); node.item.lParam = static_cast(i); nodes[i] = TreeView_InsertItem(tree, &node); - if (!selected || static_cast(i) == view.selected) selected = nodes[i]; + if (nodes[i] && (!selected || static_cast(i) == view.selected)) + { + selected = nodes[i]; + selectedIndex = static_cast(i); + } } - if (query.empty()) TreeView_Expand(tree, nodes[GuideRoot], TVE_EXPAND); + if (query.empty()) TreeView_Expand(tree, nodes[view.releases ? 0 : GuideRoot], TVE_EXPAND); SendMessageW(tree, WM_SETREDRAW, TRUE, 0); - view.rebuilding = false; - if (selected) TreeView_SelectItem(tree, selected); + if (selected) + { + TreeView_SelectItem(tree, selected); + showHelpTopic(w, view, selectedIndex); + } else { - value(w, HelpTitle, L"No matching topics"); - value(w, HelpBody, L"Try another word or clear the search to see all topics."); + value(w, HelpTitle, view.ukrainian ? L"Нічого не знайдено" : L"No matching topics"); + value(w, HelpBody, view.ukrainian ? L"Спробуйте інше слово або очистьте пошук." : + L"Try another word or clear the search to see all topics."); + ShowWindow(GetDlgItem(w, HelpReleaseLink), SW_HIDE); } + view.rebuilding = false; InvalidateRect(tree, nullptr, TRUE); } @@ -169,6 +250,7 @@ void layoutHelp(HWND w, HelpView &view) place(HelpTitle, content, scale(w, 13), r.right - pad, scale(w, 55)); place(HelpBody, content, header + pad, r.right - pad, footer - scale(w, 10)); place(IDCANCEL, r.right - pad - scale(w, 100), footer + scale(w, 14), r.right - pad, r.bottom - scale(w, 14)); + place(HelpReleaseLink, content, footer + scale(w, 14), content + scale(w, 170), r.bottom - scale(w, 14)); const auto dpi = GetDpiForWindow(w); if (view.dpi != dpi || !view.heading) { @@ -252,6 +334,18 @@ LRESULT CALLBACK helpProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) } case WM_COMMAND: if (LOWORD(wp) == HelpSearch && HIWORD(wp) == EN_CHANGE) fillHelpTopics(w, *view); + if (LOWORD(wp) == HelpReleaseLink && IsWindowVisible(GetDlgItem(w, HelpReleaseLink))) + { + const auto &version = view->topics[view->selected].releaseVersion; + constexpr auto repository = L"https://gitea.hrynco.com/hrynco/hrynco-kswitcher"; + // Older release pages can be superseded while the tagged notes remain available. + const auto path = version == AppVersion ? L"/releases/tag/release-v" + version + : L"/src/tag/release-v" + version + L"/Release/README.md"; + const auto address = repository + path; + if (reinterpret_cast(ShellExecuteW(w, L"open", address.c_str(), nullptr, nullptr, SW_SHOWNORMAL)) <= 32) + MessageBoxW(w, view->ukrainian ? L"Не вдалося відкрити сторінку випуску." : + L"Could not open the release page.", view->ukrainian ? L"Що нового" : L"What's new", MB_OK | MB_ICONWARNING); + } if (LOWORD(wp) == IDCANCEL) DestroyWindow(w); return 0; case WM_NCDESTROY: @@ -265,7 +359,7 @@ LRESULT CALLBACK helpProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) return DefWindowProcW(w, msg, wp, lp); } -void openHelp(App &app, int topic) +void openHelp(App &app, HelpPage page, LANGID language = LANG_ENGLISH) { if (!app.helpWindow) { @@ -273,15 +367,8 @@ void openHelp(App &app, int topic) app.helpWindow = w; setWindowTaskbarIdentity(w, IDI_KSWITCHER_HELP, L"HrynCo.KSwitcher.Help"); auto &view = *reinterpret_cast(GetWindowLongPtrW(w, GWLP_USERDATA)); - view.topics = {{L"Keyboard shortcuts", L"Current shortcut bindings and keyboard controls"}}; - addHelpDocument(view, IDR_HELP_GUIDE, L"Using KSwitcher", L"Choose an area to learn how to use it.\r\n"); - addHelpDocument(view, IDR_HELP_MANUAL, L"KSwitcher manual", L"Detailed documentation for the main application.\r\n"); - addHelpDocument(view, IDR_HELP_FILES, L"Files manual (Українська)", L"Докладний посібник з KSwitcher Files.\r\n"); - addHelpDocument(view, IDR_HELP_COMPUTERS, L"Paired computers manual", L"Detailed documentation for discovery, pairing and LAN features.\r\n"); - auto search = edit(w, HelpSearch, 0, 0, 0); SendMessageW(search, EM_SETLIMITTEXT, 120, 0); - SendMessageW(search, EM_SETCUEBANNER, TRUE, reinterpret_cast(L"Search help")); INITCOMMONCONTROLSEX classes{sizeof(classes), ICC_TREEVIEW_CLASSES}; InitCommonControlsEx(&classes); control(w, WC_TREEVIEWW, L"Help topics", WS_TABSTOP | TVS_HASBUTTONS | TVS_LINESATROOT | @@ -289,13 +376,37 @@ void openHelp(App &app, int topic) control(w, L"STATIC", L"", SS_CENTERIMAGE | SS_ENDELLIPSIS, HelpTitle, 0, 0, 0, 0); auto body = edit(w, HelpBody, 0, 0, 0, 0, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL); SendMessageW(body, EM_SETLIMITTEXT, 1024 * 1024, 0); + button(w, L"Open in Gitea", HelpReleaseLink, 0, 0); button(w, L"&Close", IDCANCEL, 0, 0); SendMessageW(w, WM_SYSCOLORCHANGE, 0, 0); layoutHelp(w, view); } const auto w = app.helpWindow; auto &view = *reinterpret_cast(GetWindowLongPtrW(w, GWLP_USERDATA)); - view.selected = topic < static_cast(view.topics.size()) ? topic : GuideRoot; + const bool releases = page == HelpPage::releases; + const bool ukrainian = releases && PRIMARYLANGID(language) == LANG_UKRAINIAN; + int topic = page == HelpPage::shortcuts ? ShortcutTopic : GettingStarted; + if (releases || view.topics.empty() || view.releases) + { + view.topics.clear(); + view.releases = releases; + view.ukrainian = ukrainian; + if (releases) topic = addReleaseTopics(view, language); + else + { + view.topics = {{L"Keyboard shortcuts", L"Current shortcut bindings and keyboard controls"}}; + addHelpDocument(view, IDR_HELP_GUIDE, L"Using KSwitcher", L"Choose an area to learn how to use it.\r\n"); + addHelpDocument(view, IDR_HELP_MANUAL, L"KSwitcher manual", L"Detailed documentation for the main application.\r\n"); + addHelpDocument(view, IDR_HELP_FILES, L"Files manual (Українська)", L"Докладний посібник з KSwitcher Files.\r\n"); + addHelpDocument(view, IDR_HELP_COMPUTERS, L"Paired computers manual", L"Detailed documentation for discovery, pairing and LAN features.\r\n"); + } + } + SetWindowTextW(w, releases ? whatsNewTitle(language) : L"KSwitcher Help"); + value(w, IDCANCEL, ukrainian ? L"&Закрити" : L"&Close"); + value(w, HelpReleaseLink, ukrainian ? L"Відкрити в Gitea" : L"Open in Gitea"); + const auto *searchHint = ukrainian ? L"Пошук випусків" : releases ? L"Search releases" : L"Search help"; + SendDlgItemMessageW(w, HelpSearch, EM_SETCUEBANNER, TRUE, reinterpret_cast(searchHint)); + view.selected = topic; if (value(w, HelpSearch).empty()) fillHelpTopics(w, view); else value(w, HelpSearch, L""); if (IsIconic(w)) ShowWindow(w, SW_RESTORE); @@ -305,5 +416,10 @@ void openHelp(App &app, int topic) } } // namespace -void showHelp(App &app) { openHelp(app, GettingStarted); } -void showShortcuts(App &app) { openHelp(app, ShortcutTopic); } +void showHelp(App &app) { openHelp(app, HelpPage::guide); } +void showShortcuts(App &app) { openHelp(app, HelpPage::shortcuts); } +const wchar_t *whatsNewTitle(LANGID language) +{ + return PRIMARYLANGID(language) == LANG_UKRAINIAN ? L"Що нового" : L"What's new"; +} +void showWhatsNew(App &app, LANGID language) { openHelp(app, HelpPage::releases, language); } diff --git a/tests/input.cpp b/tests/input.cpp index 90df435..f3eeda6 100644 --- a/tests/input.cpp +++ b/tests/input.cpp @@ -426,6 +426,74 @@ int main(int argc, char **argv) { ks::encodePng(ks::decodeImage(preview))); SendMessageW(window, WM_COMMAND, IDCANCEL, 0); require(!app.helpWindow && !IsWindow(window), "Close releases the help window"); + + const auto seen = temp / L"whats-new-seen.txt"; + app.showWhatsNewAfterUpdate(); + require(!app.helpWindow && !std::filesystem::exists(seen), "ordinary startup does not open release notes"); + app.updateStartupEvent = L"Local\\KSwitcher.Update.Started." + ks::newSnippetId(); + app.showWhatsNewAfterUpdate(); + require(!app.helpWindow && !std::filesystem::exists(seen), "an unconfirmed update does not open release notes"); + const auto ready = CreateEventW(nullptr, TRUE, FALSE, app.updateStartupEvent.c_str()); + require(ready != nullptr, "update test creates a startup handshake"); + app.showWhatsNewAfterUpdate(); + const auto signaled = WaitForSingleObject(ready, 0); + CloseHandle(ready); + require(signaled == WAIT_OBJECT_0 && IsWindowVisible(app.helpWindow) && std::filesystem::exists(seen), + "successful update signals startup and opens the installed notes once"); + DestroyWindow(app.helpWindow); + const auto secondReady = CreateEventW(nullptr, TRUE, FALSE, app.updateStartupEvent.c_str()); + require(secondReady != nullptr, "repeat startup can complete its updater handshake"); + app.showWhatsNewAfterUpdate(); + const auto secondSignal = WaitForSingleObject(secondReady, 0); + CloseHandle(secondReady); + require(secondSignal == WAIT_OBJECT_0 && !app.helpWindow, + "the same version acknowledges the updater without reopening the notes"); + + const auto language = MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT); + ks::showWhatsNew(app, language); + const auto releases = app.helpWindow; + const auto releaseText = [&](int id) { + wchar_t buffer[32768]{}; + GetDlgItemTextW(releases, id, buffer, std::size(buffer)); + return std::wstring(buffer); + }; + require(std::wstring(ks::whatsNewTitle(language)) == L"What's new" && + releaseText(812) == std::wstring(L"v") + ks::AppVersion && + !releaseText(813).empty() && IsWindowVisible(GetDlgItem(releases, 814)), + "manual Help command opens embedded notes for the installed release with a Gitea link"); + const auto versions = GetDlgItem(releases, 811); + require(TreeView_GetCount(versions) > 2, "prior releases are available offline"); + SetDlgItemTextW(releases, 810, L"v0.6.126"); + require(releaseText(812) == L"v0.6.126 (withdrawn)" && !IsWindowVisible(GetDlgItem(releases, 814)), + "withdrawn releases show their archived notes without a dead Gitea release link"); + SetDlgItemTextW(releases, 810, L"v0.8.0"); + require(releaseText(812) == L"v0.8.0" && releaseText(813).find(L"Find files recursively") != std::wstring::npos, + "release history searches and shows English notes"); + const auto ukrainian = MAKELANGID(LANG_UKRAINIAN, SUBLANG_DEFAULT); + ks::showWhatsNew(app, ukrainian); + require(releases == app.helpWindow && std::wstring(ks::whatsNewTitle(ukrainian)) == L"Що нового" && + releaseText(814) == L"Відкрити в Gitea", + "the same window can display Ukrainian release history"); + SetDlgItemTextW(releases, 810, L"v0.8.0"); + require(releaseText(812) == L"v0.8.0" && releaseText(813).find(L"Рекурсивний пошук") != std::wstring::npos && + releaseText(813).find(L"Find files recursively") == std::wstring::npos, + "Ukrainian notes render without the adjacent English section"); + + SetDlgItemTextW(releases, 810, L""); + require(TreeView_GetCount(versions) > 2 && releaseText(812) == L"v0.8.0", + "clearing the search retains the selected release in the full history"); + RECT releaseClient{}; + GetClientRect(releases, &releaseClient); + RedrawWindow(releases, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN); + const auto releaseDc = GetDC(releases); + const auto releasePreview = ks::screenshotClip(releaseDc, releaseClient.right, releaseClient.bottom, {}); + ReleaseDC(releases, releaseDc); + ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"whats-new.png", + ks::encodePng(ks::decodeImage(releasePreview))); + ks::showHelp(app); + require(releases == app.helpWindow && releaseText(812) == L"Getting started" && + !IsWindowVisible(GetDlgItem(releases, 814)), + "returning to the guide restores its topics and actions"); } std::filesystem::remove_all(temp); std::cout << "Passed " << checks << " offline help checks\n"; From 0ad8d7f6aa909b02f663990039585733c6e79141 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Thu, 26 Nov 2026 12:30:29 +0200 Subject: [PATCH 56/61] Release KSwitcher v0.8.2 with Lavender Files appearance Port the optional Lavender style to the current Files panels and dialogs while retaining the 0.8 navigation and transfer features. --- CMakeLists.txt | 9 +- FILES-UI.md | 6 + Release/README.md | 10 + Release/SHA256SUMS.txt | 2 +- Release/release-files.json | 146 ++++---- resources/app.rc | 6 +- resources/files.rc | 4 +- src/files_command_history_dialog.inl | 7 +- src/files_compare.inl | 4 +- src/files_dialog_input.inl | 5 + src/files_folder_shortcuts.inl | 16 +- src/files_lavender.inl | 115 +++++++ src/files_lavender_dialogs.inl | 359 ++++++++++++++++++++ src/files_main.cpp | 476 +++++++++++++++++++++------ src/files_options.inl | 83 ++++- src/files_path_navigation.inl | 6 + src/update.h | 2 +- tests/files_activation.ps1 | 3 + tests/files_lavender.ps1 | 310 +++++++++++++++++ 19 files changed, 1377 insertions(+), 192 deletions(-) create mode 100644 src/files_lavender.inl create mode 100644 src/files_lavender_dialogs.inl create mode 100644 tests/files_lavender.ps1 diff --git a/CMakeLists.txt b/CMakeLists.txt index a332ec1..a4a2460 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.8.1 LANGUAGES C CXX RC) +project(KSwitcher VERSION 0.8.2 LANGUAGES C CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() @@ -36,7 +36,7 @@ add_custom_target(check-files-quick-view DEPENDS KSwitcherFiles VERBATIM) target_include_directories(KSwitcherFiles PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/build/terminal-deps/sdk/build/native/include") -target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr userenv KSwitcherFilesImage libssh2::libssh2) +target_link_libraries(KSwitcherFiles PRIVATE user32 gdi32 comctl32 shell32 comdlg32 advapi32 ole32 uuid wininet netapi32 mpr userenv dwmapi KSwitcherFilesImage libssh2::libssh2) if(MSVC) target_compile_options(KSwitcherFiles PRIVATE /utf-8) else() @@ -245,6 +245,11 @@ add_test(NAME files-recent-folders-panel -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_recent_folders_panel.ps1" -Executable "$") set_tests_properties(files-recent-folders-panel PROPERTIES RUN_SERIAL TRUE TIMEOUT 35) +add_test(NAME files-lavender + COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass + -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_lavender.ps1" + -Executable "$") +set_tests_properties(files-lavender PROPERTIES RUN_SERIAL TRUE TIMEOUT 55) add_test(NAME files-space-analyzer-layout COMMAND "${KSWITCHER_POWERSHELL}" -NoProfile -ExecutionPolicy Bypass -File "${CMAKE_CURRENT_SOURCE_DIR}/tests/files_space_analyzer_layout.ps1" diff --git a/FILES-UI.md b/FILES-UI.md index bd4a220..3b9a76c 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -1,5 +1,11 @@ # Оформлення KSwitcher Files +**F9 → Options → Appearance → Window style → Lavender** вмикає світлі +заокруглені панелі, виділення поточного рядка, смугу команд і оформлення +власних діалогів та налаштувань. Діалоги файлових операцій мають темний +заголовок, помітну рамку й білі поля на лавандовому тлі. Попередження мають +червоний заголовок. За замовчуванням увімкнено Far. Гарячі клавіші діють в обох стилях. + Far Manager є зразком для оформлення файлового менеджера. Основне вікно використовує системний заголовок Windows. Панелі, меню й діалоги операцій використовують моноширинний шрифт менеджера та оформлення в стилі Far. Іконка головного вікна показує дві сині панелі з бірюзовою рамкою та виділеним рядком. diff --git a/Release/README.md b/Release/README.md index 5c7cdbc..a0512c5 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,15 @@ # Latest Windows release +## v0.8.2 — 2026-11-26 + +- **Files.** Choose **F9 → Options → Appearance → Window style → Lavender** for light panes, clearer selection and a redesigned command bar. File operation dialogs have a dark title band, with a red band for warnings. Far remains the default, and keyboard shortcuts work in both styles. +- **What’s new.** KSwitcher shows release notes after an update. Reopen them from **Help → What’s new** in the tray. + +**Українською.** + +- **Files.** Виберіть **F9 → Options → Appearance → Window style → Lavender**, щоб увімкнути світлі панелі, виразніше виділення й оновлену смугу команд. Діалоги файлових операцій мають темний заголовок, а попередження — червоний. Far лишається стандартним режимом, в обох стилях працюють ті самі гарячі клавіші. +- **Що нового.** KSwitcher показує нотатки після оновлення. Повторно відкрийте їх через **Help → What’s new** у треї. + ## v0.8.1 — 2026-11-26 - **SMB.** Saved connections and a server’s shares open in the selected Files panel. Press **Enter** to open a connection or share. **Esc** returns to the previous list or folder. Profile editing and sign-in use their existing dialogs. diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index 46b7607..d75d2d2 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -4f73fa962a4a84ebb7b564fdb5e8cac6baeeff460d3e7147f09d6ded62553021 KSwitcher-win-x64.zip +01cc0f4cf1555c6e038ab6ff4d00439c28f4a79ca8452fd5e3f4158947e5ceab KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index 5336f72..0d78217 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,181 +1,181 @@ { + "schema": 1, + "version": "0.8.2", "files": [ { - "size": 3193344, "path": "KSwitcher.exe", - "sha256": "ceaeff987356f31cc4e1773b41825fe8bc621d51abd9884964339457b724198f" + "sha256": "37cdbed818cb6351e606c8ef4a052a8d1218c515863787b2d407c97cb88858c7", + "size": 3244544 }, { - "size": 2892800, "path": "KSwitcher.Config.exe", - "sha256": "d2d8fabbe9758d6744b04014cddc96cd7c87710249e025594861ed7bec508b9b" + "sha256": "6ab516b657c95c9fe5461b71e020831337831bd7807b1991a71a4bb40f26889e", + "size": 2849792 }, { - "size": 3193344, "path": "KSwitcher.Screenshot.exe", - "sha256": "b2503e613fa203773a6ead05efaf4430fb297d642569ac64927a77acd78f53a8" + "sha256": "dbc7f702c25ea63e5c8b64bb0a76b8a058cf75938262fb0a20113e80b00d88b7", + "size": 3193344 }, { - "size": 5977600, "path": "KSwitcher.Files.exe", - "sha256": "047d8ba01a3a316ca53c609283dee2638474731390dee74427ea881cc71d3617" + "sha256": "98326211b088d838720068863edfc38988f54b27326e62ed1b4ab79c3f455ab8", + "size": 5998592 }, { - "size": 194912, "path": "WebView2Loader.dll", - "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6" + "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6", + "size": 194912 }, { - "size": 1103, "path": "terminal/addon-fit-LICENSE.txt", - "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f" + "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f", + "size": 1103 }, { - "size": 1521, "path": "terminal/addon-fit.js", - "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527" + "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527", + "size": 1521 }, { - "size": 527, "path": "terminal/index.html", - "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef" + "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef", + "size": 527 }, { - "size": 1073, "path": "terminal/markdown-it-LICENSE.txt", - "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473" + "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473", + "size": 1073 }, { - "size": 100786, "path": "terminal/markdown-it.js", - "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e" + "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e", + "size": 100786 }, { - "size": 3800, "path": "terminal/markdown.html", - "sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2" + "sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2", + "size": 3800 }, { - "size": 18721, "path": "terminal/markdown.js", - "sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96" + "sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96", + "size": 18721 }, { - "size": 1089, "path": "terminal/mermaid-LICENSE.txt", - "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80" + "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80", + "size": 1089 }, { - "size": 5537838, "path": "terminal/mermaid.js", - "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3" + "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3", + "size": 5537838 }, { - "size": 6627, "path": "terminal/terminal.js", - "sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7" + "sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7", + "size": 6627 }, { - "size": 1261, "path": "terminal/xterm-LICENSE.txt", - "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd" + "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd", + "size": 1261 }, { - "size": 7112, "path": "terminal/xterm.css", - "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6" + "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6", + "size": 7112 }, { - "size": 488663, "path": "terminal/xterm.js", - "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972" + "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972", + "size": 488663 }, { - "size": 4401, "path": "LICENSE", - "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c" + "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c", + "size": 4401 }, { - "size": 1096, "path": "json-LICENSE.txt", - "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831" + "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831", + "size": 1096 }, { - "size": 883, "path": "files-text-license.txt", - "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625" + "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625", + "size": 883 }, { - "size": 4990, "path": "files-archive-license.txt", - "sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d" + "sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d", + "size": 4990 }, { - "size": 3044, "path": "files-image-license.txt", - "sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4" + "sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4", + "size": 3044 }, { - "size": 2064, "path": "files-sftp-license.txt", - "sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594" + "sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594", + "size": 2064 }, { - "size": 105515, "path": "README.md", - "sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01" + "sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01", + "size": 105515 }, { - "size": 16722, "path": "LAN-PREVIEW.md", - "sha256": "917c2f41b3943647fdfafa911d93f72b8c6fb0d08592016ce1a698d256e038bb" + "sha256": "917c2f41b3943647fdfafa911d93f72b8c6fb0d08592016ce1a698d256e038bb", + "size": 16722 }, { - "size": 732485, "path": "dictionaries/en.txt", - "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9" + "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9", + "size": 732485 }, { - "size": 20566, "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt", - "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5" + "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5", + "size": 20566 }, { - "size": 2265, "path": "dictionaries/README.md", - "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311" + "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311", + "size": 2265 }, { - "size": 1109134, "path": "dictionaries/ru.txt", - "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849" + "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849", + "size": 1109134 }, { - "size": 1280, "path": "dictionaries/sources.json", - "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408" + "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408", + "size": 1280 }, { - "size": 940799, "path": "dictionaries/uk.txt", - "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf" + "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf", + "size": 940799 }, { - "size": 993, "path": "tools/README.txt", - "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a" + "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a", + "size": 993 }, { - "size": 133120, "path": "tools/StayHere.exe", - "sha256": "98f657cdd3d5dec5db8b45760edc656e23c362edc9002b6828d2fe4c8b86073b" + "sha256": "87f842e25d07bf95dee8116733a10fd2e24fa9a10d645c5ea1f374908aaf0e0b", + "size": 133120 }, { - "size": 2796, "path": "tools/StayHere-README.md", - "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413" + "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413", + "size": 2796 } - ], - "schema": 1, - "version": "0.8.1" + ] } diff --git a/resources/app.rc b/resources/app.rc index 936071b..52ec714 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -14,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur" 1 RT_MANIFEST "app.manifest" 201 RCDATA "update.ps1" 1 VERSIONINFO - FILEVERSION 0,8,1,0 - PRODUCTVERSION 0,8,1,0 + FILEVERSION 0,8,2,0 + PRODUCTVERSION 0,8,2,0 FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN @@ -25,7 +25,7 @@ BEGIN BEGIN VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility" VALUE "ProductName", "KSwitcher" - VALUE "FileVersion", "0.8.1" + VALUE "FileVersion", "0.8.2" END END BLOCK "VarFileInfo" diff --git a/resources/files.rc b/resources/files.rc index c950503..8444d32 100644 --- a/resources/files.rc +++ b/resources/files.rc @@ -250,7 +250,7 @@ STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMEN CAPTION "KSwitcher Files Options" FONT 9, "Segoe UI" BEGIN - LTEXT "&Search settings", -1, 8, 8, 113, 10 + LTEXT "&Search settings", 418, 8, 8, 113, 10 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 @@ -276,6 +276,8 @@ BEGIN PUSHBUTTON "Change &color…", 279, 131, 48, 82, 15 LTEXT "", 280, 222, 50, 155, 12 LTEXT "", 281, 131, 30, 254, 14 + LTEXT "Interface style", 416, 131, 30, 105, 14 + COMBOBOX 417, 245, 28, 132, 65, CBS_DROPDOWNLIST | WS_TABSTOP PUSHBUTTON "Change &font…", 282, 131, 52, 82, 15 LTEXT "&Outer padding (px at 96 DPI)", 302, 131, 31, 173, 12 COMBOBOX 303, 311, 28, 56, 125, CBS_DROPDOWNLIST | WS_TABSTOP | WS_VSCROLL diff --git a/src/files_command_history_dialog.inl b/src/files_command_history_dialog.inl index fa5b99a..c2b5843 100644 --- a/src/files_command_history_dialog.inl +++ b/src/files_command_history_dialog.inl @@ -259,14 +259,15 @@ INT_PTR CALLBACK commandHistoryDialog(HWND dialog,UINT message,WPARAM wp,LPARAM SendMessageW(item.hwndItem,LB_GETTEXT,item.itemID,reinterpret_cast(label.data())); label.resize(count); const bool selected=(item.itemState&ODS_SELECTED)!=0 && item.itemData(-1)) { auto bounds=item.rcItem; InflateRect(&bounds,-historyRowInset(GetDpiForWindow(dialog)),0); const auto saved=SaveDC(item.hDC); - SelectObject(item.hDC,mono); + SelectObject(item.hDC,dialogUiFont()); SetBkColor(item.hDC,background); SetTextColor(item.hDC,ink); ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&bounds,nullptr,0,nullptr); diff --git a/src/files_compare.inl b/src/files_compare.inl index 0eac243..1cd4b9c 100644 --- a/src/files_compare.inl +++ b/src/files_compare.inl @@ -1051,6 +1051,7 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) SendMessageW(dialog,WM_SETICON,ICON_SMALL,reinterpret_cast(small)); SendMessageW(dialog,WM_SETICON,ICON_BIG,reinterpret_cast(large)); ks::files::setFileWindowTaskbar(dialog,IDI_FILES_COMPARE,L"HrynCo.KSwitcher.Files.Compare"); + if(lavenderFiles()) styleLavenderDialogControls(dialog); initializeComparisonToolbar(toolbar); const auto actions=GetDlgItem(dialog,408); initializeComparisonActions(actions); @@ -1070,6 +1071,7 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) { applyComparisonAppearance(dialog,*comparison); layoutComparisonHeaders(dialog,*comparison); + RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN); return TRUE; } if(message==WM_CLOSE && comparison) @@ -1195,7 +1197,7 @@ INT_PTR CALLBACK comparisonDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) return TRUE; } } - return FALSE; + return lavenderDialogColors(dialog,message,wp,lp); } INT_PTR CALLBACK comparisonProgressDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) diff --git a/src/files_dialog_input.inl b/src/files_dialog_input.inl index 13b63d5..c8fab8e 100644 --- a/src/files_dialog_input.inl +++ b/src/files_dialog_input.inl @@ -54,6 +54,8 @@ LRESULT CALLBACK filesDialogMouse(int code,WPARAM message,LPARAM data) class FilesModalDialog { public: + inline static void (*styleControls)(HWND){}; + inline static INT_PTR (*styleBackground)(HWND,UINT,WPARAM,LPARAM){}; FilesModalDialog(HINSTANCE instance,LPCWSTR resource,HWND owner,DLGPROC procedure,LPARAM argument, bool watchOutsideClicks=true,bool fitToOwner=true) : owner_(owner),focus_(GetFocus()),procedure_(procedure),argument_(argument), @@ -347,7 +349,10 @@ private: lp=state->argument_; } if(!state) return FALSE; + if(styleBackground) + if(const auto styled=styleBackground(dialog,message,wp,lp)) return styled; const auto handled=state->procedure_(dialog,message,wp,lp); + if(message==WM_INITDIALOG && styleControls) styleControls(dialog); if(message==WM_NCDESTROY) RemovePropW(dialog,stateProperty_); if(!handled && message==WM_CLOSE) { diff --git a/src/files_folder_shortcuts.inl b/src/files_folder_shortcuts.inl index d299bbb..c75c6ec 100644 --- a/src/files_folder_shortcuts.inl +++ b/src/files_folder_shortcuts.inl @@ -309,12 +309,16 @@ INT_PTR CALLBACK quickFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) const auto dc=BeginPaint(dialog,&ps); RECT client{}; GetClientRect(dialog,&client); - const auto frame=CreateSolidBrush(colors[Text]); - const auto bounds=paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),teal,frame); - DeleteObject(frame); - paintDialogFrameCaptions(dc,client,bounds,L"Folder shortcuts",teal,colors[Text],mono, - view->digit<0?L"Enter Esc":quickFolderHints); - paintScrollPosition(dialog,dc,GetDlgItem(dialog,shortcutList),colors[Dialog]); + const auto hints=view->digit<0?L"Enter Esc":quickFolderHints; + if(lavenderFiles()) paintLavenderDialogFrame(dialog,dc,client,L"Folder shortcuts",hints); + else + { + const auto frame=CreateSolidBrush(colors[Text]); + const auto bounds=paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),teal,frame); + DeleteObject(frame); + paintDialogFrameCaptions(dc,client,bounds,L"Folder shortcuts",teal,colors[Text],mono,hints); + } + paintScrollPosition(dialog,dc,GetDlgItem(dialog,shortcutList),lavenderFiles()?lavender::surface:colors[Dialog]); EndPaint(dialog,&ps); return TRUE; } diff --git a/src/files_lavender.inl b/src/files_lavender.inl new file mode 100644 index 0000000..852f740 --- /dev/null +++ b/src/files_lavender.inl @@ -0,0 +1,115 @@ +namespace lavender +{ +constexpr COLORREF canvas=RGB(238,240,250), surface=RGB(255,255,255), line=RGB(218,221,241); +constexpr COLORREF ink=RGB(29,33,64), muted=RGB(91,97,133), accent=RGB(70,72,187); +constexpr COLORREF activeEdge=RGB(151,151,244), selection=RGB(231,227,253), idleSelection=RGB(240,241,249); +constexpr COLORREF folder=RGB(124,133,227), key=RGB(231,230,252), path=RGB(247,247,253); +constexpr COLORREF marked=RGB(105,52,170), markedSelection=RGB(219,209,250); + +HFONT font{}; + +void setFont(UINT dpi) +{ + if(font) DeleteObject(font); + font=CreateFontW(-MulDiv(14,dpi,96),0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET, + OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI"); +} + +void fill(HDC dc,const RECT &rect,COLORREF color) +{ + SetDCBrushColor(dc,color); + FillRect(dc,&rect,static_cast(GetStockObject(DC_BRUSH))); +} + +void rounded(HDC dc,RECT rect,int radius,COLORREF color,COLORREF border) +{ + if(rect.right<=rect.left || rect.bottom<=rect.top) return; + const auto brush=SelectObject(dc,GetStockObject(DC_BRUSH)); + const auto pen=SelectObject(dc,GetStockObject(DC_PEN)); + SetDCBrushColor(dc,color); + SetDCPenColor(dc,border); + RoundRect(dc,rect.left,rect.top,rect.right,rect.bottom,2*radius,2*radius); + SelectObject(dc,pen); + SelectObject(dc,brush); +} + +void text(HDC dc,RECT rect,const wchar_t *label,COLORREF color,UINT alignment=DT_LEFT, + UINT ellipsis=DT_END_ELLIPSIS) +{ + if(rect.right<=rect.left) return; + const auto previous=SelectObject(dc,font?font:GetStockObject(DEFAULT_GUI_FONT)); + const auto background=SetBkMode(dc,TRANSPARENT); + const auto inkColor=SetTextColor(dc,color); + DrawTextW(dc,label,-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|alignment|ellipsis); + SetTextColor(dc,inkColor); + SetBkMode(dc,background); + SelectObject(dc,previous); +} +} + +struct LavenderMetrics +{ + UINT dpi; + int px(int value) const { return MulDiv(value,dpi,96); } + int row; + explicit LavenderMetrics(HWND window): dpi(GetDpiForWindow(window)),row(px(25)) {} +}; + +void styleLavenderCaption(HWND window,bool enabled) +{ + const COLORREF surface=enabled?lavender::path:DWMWA_COLOR_DEFAULT; + const COLORREF text=enabled?lavender::ink:DWMWA_COLOR_DEFAULT; + DwmSetWindowAttribute(window,DWMWA_CAPTION_COLOR,&surface,sizeof(surface)); + DwmSetWindowAttribute(window,DWMWA_TEXT_COLOR,&text,sizeof(text)); +} + +void paintLavenderFileIcon(HDC dc,RECT row,const LavenderMetrics &metrics,bool folder) +{ + using namespace lavender; + const int x=row.left+metrics.px(9), y=(row.top+row.bottom-metrics.px(12))/2; + const int stroke=metrics.px(1); + if(folder) + { + const auto edge=RGB(104,114,205); + rounded(dc,{x,y,x+metrics.px(8),y+metrics.px(8)},stroke,lavender::folder,edge); + rounded(dc,{x,y+metrics.px(3),x+metrics.px(14),y+metrics.px(12)},2*stroke,lavender::folder,edge); + } + else + { + const int left=x+metrics.px(2), right=x+metrics.px(12), bottom=y+metrics.px(13); + rounded(dc,{left,y,right,bottom},stroke,path,RGB(157,164,198)); + for(int offset:{5,8}) fill(dc,{left+2*stroke,y+metrics.px(offset),right-2*stroke, + y+metrics.px(offset)+stroke},RGB(185,190,215)); + } +} + +void paintLavenderCommand(const DRAWITEMSTRUCT &item,const std::wstring &label,const LavenderMetrics &metrics,bool compact) +{ + using namespace lavender; + const auto &box=item.rcItem; + fill(item.hDC,box,canvas); + const bool pressed=item.itemState&ODS_SELECTED; + rounded(item.hDC,box,metrics.px(8),pressed?selection:path,pressed?activeEdge:line); + const auto separator=label.find(L' '); + const auto shortcut=label.substr(0,separator); + const int width=metrics.px(shortcut.size()>3?48:27); + const int padding=metrics.px(5); + if(compact) + { + const LONG left=std::max(box.left,(box.left+box.right-width)/2); + const LONG top=box.top+metrics.px(2); + const RECT badge{left,top,std::min(box.right,left+width),top+metrics.px(17)}; + rounded(item.hDC,badge,metrics.px(4),key,key); + text(item.hDC,badge,shortcut.c_str(),accent,DT_CENTER); + if(separator!=label.npos) + text(item.hDC,{box.left+1,badge.bottom,box.right-1,box.bottom-1}, + label.c_str()+separator+1,ink,DT_CENTER); + return; + } + const LONG top=(box.top+box.bottom-metrics.px(18))/2; + const RECT badge{box.left+padding,top,std::min(box.left+padding+width,box.right-padding),top+metrics.px(18)}; + rounded(item.hDC,badge,metrics.px(4),key,key); + text(item.hDC,badge,shortcut.c_str(),accent,DT_CENTER); + if(separator!=label.npos) + text(item.hDC,{badge.right+padding,box.top,box.right-padding,box.bottom},label.c_str()+separator+1,ink); +} diff --git a/src/files_lavender_dialogs.inl b/src/files_lavender_dialogs.inl new file mode 100644 index 0000000..e4c3851 --- /dev/null +++ b/src/files_lavender_dialogs.inl @@ -0,0 +1,359 @@ +constexpr auto lavenderDialogWarning=L"KSwitcher.Files.Lavender.Warning"; +constexpr auto lavenderFileOperation=L"KSwitcher.Files.Lavender.FileOperation"; +constexpr int lavenderSidebarLabel=418; +constexpr int operationHeaderHeight=27; +constexpr COLORREF operationSurface=RGB(242,239,251), operationBorder=RGB(111,96,166); + +bool isLavenderFileOperation(HWND dialog) { return GetPropW(dialog,lavenderFileOperation)!=nullptr; } +void markLavenderFileOperation(HWND dialog) +{ + if(lavenderFiles()) SetPropW(dialog,lavenderFileOperation,reinterpret_cast(1)); +} + +COLORREF lavenderDialogSurface(HWND dialog) +{ + return isLavenderFileOperation(dialog)?operationSurface:lavender::surface; +} + +HFONT dialogUiFont() { return lavenderFiles() && lavender::font?lavender::font:mono; } + +bool dialogClass(HWND control,const wchar_t *name) +{ + wchar_t type[64]{}; + GetClassNameW(control,type,static_cast(std::size(type))); + return _wcsicmp(type,name)==0; +} + +COLORREF dialogEdge(HWND dialog) +{ + return GetPropW(dialog,lavenderDialogWarning)?RGB(161,43,72):lavender::accent; +} + +void paintLavenderDialogButton(HWND control,HDC dc,RECT bounds,bool pressed,bool focused,bool primary) +{ + using namespace lavender; + const LavenderMetrics metrics(control); + const bool enabled=IsWindowEnabled(control)!=FALSE; + const auto id=GetDlgCtrlID(control); + const auto dialog=GetParent(control); + const bool operation=isLavenderFileOperation(dialog); + const auto accentColor=id==IDCANCEL || id==IDNO?accent:dialogEdge(dialog); + const auto bg=!enabled?canvas:primary?accentColor:pressed?selection:operation?surface:path; + fill(dc,bounds,lavenderDialogSurface(dialog)); + InflateRect(&bounds,-metrics.px(1),-metrics.px(1)); + rounded(dc,bounds,metrics.px(6),bg,focused?accentColor:primary?bg:enabled && operation?operationBorder:line); + wchar_t label[128]{}; + GetWindowTextW(control,label,static_cast(std::size(label))); + const auto previous=SelectObject(dc,reinterpret_cast(SendMessageW(control,WM_GETFONT,0,0))); + const auto mode=SetBkMode(dc,TRANSPARENT); + const auto color=SetTextColor(dc,!enabled?muted:primary?surface:ink); + InflateRect(&bounds,-metrics.px(3),0); + DrawTextW(dc,label,-1,&bounds,DT_CENTER|DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS); + if(focused && primary) + { + InflateRect(&bounds,0,-metrics.px(3)); + DrawFocusRect(dc,&bounds); + } + SetTextColor(dc,color); + SetBkMode(dc,mode); + SelectObject(dc,previous); +} + +void paintLavenderToggle(HWND control,HDC dc,RECT bounds,bool radio) +{ + using namespace lavender; + const LavenderMetrics metrics(control); + const int side=std::min(metrics.px(14),static_cast(bounds.bottom-bounds.top)); + const LONG x=bounds.left+metrics.px(1), y=(bounds.top+bounds.bottom-side)/2; + const bool checked=SendMessageW(control,BM_GETCHECK,0,0)==BST_CHECKED; + const bool enabled=IsWindowEnabled(control)!=FALSE; + const RECT indicator{x,y,x+side,y+side}; + fill(dc,bounds,lavenderDialogSurface(GetParent(control))); + rounded(dc,indicator,radio?side/2:metrics.px(3),checked?accent:path,enabled?accent:line); + if(checked && radio) + { + auto dot=indicator; + InflateRect(&dot,-side/3,-side/3); + rounded(dc,dot,side/4,surface,surface); + } + else if(checked) + { + const auto old=SelectObject(dc,GetStockObject(DC_PEN)); + SetDCPenColor(dc,surface); + const POINT check[]{{x+side/4,y+side/2},{x+side*2/5,y+side*2/3},{x+side*3/4,y+side/3}}; + Polyline(dc,check,static_cast(std::size(check))); + SelectObject(dc,old); + } + bounds.left=x+side+metrics.px(6); + wchar_t label[128]{}; + GetWindowTextW(control,label,static_cast(std::size(label))); + const auto previous=SelectObject(dc,reinterpret_cast(SendMessageW(control,WM_GETFONT,0,0))); + SetBkMode(dc,TRANSPARENT); + SetTextColor(dc,enabled?ink:muted); + DrawTextW(dc,label,-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS); + if(GetFocus()==control) + { + RECT extent{}; + DrawTextW(dc,label,-1,&extent,DT_SINGLELINE|DT_CALCRECT); + bounds.right=std::min(bounds.right,bounds.left+extent.right+metrics.px(3)); + DrawFocusRect(dc,&bounds); + } + SelectObject(dc,previous); +} + +LRESULT CALLBACK lavenderNativeButton(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + if(!lavenderFiles()) return DefSubclassProc(control,message,wp,lp); + const auto style=GetWindowLongPtrW(control,GWL_STYLE)&BS_TYPEMASK; + if(message==WM_PAINT || message==WM_PRINTCLIENT) + { + PAINTSTRUCT paint{}; + const auto dc=message==WM_PAINT?BeginPaint(control,&paint):reinterpret_cast(wp); + RECT bounds{}; + GetClientRect(control,&bounds); + if(style==BS_GROUPBOX) + { + const LavenderMetrics metrics(control); + auto frame=bounds; + frame.top+=metrics.px(7); + lavender::fill(dc,bounds,lavender::surface); + lavender::rounded(dc,frame,metrics.px(7),lavender::surface,lavender::line); + wchar_t label[96]{}; + GetWindowTextW(control,label,static_cast(std::size(label))); + paintDialogCaption(dc,{bounds.left,bounds.top,bounds.right,bounds.top+metrics.px(15)},label, + static_cast(GetStockObject(WHITE_BRUSH)),lavender::muted, + reinterpret_cast(SendMessageW(control,WM_GETFONT,0,0))); + } + else if(style==BS_AUTOCHECKBOX || style==BS_AUTORADIOBUTTON) + paintLavenderToggle(control,dc,bounds,style==BS_AUTORADIOBUTTON); + else paintLavenderDialogButton(control,dc,bounds,(SendMessageW(control,BM_GETSTATE,0,0)&BST_PUSHED)!=0, + GetFocus()==control,style==BS_DEFPUSHBUTTON); + if(message==WM_PAINT) EndPaint(control,&paint); + return 0; + } + const auto result=DefSubclassProc(control,message,wp,lp); + if(message==WM_SETFOCUS || message==WM_KILLFOCUS || message==WM_ENABLE || message==BM_SETSTATE || + message==BM_SETCHECK || message==BM_SETSTYLE || message==WM_SETTEXT || + message==WM_LBUTTONUP || message==WM_KEYUP) + InvalidateRect(control,nullptr,FALSE); + return result; +} + +LRESULT CALLBACK lavenderEditEdge(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + if(message==WM_NCCALCSIZE && lavenderFiles()) + { + const auto result=DefSubclassProc(control,message,wp,lp); + auto &client=*reinterpret_cast(lp); + const auto inset=LavenderMetrics(control).px(2); + InflateRect(&client,-inset,-inset); + return result; + } + if(message==WM_NCPAINT && lavenderFiles()) + { + const auto dc=GetWindowDC(control); + if(!dc) return DefSubclassProc(control,message,wp,lp); + RECT bounds{}, client{}; + GetWindowRect(control,&bounds); + GetClientRect(control,&client); + MapWindowPoints(control,nullptr,reinterpret_cast(&client),2); + OffsetRect(&client,-bounds.left,-bounds.top); + OffsetRect(&bounds,-bounds.left,-bounds.top); + ExcludeClipRect(dc,client.left,client.top,client.right,client.bottom); + const auto dialog=GetParent(control); + const bool operation=isLavenderFileOperation(dialog); + lavender::fill(dc,bounds,lavenderDialogSurface(dialog)); + lavender::rounded(dc,bounds,LavenderMetrics(control).px(4),operation?lavender::surface:lavender::path, + GetFocus()==control?(operation?dialogEdge(dialog):lavender::activeEdge):operation?operationBorder:lavender::line); + ReleaseDC(control,dc); + return 0; + } + const auto result=DefSubclassProc(control,message,wp,lp); + if((message==WM_SETFOCUS || message==WM_KILLFOCUS) && lavenderFiles()) + RedrawWindow(control,nullptr,nullptr,RDW_INVALIDATE|RDW_FRAME); + return result; +} + +void paintLavenderComboFace(HWND control,HDC dc,RECT bounds,const wchar_t *label) +{ + using namespace lavender; + const LavenderMetrics metrics(control); + const bool focused=GetFocus()==control; + const auto dialog=GetParent(control); + const bool operation=isLavenderFileOperation(dialog); + fill(dc,bounds,lavenderDialogSurface(dialog)); + rounded(dc,bounds,metrics.px(5),operation?surface:path, + focused?(operation?dialogEdge(dialog):activeEdge):operation?operationBorder:line); + const LONG center=label[0]?bounds.right-metrics.px(10):(bounds.left+bounds.right)/2; + const LONG middle=(bounds.top+bounds.bottom)/2; + const int arm=metrics.px(3); + const auto previous=SelectObject(dc,GetStockObject(DC_PEN)); + SetDCPenColor(dc,IsWindowEnabled(control)?accent:muted); + const POINT arrow[]{{center-arm,middle-arm/2},{center,middle+arm/2},{center+arm,middle-arm/2}}; + Polyline(dc,arrow,static_cast(std::size(arrow))); + SelectObject(dc,previous); + bounds.left+=metrics.px(7); + bounds.right-=metrics.px(20); + const auto oldFont=SelectObject(dc,reinterpret_cast(SendMessageW(control,WM_GETFONT,0,0))); + SetTextColor(dc,IsWindowEnabled(control)?ink:muted); + SetBkMode(dc,TRANSPARENT); + DrawTextW(dc,label,-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS|DT_NOPREFIX); + SelectObject(dc,oldFont); +} + +LRESULT CALLBACK lavenderNativeCombo(HWND control,UINT message,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR) +{ + if(lavenderFiles() && (message==WM_PAINT || message==WM_PRINTCLIENT)) + { + PAINTSTRUCT paint{}; + const auto dc=message==WM_PAINT?BeginPaint(control,&paint):reinterpret_cast(wp); + RECT bounds{}; + GetClientRect(control,&bounds); + const auto length=GetWindowTextLengthW(control); + std::wstring label(length+1,L'\0'); + GetWindowTextW(control,label.data(),static_cast(label.size())); + paintLavenderComboFace(control,dc,bounds,label.c_str()); + if(message==WM_PAINT) EndPaint(control,&paint); + return 0; + } + const auto result=DefSubclassProc(control,message,wp,lp); + if(message==WM_SETFOCUS || message==WM_KILLFOCUS || message==CB_SETCURSEL || message==WM_ENABLE) + InvalidateRect(control,nullptr,FALSE); + return result; +} + +void styleLavenderDialogControls(HWND dialog) +{ + const bool modern=lavenderFiles(); + const bool custom=(GetWindowLongPtrW(dialog,GWL_STYLE)&WS_CAPTION)==0; + if(!custom) styleLavenderCaption(dialog,modern); + for(auto control=GetWindow(dialog,GW_CHILD);control;control=GetWindow(control,GW_HWNDNEXT)) + { + DWORD_PTR oldEdge{}; + if(!modern) + { + if(GetWindowSubclass(control,lavenderEditEdge,1,&oldEdge)) + { + RemoveWindowSubclass(control,lavenderEditEdge,1); + SetWindowLongPtrW(control,GWL_EXSTYLE,GetWindowLongPtrW(control,GWL_EXSTYLE)|oldEdge); + SendMessageW(control,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN, + MAKELPARAM(EC_USEFONTINFO,EC_USEFONTINFO)); + SetWindowPos(control,nullptr,0,0,0,0,SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); + } + if(dialogClass(control,WC_TREEVIEWW)) + { + const auto style=GetWindowLongPtrW(control,GWL_STYLE); + SetWindowLongPtrW(control,GWL_STYLE,(style&~TVS_FULLROWSELECT)|WS_BORDER|TVS_HASLINES); + TreeView_SetBkColor(control,CLR_NONE); + TreeView_SetTextColor(control,CLR_NONE); + TreeView_SetLineColor(control,CLR_DEFAULT); + SetWindowPos(control,nullptr,0,0,0,0,SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); + } + continue; + } + if(custom) SendMessageW(control,WM_SETFONT,reinterpret_cast(dialogUiFont()),FALSE); + if(dialogClass(control,L"Button")) + { + const auto type=GetWindowLongPtrW(control,GWL_STYLE)&BS_TYPEMASK; + DWORD_PTR existing{}; + if(type!=BS_OWNERDRAW && !GetWindowSubclass(control,lavenderNativeButton,2,&existing)) + SetWindowSubclass(control,lavenderNativeButton,2,0); + } + else if(dialogClass(control,WC_TREEVIEWW)) + { + const auto style=GetWindowLongPtrW(control,GWL_STYLE); + SetWindowLongPtrW(control,GWL_STYLE,(style&~(WS_BORDER|TVS_HASLINES))|TVS_FULLROWSELECT); + TreeView_SetBkColor(control,lavender::path); + TreeView_SetTextColor(control,lavender::ink); + TreeView_SetLineColor(control,lavender::activeEdge); + SetWindowPos(control,nullptr,0,0,0,0,SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); + } + else if(dialogClass(control,L"ComboBox")) + { + const auto style=GetWindowLongPtrW(control,GWL_STYLE); + if((style&3)==CBS_DROPDOWNLIST && !(style&(CBS_OWNERDRAWFIXED|CBS_OWNERDRAWVARIABLE))) + SetWindowSubclass(control,lavenderNativeCombo,1,0); + } + else if((dialogClass(control,L"KSwitcher.Files.FarEdit") || + (dialogClass(control,L"Edit") && !(GetWindowLongPtrW(control,GWL_STYLE)&ES_READONLY))) && + !GetWindowSubclass(control,lavenderEditEdge,1,&oldEdge)) + { + const auto style=GetWindowLongPtrW(control,GWL_EXSTYLE); + SetWindowLongPtrW(control,GWL_EXSTYLE,style&~WS_EX_CLIENTEDGE); + SetWindowSubclass(control,lavenderEditEdge,1,style&WS_EX_CLIENTEDGE); + SetWindowPos(control,nullptr,0,0,0,0,SWP_FRAMECHANGED|SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE); + const auto padding=LavenderMetrics(control).px(6); + SendMessageW(control,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,MAKELPARAM(padding,padding)); + } + } + RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN); +} + +INT_PTR lavenderDialogColors(HWND dialog,UINT message,WPARAM wp,LPARAM lp) +{ + if(message==WM_NCDESTROY) RemovePropW(dialog,lavenderFileOperation); + if(!lavenderFiles()) return FALSE; + if(message!=WM_CTLCOLORDLG && message!=WM_CTLCOLORSTATIC && message!=WM_CTLCOLOREDIT && message!=WM_CTLCOLORLISTBOX && + message!=WM_CTLCOLORBTN) return FALSE; + const auto dc=reinterpret_cast(wp); + const auto control=reinterpret_cast(lp); + const bool field=message==WM_CTLCOLOREDIT || + (message==WM_CTLCOLORSTATIC && dialogClass(control,L"KSwitcher.Files.FarEdit")); + const auto background=field?(isLavenderFileOperation(dialog)?lavender::surface:lavender::path): + GetDlgCtrlID(control)==lavenderSidebarLabel && message==WM_CTLCOLORSTATIC?lavender::path:lavenderDialogSurface(dialog); + SetTextColor(dc,IsWindowEnabled(control)?lavender::ink:lavender::muted); + SetBkColor(dc,background); + SetDCBrushColor(dc,background); + return reinterpret_cast(GetStockObject(DC_BRUSH)); +} + +RECT paintLavenderDialogFrame(HWND dialog,HDC dc,RECT client,const wchar_t *title,const wchar_t *hints=nullptr) +{ + using namespace lavender; + const LavenderMetrics metrics(dialog); + fill(dc,client,canvas); + const bool operation=isLavenderFileOperation(dialog); + const auto edge=dialogEdge(dialog); + LONG headerBottom=client.top+metrics.px(operationHeaderHeight); + if(operation) + { + for(auto control=GetWindow(dialog,GW_CHILD);control;control=GetWindow(control,GW_HWNDNEXT)) + { + if(!IsWindowVisible(control)) continue; + RECT bounds{}; + GetWindowRect(control,&bounds); + MapWindowPoints(nullptr,dialog,reinterpret_cast(&bounds),2); + headerBottom=std::min(headerBottom,bounds.top); + } + rounded(dc,client,metrics.px(9),edge,edge); + const int stroke=metrics.px(2); + auto inner=client; + InflateRect(&inner,-stroke,-stroke); + const int diameter=metrics.px(14); + const auto clip=CreateRoundRectRgn(inner.left,inner.top,inner.right+1,inner.bottom+1,diameter,diameter); + const auto saved=SaveDC(dc); + if(clip && saved) + { + ExtSelectClipRgn(dc,clip,RGN_AND); + fill(dc,{inner.left,std::max(inner.top,headerBottom),inner.right,inner.bottom},operationSurface); + } + if(saved) RestoreDC(dc,saved); + if(clip) DeleteObject(clip); + } + else rounded(dc,client,metrics.px(9),surface,line); + auto content=client; + const int inset=metrics.px(10); + InflateRect(&content,-inset,0); + std::wstring_view caption(title); + const auto first=caption.find_first_not_of(L' '); + if(first!=caption.npos) + { + caption=caption.substr(first,caption.find_last_not_of(L' ')-first+1); + const auto titleInset=dialogFrameMetrics(metrics.dpi).content(); + auto label=RECT{client.left+titleInset,client.top+metrics.px(4),content.right,client.top+metrics.px(23)}; + if(operation) label.bottom=headerBottom; + text(dc,label,std::wstring(caption).c_str(),operation?surface:edge); + } + if(hints) text(dc,{content.left,client.bottom-metrics.px(21),content.right,client.bottom},hints,muted,DT_CENTER); + return content; +} diff --git a/src/files_main.cpp b/src/files_main.cpp index bf9e0b1..474f2d4 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -939,6 +940,10 @@ enum Color { PanelBlue, Text, Frame, Dialog, Selection, Footer, PanelCursor, Col constexpr std::array defaultColors{RGB(0,0,128), RGB(230,255,255), RGB(0,255,255), RGB(0,128,128), RGB(0,0,0), RGB(0,128,128), RGB(0,128,128)}; auto colors=defaultColors; +enum class FilesAppearance : DWORD { Far, Lavender }; +constexpr auto filesAppearanceKey=L"AppearanceMode"; +FilesAppearance filesAppearance=FilesAppearance::Far; +bool lavenderFiles() { return filesAppearance==FilesAppearance::Lavender; } constexpr auto placementPreference = L"WindowPlacement"; bool restorePlacement(HWND window) @@ -980,6 +985,7 @@ struct FilesNoticeOptions FilesNoticeTone tone{FilesNoticeTone::dialog}; bool processes{}; bool saveChanges{}, chooseTransfer{}; + bool fileOperation{}; const wchar_t *accept{}, *decline{}; }; INT_PTR showFilesNotice(HWND owner,const wchar_t *text,const wchar_t *title,FilesNoticeOptions options={}); @@ -1012,9 +1018,19 @@ void savePreference(const wchar_t *name, DWORD value) } #include "files_styles.inl" +#include "files_lavender.inl" FileRowStyle panelRowStyle(const Panel &panel,size_t row,bool cursor,bool activePanel) { + if(lavenderFiles() && row=panel.rows.size() || panel.sizes[row]==L"Up") return {foreground,background}; @@ -1332,6 +1348,12 @@ bool applyFont(HWND owner, LOGFONTW font, int points) return true; } +UINT_PTR CALLBACK lavenderSystemPicker(HWND dialog,UINT message,WPARAM,LPARAM) +{ + if(message==WM_INITDIALOG) styleLavenderCaption(dialog,true); + return 0; +} + bool chooseDisplayFont(HWND owner,LOGFONTW &font,int &points,int maximum=24) { CHOOSEFONTW dialog{}; @@ -1340,6 +1362,11 @@ bool chooseDisplayFont(HWND owner,LOGFONTW &font,int &points,int maximum=24) dialog.lpLogFont=&font; dialog.iPointSize=points; dialog.Flags=CF_SCREENFONTS|CF_INITTOLOGFONTSTRUCT|CF_LIMITSIZE; + if(lavenderFiles()) + { + dialog.Flags|=CF_ENABLEHOOK; + dialog.lpfnHook=lavenderSystemPicker; + } dialog.nSizeMin=8; dialog.nSizeMax=maximum; if(!ChooseFontW(&dialog)) return false; @@ -1376,6 +1403,11 @@ bool choosePanelColor(HWND owner,COLORREF &color,COLORREF *custom) dialog.rgbResult=color; dialog.lpCustColors=custom; dialog.Flags=CC_RGBINIT | CC_FULLOPEN; + if(lavenderFiles()) + { + dialog.Flags|=CC_ENABLEHOOK; + dialog.lpfnHook=lavenderSystemPicker; + } if(!ChooseColorW(&dialog)) return false; color=dialog.rgbResult; return true; @@ -1391,10 +1423,11 @@ void paintText(HDC dc, RECT rect, const wchar_t *text, COLORREF foreground, COLO SetTextAlign(dc,alignment); } -void paintMenuLabel(HDC dc,RECT rect,const std::wstring &text,size_t access,COLORREF foreground,COLORREF background) +void paintMenuLabel(HDC dc,RECT rect,const std::wstring &text,size_t access,COLORREF foreground,COLORREF background, + COLORREF accessInk=RGB(255,255,0),HFONT font=nullptr) { - paintText(dc,rect,text.c_str(),foreground,background); - ks::files::paintMenuAccessKey(dc,rect,{rect.left+5,rect.top+3},text,access,RGB(255,255,0)); + paintText(dc,rect,text.c_str(),foreground,background,false,font); + ks::files::paintMenuAccessKey(dc,rect,{rect.left+5,rect.top+3},text,access,accessInk); } struct DialogFramePadding @@ -1708,7 +1741,10 @@ bool hasSelectionSummary() int clampPanelDivider(int position,int width) { - return std::clamp(position,120,std::max(120,width-120)); + const int panelMinimum=lavenderFiles() && panels[0].list? + LavenderMetrics(GetParent(panels[0].list)).px(135):120; + const int minimum=std::min(width/2,panelMinimum); + return std::clamp(position,minimum,width-minimum); } int panelDivider(int width) @@ -1732,12 +1768,15 @@ void layout(HWND window,bool activeOnly) RECT rect{}; GetClientRect(window, &rect); int width = rect.right, height = rect.bottom; - const int inputTop=height-textHeight-terminalTextHeight; + const bool lavender=lavenderFiles(); + const LavenderMetrics modern(window); + const int commandHeight=lavender?modern.row+modern.px(widthmaxButtons?SW_SHOWNA:SW_HIDE); } - const int headingTop=pathTop+textHeight+(compactLayout?2:6); + const int headingTop=panelTop+pathHeight+(lavender?modern.px(7):compactLayout?2:6); + const int rowHeight=lavender?std::max(modern.row,textHeight):textHeight; + const auto panelFont=reinterpret_cast(lavender?lavender::font:mono); + SendMessageW(status,WM_SETFONT,panelFont,FALSE); for (int i = 0; i < 2; ++i) { int x = i ? middle + 2 : 0; int end = i ? width : middle - 2; - place(panels[i].path, x+panelMargin,pathTop,std::max(0,end-x-2*panelMargin),textHeight); - int headingHeight=detailedPanel(panels[i])?textHeight:0; - const int listWidth=std::max(0,end-x-panelMargin-3-scrollBarWidth(panels[i].list)); + place(panels[i].path,x+inset,panelTop,std::max(0,end-x-2*inset),pathHeight); + const int headingHeight=detailedPanel(panels[i])?rowHeight:0; + const int listWidth=std::max(0,end-x-(lavender?2*inset:panelMargin+3)-scrollBarWidth(panels[i].list)); const bool panelVisible=!gitMode && !terminalVisible && (!quickViewWindow || i==quickViewSource); ShowWindow(panels[i].path,panelVisible?SW_SHOWNA:SW_HIDE); ShowWindow(panels[i].list,panelVisible?SW_SHOWNA:SW_HIDE); - place(panels[i].heading,x+panelMargin,headingTop,listWidth,headingHeight); + SendMessageW(panels[i].selectionSummary,WM_SETFONT,panelFont,FALSE); + if(SendMessageW(panels[i].list,LB_GETITEMHEIGHT,0,0)!=rowHeight) + SendMessageW(panels[i].list,LB_SETITEMHEIGHT,0,rowHeight); + place(panels[i].heading,x+inset,headingTop,listWidth,headingHeight); ShowWindow(panels[i].heading,panelVisible && detailedPanel(panels[i])?SW_SHOWNA:SW_HIDE); - place(panels[i].list,x+panelMargin,headingTop+headingHeight,listWidth, + place(panels[i].list,x+inset,headingTop+headingHeight,listWidth, std::max(0,panelBottom-headingTop-headingHeight)); - place(panels[i].selectionSummary,x+8,panelBottom+detailsInset,std::max(0,end-x-16),summaryHeight); + place(panels[i].selectionSummary,x+detailsInset,detailsTop,std::max(0,end-x-2*detailsInset),summaryHeight); ShowWindow(panels[i].selectionSummary,panelVisible && summaryHeight?SW_SHOWNA:SW_HIDE); } place(menuBar,0,0,width,textHeight+4); @@ -1799,7 +1849,7 @@ void layout(HWND window,bool activeOnly) } const int detailsLeft=active?middle+2:0; const int detailsRight=active?width:middle-2; - place(status,detailsLeft+8,panelBottom+detailsInset+summaryHeight,std::max(0,detailsRight-detailsLeft-16),textHeight); + place(status,detailsLeft+detailsInset,detailsTop+summaryHeight,std::max(0,detailsRight-detailsLeft-2*detailsInset),textHeight); const auto ¤t=panels[active]; const auto prompt=panelLocation(current)+(terminalVisible?L"> ":L">"); SetWindowTextW(terminalPrompt,prompt.c_str()); @@ -1816,8 +1866,8 @@ void layout(HWND window,bool activeOnly) place(terminalInput,4+promptWidth,inputTop,std::max(0,width-8-promptWidth),terminalTextHeight); if(activeOnly) { - const RECT details{0,panelBottom+detailsInset+summaryHeight,width, - panelBottom+detailsInset+summaryHeight+textHeight}; + const RECT details{0,lavender?driveHeight:detailsTop+summaryHeight,width, + detailsTop+summaryHeight+textHeight+(lavender?modern.px(4):0)}; if(driveHeight) { const RECT drives{0,0,width,driveHeight}; @@ -1842,14 +1892,19 @@ void layout(HWND window,bool activeOnly) ShowWindow(terminalInput,gitMode?SW_HIDE:SW_SHOWNA); terminalView.layout(terminalOutput,showOutput && !sshPrompt,terminalBottom-4); sshView.layout(terminalOutput,showOutput && sshPrompt.has_value(),terminalBottom-4); + const int gap=modern.px(5); + const int barWidth=std::max(0,std::min(width-gap,modern.px(880)+gap)); constexpr int refreshExtra=4; for (int i = 0; i < static_cast(std::size(commands)); ++i) { constexpr int unit=10; const int total=static_cast(std::size(commands))*unit+refreshExtra; - const int left=i?(i*unit+refreshExtra)*width/total:0; - const int right=((i+1)*unit+refreshExtra)*width/total; - place(commands[i],left,height-textHeight,right-left,textHeight); + const int available=lavender?barWidth:width; + const int left=i?(i*unit+refreshExtra)*available/total:0; + const int right=((i+1)*unit+refreshExtra)*available/total; + if(lavender) place(commands[i],left+gap,height-commandHeight+gap, + std::max(0,right-left-gap),commandHeight-2*gap); + else place(commands[i],left,height-textHeight,right-left,textHeight); ShowWindow(commands[i],gitMode?SW_HIDE:SW_SHOWNA); } if(quickViewWindow) @@ -4661,6 +4716,7 @@ void openSelectedWithSystem(const Panel &panel) folder?L"Cannot open the selected folder in File Explorer.":L"Cannot open the selected file."); } +#include "files_lavender_dialogs.inl" #include "files_dialog_input.inl" ks::files::TextDialogs textWindowDialogs() @@ -4924,6 +4980,7 @@ void centerDialogEditText(HWND field) SelectObject(dc,oldFont); ReleaseDC(field,dc); } + if(lavenderFiles()) InflateRect(&edit,-LavenderMetrics(field).px(6),0); SendMessageW(field,EM_SETRECTNP,0,reinterpret_cast(&edit)); } @@ -4973,7 +5030,7 @@ bool registerFarEdit(HINSTANCE instance) void prepareDialogEdit(HWND field) { - SendMessageW(field,WM_SETFONT,reinterpret_cast(mono),FALSE); + SendMessageW(field,WM_SETFONT,reinterpret_cast(dialogUiFont()),FALSE); const auto margin=MulDiv(2,GetDpiForWindow(field),96); SendMessageW(field,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,MAKELPARAM(margin,margin)); } @@ -4994,7 +5051,8 @@ void fitFarEditToLine(HWND field) RECT cell{}; GetWindowRect(field,&cell); MapWindowPoints(nullptr,parent,reinterpret_cast(&cell),2); - const auto height=std::max(metrics.tmHeight,1L); + const auto height=lavenderFiles()?std::min(cell.bottom-cell.top, + metrics.tmHeight+LavenderMetrics(field).px(8)):std::max(metrics.tmHeight,1L); SetWindowPos(field,nullptr,cell.left,cell.top+(cell.bottom-cell.top-height)/2, cell.right-cell.left,height,SWP_NOZORDER|SWP_NOACTIVATE); } @@ -5030,7 +5088,8 @@ void layoutDialogContent(HWND dialog,int firstControl) const auto frame=dialogFrameMetrics(dpi); const auto first=dialogControlBounds(dialog,firstControl); const int dx=frame.content()-first.left; - const int dy=dialogListInset(frame,textHeight)+MulDiv(1,dpi,96)-first.top; + const int header=isLavenderFileOperation(dialog)?LavenderMetrics(dialog).px(operationHeaderHeight+2):0; + const int dy=std::max(header,dialogListInset(frame,textHeight)+MulDiv(1,dpi,96))-first.top; for(auto control=GetWindow(dialog,GW_CHILD);control;control=GetWindow(control,GW_HWNDNEXT)) { RECT bounds{}; @@ -5156,6 +5215,12 @@ void layoutDialogButtons(HWND dialog,int divider,std::initializer_list cont void drawFarDialogLabel(HDC dc,RECT bounds,std::wstring caption,bool centered) { + if(lavenderFiles()) + { + DrawTextW(dc,caption.c_str(),-1,&bounds,DT_SINGLELINE|DT_VCENTER|DT_END_ELLIPSIS| + (centered?DT_CENTER:DT_LEFT)); + return; + } const auto access=caption.find(L'&'); if(access!=caption.npos) caption.erase(access,1); SIZE extent{}; @@ -5171,6 +5236,14 @@ void drawFarDialogLabel(HDC dc,RECT bounds,std::wstring caption,bool centered) void paintDialogButton(const DRAWITEMSTRUCT &item,COLORREF surface,COLORREF foreground,bool farAccessKeys=false) { + const auto defaultButton=SendMessageW(GetParent(item.hwndItem),DM_GETDEFID,0,0); + const bool isDefault=HIWORD(defaultButton)==DC_HASDEFID && LOWORD(defaultButton)==item.CtlID; + if(lavenderFiles()) + { + paintLavenderDialogButton(item.hwndItem,item.hDC,item.rcItem,(item.itemState&ODS_SELECTED)!=0, + (item.itemState&ODS_FOCUS)!=0,isDefault); + return; + } wchar_t label[32]{}; GetWindowTextW(item.hwndItem,label,static_cast(std::size(label))); const bool focused=(item.itemState&(ODS_FOCUS|ODS_SELECTED))!=0; @@ -5182,8 +5255,6 @@ void paintDialogButton(const DRAWITEMSTRUCT &item,COLORREF surface,COLORREF fore SetBkMode(item.hDC,TRANSPARENT); SetTextColor(item.hDC,(item.itemState&ODS_DISABLED)?RGB(128,128,128):focused?colors[Text]:foreground); auto rect=item.rcItem; - const auto defaultButton=SendMessageW(GetParent(item.hwndItem),DM_GETDEFID,0,0); - const bool isDefault=HIWORD(defaultButton)==DC_HASDEFID && LOWORD(defaultButton)==item.CtlID; const auto caption=(isDefault?L"{ ":L"[ ")+std::wstring(label)+(isDefault?L" }":L" ]"); if(farAccessKeys && !(item.itemState&ODS_DISABLED)) drawFarDialogLabel(item.hDC,rect,caption,true); else DrawTextW(item.hDC,caption.c_str(),-1,&rect,DT_CENTER|DT_VCENTER|DT_SINGLELINE); @@ -5193,6 +5264,9 @@ INT_PTR paintCopyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp, const wchar_t *caption, bool warning, std::initializer_list dividers, bool useDialogPalette=false, HWND scrollControl=nullptr,bool scrollEdit=false) { + if(message==WM_INITDIALOG && warning && lavenderFiles()) + SetPropW(dialog,lavenderDialogWarning,reinterpret_cast(1)); + if(message==WM_NCDESTROY) RemovePropW(dialog,lavenderDialogWarning); const auto foreground=useDialogPalette?colors[Text]:warning?RGB(255,255,255):RGB(0,0,0); const auto surface=useDialogPalette?colors[Dialog]:warning?RGB(128,0,0):RGB(192,192,192); const auto brush=useDialogPalette?teal:warning?warningBrush:static_cast(GetStockObject(LTGRAY_BRUSH)); @@ -5216,15 +5290,19 @@ INT_PTR paintCopyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp, const auto client=bounds; const auto black=static_cast(GetStockObject(useDialogPalette?DC_BRUSH:warning?WHITE_BRUSH:BLACK_BRUSH)); if(useDialogPalette) SetDCBrushColor(dc,foreground); - bounds=paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),brush,black); + const bool lavender=lavenderFiles(); + bounds=lavender?paintLavenderDialogFrame(dialog,dc,client,caption): + paintDialogFrame(dc,client,dialogFrameMetrics(GetDpiForWindow(dialog)),brush,black); for(const auto control:dividers) { const auto y=dialogDividerY(dialog,control); RECT divider{bounds.left+1,y,bounds.right-1,y+1}; - FillRect(dc,÷r,black); + if(lavender) lavender::fill(dc,divider,isLavenderFileOperation(dialog)?operationBorder:lavender::line); + else FillRect(dc,÷r,black); } - paintDialogFrameCaptions(dc,client,bounds,caption,brush,foreground,mono); - if(scrollControl) paintScrollPosition(dialog,dc,scrollControl,surface,scrollEdit); + if(!lavender) paintDialogFrameCaptions(dc,client,bounds,caption,brush,foreground,mono); + if(scrollControl) paintScrollPosition(dialog,dc,scrollControl, + lavender?lavenderDialogSurface(dialog):surface,scrollEdit); EndPaint(dialog,&paint); return TRUE; } @@ -5237,6 +5315,13 @@ INT_PTR paintCopyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp, return FALSE; } +INT_PTR paintFileOperationDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp,const wchar_t *caption, + bool warning,std::initializer_list dividers) +{ + if(message==WM_INITDIALOG) markLavenderFileOperation(dialog); + return paintCopyDialog(dialog,message,wp,lp,caption,warning,dividers); +} + struct FarDropDownBounds { RECT field,arrow; @@ -5244,6 +5329,7 @@ struct FarDropDownBounds ks::files::FarDropDownPalette farDropDownPalette() { + if(lavenderFiles()) return {lavender::path,lavender::ink,lavender::selection}; return {colors[Dialog],colors[Text],colors[Selection]}; } @@ -5310,9 +5396,13 @@ LRESULT CALLBACK paintFarCombo(HWND control,UINT message,WPARAM wp,LPARAM lp,UIN } const auto parts=farDropDownBounds(bounds); const bool enabled=IsWindowEnabled(control)!=FALSE; - paintFarDropDownText(dc,parts.field,label.c_str(),enabled); - ks::files::paintFarFieldArrow(dc,parts.arrow,enabled,GetDpiForWindow(control)); - if(GetFocus()==control) DrawFocusRect(dc,&parts.field); + if(lavenderFiles()) paintLavenderComboFace(control,dc,bounds,label.c_str()); + else + { + paintFarDropDownText(dc,parts.field,label.c_str(),enabled); + ks::files::paintFarFieldArrow(dc,parts.arrow,enabled,GetDpiForWindow(control)); + if(GetFocus()==control) DrawFocusRect(dc,&parts.field); + } if(message==WM_PAINT) EndPaint(control,&paint); return 0; } @@ -5365,7 +5455,7 @@ LRESULT CALLBACK paintFarCheckbox(HWND field,UINT message,WPARAM wp,LPARAM lp,UI { if(message==WM_KILLFOCUS) DestroyCaret(); const auto result=DefSubclassProc(field,message,wp,lp); - if(message==WM_SETFOCUS || ((message==WM_SIZE || message==WM_SETFONT) && GetFocus()==field)) + if(!lavenderFiles() && (message==WM_SETFOCUS || ((message==WM_SIZE || message==WM_SETFONT) && GetFocus()==field))) showFarCheckboxCaret(field); if(message==BM_SETCHECK || message==WM_SETTEXT || message==WM_ENABLE) InvalidateRect(field,nullptr,FALSE); @@ -5375,6 +5465,12 @@ LRESULT CALLBACK paintFarCheckbox(HWND field,UINT message,WPARAM wp,LPARAM lp,UI const auto dc=BeginPaint(field,&paint); RECT bounds{}; GetClientRect(field,&bounds); + if(lavenderFiles()) + { + paintLavenderToggle(field,dc,bounds,(GetWindowLongPtrW(field,GWL_STYLE)&BS_TYPEMASK)==BS_AUTORADIOBUTTON); + EndPaint(field,&paint); + return 0; + } const auto surface=static_cast(palette); const auto background=surface==FarCheckboxSurface::gray?RGB(192,192,192): surface==FarCheckboxSurface::warning?RGB(128,0,0):colors[Dialog]; @@ -5417,7 +5513,9 @@ void drawFarComboRow(const DRAWITEMSTRUCT &item) SendMessageW(item.hwndItem,CB_GETLBTEXT,item.itemID,reinterpret_cast(label)); const bool selected=(item.itemState&ODS_SELECTED)!=0 && (item.itemState&ODS_COMBOBOXEDIT)==0; const auto palette=farDropDownPalette(); - paintText(item.hDC,item.rcItem,label,palette.text,selected?palette.selection:palette.surface); + if(lavenderFiles()) paintDialogListRow(item.hDC,item.rcItem,label,dialogUiFont(),palette.text, + selected?palette.selection:palette.surface,LavenderMetrics(item.hwndItem).px(6)); + else paintText(item.hDC,item.rcItem,label,palette.text,selected?palette.selection:palette.surface); } CopyDestination validateCopyDestination(CopyRequest request,const std::wstring &value, @@ -5517,8 +5615,8 @@ INT_PTR CALLBACK copyDialog(HWND dialog, UINT message, WPARAM wp, LPARAM lp) return reinterpret_cast(teal); } const auto prompt=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); - const auto painted=prompt && prompt->ftpRename?paintCopyDialog(dialog,message,wp,lp,L" Rename ",false,{217}): - paintCopyDialog(dialog,message,wp,lp,prompt && prompt->move?L" Rename/Move ":L" Copy ",false,{213,214}); + const auto painted=prompt && prompt->ftpRename?paintFileOperationDialog(dialog,message,wp,lp,L" Rename ",false,{217}): + paintFileOperationDialog(dialog,message,wp,lp,prompt && prompt->move?L" Rename/Move ":L" Copy ",false,{213,214}); if(painted) return painted; if(message==WM_INITDIALOG) @@ -5770,6 +5868,21 @@ LRESULT CALLBACK paintCopyProgressBar(HWND bar,UINT message,WPARAM wp,LPARAM lp, const auto percent=std::clamp(SendMessageW(bar,PBM_GETPOS,0,0),LRESULT{0},LRESULT{100}); auto filled=bounds; filled.right=static_cast(bounds.right*percent/100); + if(lavenderFiles()) + { + const LavenderMetrics metrics(bar); + const auto label=std::to_wstring(percent)+L"%"; + lavender::fill(dc,bounds,lavender::surface); + lavender::rounded(dc,bounds,metrics.px(6),lavender::idleSelection,lavender::line); + lavender::rounded(dc,filled,metrics.px(6),lavender::accent,lavender::accent); + lavender::text(dc,bounds,label.c_str(),lavender::ink,DT_CENTER); + const auto saved=SaveDC(dc); + IntersectClipRect(dc,filled.left,filled.top,filled.right,filled.bottom); + lavender::text(dc,bounds,label.c_str(),lavender::surface,DT_CENTER); + RestoreDC(dc,saved); + EndPaint(bar,&paint); + return 0; + } FillRect(dc,&bounds,static_cast(GetStockObject(WHITE_BRUSH))); FillRect(dc,&filled,static_cast(GetStockObject(BLACK_BRUSH))); const auto label=std::to_wstring(percent)+L"%"; @@ -5879,17 +5992,19 @@ INT_PTR paintSearchDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) const auto &item=*reinterpret_cast(lp); if(item.CtlID==ks::files::searchHistoryButton) { - ks::files::paintFarFieldArrow(item.hDC,item.rcItem, + if(lavenderFiles()) paintLavenderComboFace(item.hwndItem,item.hDC,item.rcItem,L""); + else ks::files::paintFarFieldArrow(item.hDC,item.rcItem, !(item.itemState&ODS_DISABLED),GetDpiForWindow(item.hwndItem)); if(item.itemState&ODS_FOCUS) DrawFocusRect(item.hDC,&item.rcItem); return TRUE; } if(item.CtlType==ODT_STATIC) { - FillRect(item.hDC,&item.rcItem,static_cast(GetStockObject(LTGRAY_BRUSH))); - SelectObject(item.hDC,mono); + if(lavenderFiles()) lavender::fill(item.hDC,item.rcItem,lavender::surface); + else FillRect(item.hDC,&item.rcItem,static_cast(GetStockObject(LTGRAY_BRUSH))); + SelectObject(item.hDC,dialogUiFont()); SetBkMode(item.hDC,TRANSPARENT); - SetTextColor(item.hDC,RGB(0,0,0)); + SetTextColor(item.hDC,lavenderFiles()?lavender::ink:RGB(0,0,0)); wchar_t label[40]{}; GetWindowTextW(item.hwndItem,label,static_cast(std::size(label))); drawFarDialogLabel(item.hDC,item.rcItem,label,false); @@ -5993,7 +6108,7 @@ void prepareTextDialog(HWND dialog) const auto templateFont=reinterpret_cast(SendMessageW(dialog,WM_GETFONT,0,0)); const auto previous=SelectObject(dc,templateFont); GetTextMetricsW(dc,&templateMetrics); - SelectObject(dc,mono); + SelectObject(dc,dialogUiFont()); GetTextMetricsW(dc,&filesMetrics); SelectObject(dc,previous); ReleaseDC(dialog,dc); @@ -6009,7 +6124,7 @@ void prepareTextDialog(HWND dialog) const auto width=x(bounds.right-bounds.left),height=y(bounds.bottom-bounds.top); SetWindowPos(dialog,nullptr,(bounds.left+bounds.right-width)/2,(bounds.top+bounds.bottom-height)/2, width,height,SWP_NOZORDER|SWP_NOACTIVATE); - SendMessageW(dialog,WM_SETFONT,reinterpret_cast(mono),FALSE); + SendMessageW(dialog,WM_SETFONT,reinterpret_cast(dialogUiFont()),FALSE); const bool search=GetDlgItem(dialog,ks::files::searchOptionsDivider)!=nullptr; for(auto field=GetWindow(dialog,GW_CHILD);field;field=GetWindow(field,GW_HWNDNEXT)) { @@ -6018,7 +6133,7 @@ void prepareTextDialog(HWND dialog) MapWindowPoints(nullptr,dialog,reinterpret_cast(&rect),2); SetWindowPos(field,nullptr,x(rect.left),y(rect.top),x(rect.right)-x(rect.left),y(rect.bottom)-y(rect.top), SWP_NOZORDER|SWP_NOACTIVATE); - SendMessageW(field,WM_SETFONT,reinterpret_cast(mono),FALSE); + SendMessageW(field,WM_SETFONT,reinterpret_cast(dialogUiFont()),FALSE); wchar_t type[16]{}; GetClassNameW(field,type,static_cast(std::size(type))); if(lstrcmpiW(type,L"Button")==0 && (GetWindowLongPtrW(field,GWL_STYLE)&BS_TYPEMASK)==BS_AUTOCHECKBOX) @@ -6080,7 +6195,8 @@ void layoutFilesNotice(HWND dialog) const auto ¬ice=*reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); const auto frame=dialogFrameMetrics(GetDpiForWindow(dialog)); const auto inset=frame.content(); - const auto top=dialogListInset(frame,textHeight); + const int header=isLavenderFileOperation(dialog)?LavenderMetrics(dialog).px(operationHeaderHeight+2):0; + const auto top=std::max(header,dialogListInset(frame,textHeight)); const auto field=GetDlgItem(dialog,100); RECT client{}; GetClientRect(dialog,&client); @@ -6088,7 +6204,7 @@ void layoutFilesNotice(HWND dialog) TEXTMETRICW metrics{}; if(const auto dc=GetDC(field)) { - const auto previous=SelectObject(dc,mono); + const auto previous=SelectObject(dc,dialogUiFont()); GetTextMetricsW(dc,&metrics); SelectObject(dc,previous); ReleaseDC(field,dc); @@ -6129,6 +6245,8 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) { SetWindowLongPtrW(window,DWLP_USER,lp); const auto ¬ice=*reinterpret_cast(lp); + if(notice.options.fileOperation || isLavenderFileOperation(GetWindow(window,GW_OWNER))) + markLavenderFileOperation(window); prepareTextDialog(window); const auto field=GetDlgItem(window,100); SendMessageW(field,EM_SETMARGINS,EC_LEFTMARGIN|EC_RIGHTMARGIN,0); @@ -6166,7 +6284,7 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) RECT caption{},text{}; if(const auto dc=GetDC(window)) { - const auto previous=SelectObject(dc,mono); + const auto previous=SelectObject(dc,dialogUiFont()); DrawTextW(dc,notice.title.c_str(),-1,&caption,DT_CALCRECT|DT_SINGLELINE|DT_NOPREFIX); DrawTextW(dc,notice.text,-1,&text,DT_CALCRECT|DT_NOPREFIX|DT_EXPANDTABS); SelectObject(dc,previous); @@ -6188,6 +6306,7 @@ INT_PTR CALLBACK filesNoticeDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) if(!notice) return FALSE; const bool warning=notice->options.tone==FilesNoticeTone::warning; const bool palette=notice->options.tone==FilesNoticeTone::dialog; + if(warning && lavenderFiles()) SetPropW(window,lavenderDialogWarning,reinterpret_cast(1)); if(message==WM_CTLCOLORSTATIC && reinterpret_cast(lp)==GetDlgItem(window,100) && !palette) { const auto dc=reinterpret_cast(wp); @@ -6231,7 +6350,7 @@ void showFileOperationError(HWND owner,const wchar_t *title,const std::wstring & { setStatus(L""); const auto choice=showFilesNotice(owner,message.c_str(),title, - {.tone=FilesNoticeTone::warning,.processes=!lockPaths.empty()}); + {.tone=FilesNoticeTone::warning,.processes=!lockPaths.empty(),.fileOperation=true}); if(choice==showProcessesButton) showProcesses(owner,std::move(lockPaths)); } @@ -6242,7 +6361,7 @@ void showTextMessage(HWND owner,const wchar_t *text) INT_PTR CALLBACK cancelOperationDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) { - if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Operation interrupted ",true,{236})) + if(const auto painted=paintFileOperationDialog(window,message,wp,lp,L" Operation interrupted ",true,{236})) return painted; if(message==WM_INITDIALOG) { @@ -6286,10 +6405,11 @@ INT_PTR CALLBACK copyProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM lp std::wstring path(GetWindowTextLengthW(item.hwndItem)+1,L'\0'); GetWindowTextW(item.hwndItem,path.data(),static_cast(path.size())); auto bounds=item.rcItem; - FillRect(item.hDC,&bounds,static_cast(GetStockObject(LTGRAY_BRUSH))); - SelectObject(item.hDC,mono); + if(lavenderFiles()) lavender::fill(item.hDC,bounds,lavenderDialogSurface(window)); + else FillRect(item.hDC,&bounds,static_cast(GetStockObject(LTGRAY_BRUSH))); + SelectObject(item.hDC,dialogUiFont()); SetBkMode(item.hDC,TRANSPARENT); - SetTextColor(item.hDC,RGB(0,0,0)); + SetTextColor(item.hDC,lavenderFiles()?lavender::ink:RGB(0,0,0)); constexpr auto flags=DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX; const int prefix=wp==220?6:4; if(GetWindowTextLengthW(item.hwndItem)>prefix && path[prefix-2]==L':') @@ -6304,7 +6424,7 @@ INT_PTR CALLBACK copyProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM lp return TRUE; } const auto operation=reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); - if(const auto painted=paintCopyDialog(window,message,wp,lp, + if(const auto painted=paintFileOperationDialog(window,message,wp,lp, operation && operation->writingArchive?L" Pack ":operation && operation->move?L" Move ":L" Copy ",false,{228,229})) return painted; if(message==WM_DPICHANGED) @@ -6424,7 +6544,7 @@ LRESULT CALLBACK warningButtonKeys(HWND button,UINT message,WPARAM wp,LPARAM lp, INT_PTR CALLBACK warningDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) { - if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Warning ",true,{233,333,234})) + if(const auto painted=paintFileOperationDialog(window,message,wp,lp,L" Warning ",true,{233,333,234})) return painted; if(message==WM_INITDIALOG) { @@ -7262,9 +7382,9 @@ INT_PTR CALLBACK deleteConfirmationDialog(HWND window,UINT message,WPARAM wp,LPA if(message==WM_INITDIALOG) SetWindowLongPtrW(window,DWLP_USER,lp); const auto data=reinterpret_cast(GetWindowLongPtrW(window,DWLP_USER)); if(!data) return FALSE; - if(const auto painted=paintCopyDialog(window,message,wp,lp, + if(const auto painted=paintFileOperationDialog(window,message,wp,lp, data->readOnlyPrompt?L" Warning ":data->folderPrompt?L" Delete folder ":L" Delete ", - data->permanent,{243})) return painted; + data->permanent || (lavenderFiles() && data->readOnlyPrompt),{243})) return painted; if(message==WM_INITDIALOG) { prepareCopyDialog(window); @@ -7358,7 +7478,7 @@ INT_PTR CALLBACK deleteConfirmationDialog(HWND window,UINT message,WPARAM wp,LPA INT_PTR CALLBACK deleteProgressDialog(HWND window,UINT message,WPARAM wp,LPARAM lp) { - if(const auto painted=paintCopyDialog(window,message,wp,lp,L" Delete ",false,{248})) + if(const auto painted=paintFileOperationDialog(window,message,wp,lp,L" Delete ",false,{248})) return painted; if(message==WM_INITDIALOG) { @@ -7703,6 +7823,7 @@ std::wstring dialogFieldText(HWND field) INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) { + if(message==WM_INITDIALOG) markLavenderFileOperation(dialog); constexpr int label=360,field=361,divider=362,history=363,linkLabel=364,linkType=365, targetLabel=366,target=367,multiple=368,footer=369; const auto input=GetDlgItem(dialog,field); @@ -7742,16 +7863,19 @@ INT_PTR CALLBACK makeFolderDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) if(wp==linkType) { drawFarComboRow(item); return TRUE; } if(wp==history) { - ks::files::paintFarFieldArrow(item.hDC,item.rcItem,IsWindowEnabled(item.hwndItem), + if(lavenderFiles()) paintLavenderComboFace(item.hwndItem,item.hDC,item.rcItem,L""); + else ks::files::paintFarFieldArrow(item.hDC,item.rcItem,IsWindowEnabled(item.hwndItem), GetDpiForWindow(item.hwndItem)); return TRUE; } if(wp==label || wp==linkLabel || wp==targetLabel) { - FillRect(item.hDC,&item.rcItem,static_cast(GetStockObject(LTGRAY_BRUSH))); - SelectObject(item.hDC,mono); + if(lavenderFiles()) lavender::fill(item.hDC,item.rcItem,lavenderDialogSurface(dialog)); + else FillRect(item.hDC,&item.rcItem,static_cast(GetStockObject(LTGRAY_BRUSH))); + SelectObject(item.hDC,dialogUiFont()); SetBkMode(item.hDC,TRANSPARENT); - SetTextColor(item.hDC,IsWindowEnabled(item.hwndItem)?RGB(0,0,0):RGB(128,128,128)); + SetTextColor(item.hDC,lavenderFiles()?(IsWindowEnabled(item.hwndItem)?lavender::ink:lavender::muted): + IsWindowEnabled(item.hwndItem)?RGB(0,0,0):RGB(128,128,128)); drawFarDialogLabel(item.hDC,item.rcItem,dialogFieldText(item.hwndItem),false); return TRUE; } @@ -8337,7 +8461,7 @@ LRESULT CALLBACK panelKeys(HWND window, UINT message, WPARAM wp, LPARAM lp, UINT invalidatePanelCursorChange(window,previous); } if(message==WM_LBUTTONUP && GetFocus()==window) restoreCommandFocus(); - if(message==WM_PAINT && hasPanelColumns(panels[index])) + if(message==WM_PAINT && hasPanelColumns(panels[index]) && !lavenderFiles()) { auto dc=GetDC(window); if(dc) @@ -8358,6 +8482,8 @@ bool loadFilesPreferences(HWND window) { const auto [font,points]=readFilesFont(); if(!applyFont(window,font,points)) return false; + filesAppearance=preference(filesAppearanceKey,0)==static_cast(FilesAppearance::Lavender)? + FilesAppearance::Lavender:FilesAppearance::Far; loadColors(); dialogFramePadding={ std::min(preference(dialogFrameOuterKey,defaultDialogFramePadding.outer),maxDialogFramePadding), @@ -8830,6 +8956,9 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) { auto instance = GetModuleHandleW(nullptr); if(!loadFilesPreferences(window)) return -1; + lavender::setFont(GetDpiForWindow(window)); + FilesModalDialog::styleControls=[](HWND dialog) { if(lavenderFiles()) styleLavenderDialogControls(dialog); }; + FilesModalDialog::styleBackground=lavenderDialogColors; menuBar=CreateWindowW(L"BUTTON",L"",WS_CHILD|WS_CLIPSIBLINGS|BS_OWNERDRAW, 0,0,0,0,window,reinterpret_cast(120),instance,nullptr); const wchar_t *menus[]{L"Left",L"Files",L"Commands",L"Options",L"Right"}; @@ -8923,6 +9052,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) hidePicker(); const auto &bounds=*reinterpret_cast(lp); applyFont(window,displayFont,fontPoints); + lavender::setFont(LOWORD(wp)); SetWindowPos(window,nullptr,bounds.left,bounds.top,bounds.right-bounds.left, bounds.bottom-bounds.top,SWP_NOZORDER|SWP_NOACTIVATE); layout(window); @@ -8943,8 +9073,12 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) layout(window); return 0; case WM_GETMINMAXINFO: - reinterpret_cast(lp)->ptMinTrackSize = {540, 220}; + { + const LavenderMetrics metrics(window); + reinterpret_cast(lp)->ptMinTrackSize=lavenderFiles()? + POINT{metrics.px(540),metrics.px(230)}:POINT{540,220}; return 0; + } case WM_SETCURSOR: case WM_LBUTTONDOWN: { @@ -8997,6 +9131,30 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) { PAINTSTRUCT paint{}; auto dc=BeginPaint(window,&paint); + if(lavenderFiles() && !terminalVisible) + { + const LavenderMetrics metrics(window); + lavender::fill(dc,paint.rcPaint,lavender::canvas); + for(int index=0;index<2;++index) + { + const auto &panel=panels[index]; + if(!IsWindowVisible(panel.list)) continue; + RECT list{},path{}; + GetWindowRect(panel.list,&list); + GetWindowRect(panel.path,&path); + MapWindowPoints(nullptr,window,reinterpret_cast(&list),2); + MapWindowPoints(nullptr,window,reinterpret_cast(&path),2); + const int inset=metrics.px(8); + const RECT card{path.left-inset,path.top-inset,path.right+inset, + list.bottom+textHeight*(1+hasSelectionSummary())+metrics.px(9)}; + lavender::rounded(dc,card,metrics.px(11),lavender::surface, + index==active?lavender::activeEdge:lavender::line); + lavender::fill(dc,{card.left+1,list.bottom,card.right-1,list.bottom+1},lavender::line); + if(scrollPosition(panel.list,false).last()) paintScrollPosition(window,dc,panel.list,lavender::surface); + } + EndPaint(window,&paint); + return 0; + } FillRect(dc,&paint.rcPaint,terminalVisible?terminalBackground:blue); auto border=CreateSolidBrush(colors[Frame]); for(const auto &panel:panels) @@ -9037,6 +9195,14 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) case WM_CTLCOLORSTATIC: { auto dc=reinterpret_cast(wp); + const auto control=reinterpret_cast(lp); + if(lavenderFiles() && (control==status || control==panels[0].selectionSummary || + control==panels[1].selectionSummary || control==terminalPrompt || control==terminalInput)) + { + SetTextColor(dc,lavender::muted); + SetBkColor(dc,lavender::surface); + return reinterpret_cast(GetStockObject(WHITE_BRUSH)); + } if(reinterpret_cast(lp)==terminalInput || reinterpret_cast(lp)==terminalOutput || reinterpret_cast(lp)==terminalPrompt) { @@ -9049,32 +9215,70 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) return reinterpret_cast(blue); } case WM_CTLCOLORLISTBOX: - return reinterpret_cast(reinterpret_cast(lp)==picker || - reinterpret_cast(lp)==completionList?teal:blue); + if(reinterpret_cast(lp)==picker || reinterpret_cast(lp)==completionList) + { + if(lavenderFiles()) + { + SetDCBrushColor(reinterpret_cast(wp),lavender::path); + return reinterpret_cast(GetStockObject(DC_BRUSH)); + } + return reinterpret_cast(teal); + } + return reinterpret_cast(lavenderFiles()?GetStockObject(WHITE_BRUSH):blue); case WM_DRAWITEM: { const auto &item=*reinterpret_cast(lp); + if(item.hwndItem==menuBar && lavenderFiles()) + { + lavender::fill(item.hDC,item.rcItem,lavender::canvas); + return TRUE; + } if(item.hwndItem==panelSearchPopup) { const auto frame=dialogFrameMetrics(GetDpiForWindow(window)); + auto field=item.rcItem; + InflateRect(&field,-frame.content(),-frame.content()); + const auto cells=static_cast(std::max(0L,field.right-field.left-10)/std::max(1,cellWidth)); + const auto start=panelSearchPrefix.size()>cells?panelSearchPrefix.size()-cells:0; + if(lavenderFiles()) + { + paintLavenderDialogFrame(window,item.hDC,item.rcItem,L"Search"); + lavender::rounded(item.hDC,field,LavenderMetrics(window).px(5),lavender::path,lavender::line); + field.left+=LavenderMetrics(window).px(6); + lavender::text(item.hDC,field,panelSearchPrefix.c_str()+start,lavender::ink); + return TRUE; + } const auto surface=GetSysColorBrush(COLOR_BTNFACE); const auto border=GetSysColorBrush(COLOR_BTNTEXT); const auto ink=GetSysColor(COLOR_BTNTEXT); const auto box=paintDialogFrame(item.hDC,item.rcItem,frame,surface,border); paintDialogFrameCaptions(item.hDC,item.rcItem,box,L"Search",surface,ink,mono); - auto field=item.rcItem; - InflateRect(&field,-frame.content(),-frame.content()); - const auto cells=static_cast(std::max(0L,field.right-field.left-10)/std::max(1,cellWidth)); - const auto start=panelSearchPrefix.size()>cells?panelSearchPrefix.size()-cells:0; paintText(item.hDC,field,panelSearchPrefix.c_str()+start,RGB(0,0,0),RGB(0,128,128)); return TRUE; } if(item.CtlID==142 || item.CtlID==143) { auto bounds=item.rcItem; - FillRect(item.hDC,&bounds,blue); const auto &panel=panels[item.CtlID-142]; const auto path=panelCaption(panel); + if(lavenderFiles()) + { + const LavenderMetrics metrics(window); + const bool highlighted=static_cast(item.CtlID)-142==active; + lavender::fill(item.hDC,bounds,lavender::surface); + lavender::rounded(item.hDC,bounds,metrics.px(7),lavender::path, + highlighted?lavender::activeEdge:lavender::line); + if(pathNavigationAvailable(panel)) paintPanelPath(item.hDC,bounds,panel,highlighted); + else + { + paintLavenderFileIcon(item.hDC,bounds,metrics,true); + bounds.left+=metrics.px(30); + bounds.right-=metrics.px(9); + lavender::text(item.hDC,bounds,path.c_str(),lavender::ink,DT_LEFT,DT_PATH_ELLIPSIS); + } + return TRUE; + } + FillRect(item.hDC,&bounds,blue); const auto middle=bounds.top+(bounds.bottom-bounds.top)/2; SetDCBrushColor(item.hDC,colors[Frame]); const auto lineBrush=static_cast(GetStockObject(DC_BRUSH)); @@ -9121,9 +9325,25 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) if(item.CtlID==140 || item.CtlID==141) { const auto &panel=panels[item.CtlID-140]; + const bool modern=lavenderFiles(); + if(modern) + { + lavender::fill(item.hDC,item.rcItem,lavender::surface); + const auto &r=item.rcItem; + lavender::fill(item.hDC,{r.left,r.bottom-1,r.right,r.bottom},lavender::line); + } + const auto heading=[&](RECT bounds,const wchar_t *label,bool numeric) + { + if(modern) + { + InflateRect(&bounds,-LavenderMetrics(window).px(8),0); + lavender::text(item.hDC,bounds,label,lavender::muted,numeric?DT_RIGHT:DT_LEFT); + } + else paintText(item.hDC,bounds,label,RGB(255,255,0),colors[PanelBlue],numeric); + }; if(panel.findOrigin || panelListsLocations(panel)) { - paintText(item.hDC,item.rcItem,panel.findOrigin?L"Relative path":L"Name",RGB(255,255,0),colors[PanelBlue]); + heading(item.rcItem,panel.findOrigin?L"Relative path":L"Name",false); return TRUE; } const auto columns=panelColumns(panel,item.rcItem); @@ -9134,15 +9354,21 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) std::wstring label=panelColumnNames[i]; if(i==nameColumn && !panel.view.mask.empty()) label+=L" *"; if(static_cast(panel.view.sort)==i) label+=panel.view.descending?L" ↓":L" ↑"; - paintText(item.hDC,columns[i],label.c_str(),RGB(255,255,0),colors[PanelBlue], - i==sizeColumn || i==allocationColumn || i==linkColumn); + heading(columns[i],label.c_str(),i==sizeColumn || i==allocationColumn || i==linkColumn); } - paintPanelColumnLines(item.hDC,columns); + if(!modern) paintPanelColumnLines(item.hDC,columns); return TRUE; } if(item.hwndItem==pickerFrame || item.hwndItem==completionFrame) { const bool driveFrame=item.hwndItem==pickerFrame && !commandPicker && !folderPicker; + if(lavenderFiles()) + { + const auto title=driveFrame?L"Change drive":folderPicker?folderPicker->caption:L""; + paintLavenderDialogFrame(window,item.hDC,item.rcItem,title); + paintScrollPosition(item.hwndItem,item.hDC,item.hwndItem==pickerFrame?picker:completionList,lavender::path); + return TRUE; + } auto border=CreateSolidBrush(driveFrame?RGB(255,255,255):colors[Frame]); const auto box=paintDialogFrame(item.hDC,item.rcItem, dialogFrameMetrics(GetDpiForWindow(window)),teal,border); @@ -9207,6 +9433,14 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) { if(item.CtlID==114 && remoteSearchResults(panels[active]) && panels[active].ftp) text=filesKeyBarLabel(FilesKey::Move,L"Rename"); + if(lavenderFiles()) + { + const LavenderMetrics metrics(window); + if(!remoteSearchActionAvailable(item.CtlID)) + if(const auto space=text.find(L' ');space!=text.npos) text.resize(space); + paintLavenderCommand(item,text,metrics,item.rcItem.bottom-item.rcItem.top>metrics.row); + return TRUE; + } const auto separator=text.find(L' '); auto key=text.substr(0,separator); if(key.starts_with(L'F') && key.size()>1) key.erase(0,1); @@ -9220,21 +9454,31 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) return TRUE; } const bool popupRow=item.hwndItem==picker || item.hwndItem==completionList; + const bool modernPopup=popupRow && lavenderFiles(); + const auto popupPalette=farDropDownPalette(); + const auto popupLine=modernPopup?lavender::line:RGB(255,255,255); + const auto popupAccess=modernPopup?lavender::accent:RGB(255,255,0); auto background=item.CtlType==ODT_BUTTON?Footer:popupRow?Dialog:PanelBlue; - auto foreground=colors[Text]; + auto foreground=modernPopup?popupPalette.text:colors[Text]; if(item.hwndItem==picker && !folderPicker && ((commandPicker && item.itemID(GetStockObject(DC_BRUSH))); return TRUE; } if(item.hwndItem==picker && !commandPicker && !folderPicker && item.itemID==lanHeaderRow()) { auto row=item.rcItem; + if(modernPopup) + { + lavender::fill(item.hDC,row,popupPalette.surface); + lavender::text(item.hDC,row,L"KSwitcher LAN",lavender::muted,DT_CENTER); + return TRUE; + } FillRect(item.hDC,&row,teal); const RECT line{row.left,row.top,row.right,row.top+1}; SetDCBrushColor(item.hDC,RGB(255,255,255)); @@ -9248,10 +9492,12 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) if(item.CtlID>=130 && item.CtlID<=134 && static_cast(item.CtlID)-130==menuIndex) background=Selection; const bool panelRow=item.CtlID==102 || item.CtlID==103; + const bool lavenderRow=panelRow && lavenderFiles(); + const LavenderMetrics metrics(window); const bool activePanelRow=panelRow && item.hwndItem==panels[active].list; if(!panelRow && (item.itemState&(ODS_SELECTED|ODS_FOCUS))) background=Selection; - COLORREF rowBackground=colors[background]; + COLORREF rowBackground=modernPopup?(background==Selection?popupPalette.selection:popupPalette.surface):colors[background]; HFONT rowFont{}; std::wstring folderIndicator; if(panelRow) @@ -9263,12 +9509,40 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) foreground=resolved.foreground; rowBackground=resolved.background; rowFont=fileStyleFonts[resolved.decorations]; + if(lavenderRow) + { + auto row=item.rcItem; + lavender::fill(item.hDC,row,lavender::surface); + if(rowBackground!=lavender::surface) + { + InflateRect(&row,-metrics.px(1),-metrics.px(1)); + lavender::rounded(item.hDC,row,metrics.px(6),rowBackground, + cursor && activePanelRow?lavender::activeEdge:rowBackground); + } + if(item.itemID(sizeWidth)); } } + const auto paintRow=[&](RECT bounds,const wchar_t *label,bool right=false,bool icon=false) + { + if(lavenderRow) + { + bounds.left+=metrics.px(icon?30:5); + bounds.right-=metrics.px(8); + lavender::text(item.hDC,bounds,label,foreground,right?DT_RIGHT:DT_LEFT); + } + else paintText(item.hDC,bounds,label,foreground,rowBackground,right,right?nullptr:rowFont); + }; auto shortcut=text.find(L'\t'); if((item.hwndItem==picker && folderPicker) || (panelRow && recentFolderList(panels[item.CtlID-102]))) paintDialogListRow(item.hDC,item.rcItem,text,rowFont?rowFont:mono,foreground,rowBackground, @@ -9276,7 +9550,8 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) else if(item.hwndItem==picker && commandPicker && item.itemID(item.itemID)==driveHover? - hover:colors[background]); + hover:rowBackground); ExtTextOutW(item.hDC,0,0,ETO_OPAQUE,&item.rcItem,L"",0,nullptr); SetBkMode(item.hDC,TRANSPARENT); - SetDCBrushColor(item.hDC,RGB(255,255,255)); + SetDCBrushColor(item.hDC,popupLine); const auto brush=static_cast(GetStockObject(DC_BRUSH)); size_t start=0; for(size_t i=0;i(length),nullptr); if(i==0 && length) { - SetTextColor(item.hDC,RGB(255,255,0)); + SetTextColor(item.hDC,popupAccess); ExtTextOutW(item.hDC,x,item.rcItem.top+3,ETO_CLIPPED,&item.rcItem,text.c_str(),1,nullptr); } if(end==text.npos) break; @@ -9339,7 +9614,7 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) choice==remoteDriveRows.end()?L'\0':choice->second.digit; SelectObject(item.hDC,mono); SetTextColor(item.hDC,foreground); - SetBkColor(item.hDC,colors[wake?Dialog:background]); + SetBkColor(item.hDC,wake?popupPalette.surface:rowBackground); if(wake) { button=driveWakeAction.bounds(bounds,cellWidth); @@ -9354,28 +9629,34 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) text.c_str(),static_cast(text.size()),nullptr); if(digit) { - const auto previous=SetTextColor(item.hDC,RGB(255,255,0)); + const auto previous=SetTextColor(item.hDC,popupAccess); ExtTextOutW(item.hDC,x,y,ETO_CLIPPED,&bounds,&digit,1,nullptr); SetTextColor(item.hDC,previous); } if(wake) { const bool focused=(item.itemState&ODS_SELECTED) && GetFocus()==picker; - driveWakeAction.paint(item.hDC,button,3,foreground,colors[Dialog], + driveWakeAction.paint(item.hDC,button,3,foreground,popupPalette.surface, focused || static_cast(item.itemID)==driveHover); } } else if(item.CtlID>=130 && item.CtlID<=134) - paintMenuLabel(item.hDC,item.rcItem,text,0,foreground,colors[background]); + { + if(lavenderFiles()) paintMenuLabel(item.hDC,item.rcItem,text,0,lavender::ink, + background==Selection?lavender::selection:lavender::canvas,lavender::accent,dialogUiFont()); + else paintMenuLabel(item.hDC,item.rcItem,text,0,foreground,colors[background]); + } else if(!folderIndicator.empty() && !detailedPanel(panels[item.CtlID-102])) { auto name=item.rcItem, indicator=item.rcItem; indicator.left=std::max(indicator.left,indicator.right-static_cast(folderIndicator.size())*cellWidth-10); name.right=indicator.left; - paintText(item.hDC,name,text.c_str(),foreground,rowBackground,false,rowFont); - paintText(item.hDC,indicator,folderIndicator.c_str(),foreground,rowBackground,true); + paintRow(name,text.c_str(),false,true); + paintRow(indicator,folderIndicator.c_str(),true); } - else paintText(item.hDC,item.rcItem,text.c_str(),foreground,rowBackground,false,rowFont); + else if(!lavenderRow || !hasPanelColumns(panels[item.CtlID-102]) || + transferProfileList(panels[item.CtlID-102]) || item.itemID>=panels[item.CtlID-102].sizes.size()) + paintRow(item.rcItem,text.c_str(),false,true); if(item.CtlID==102 || item.CtlID==103) { const auto &panel=panels[item.CtlID-102]; @@ -9408,14 +9689,18 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) } } else suffix.clear(); - paintText(item.hDC,extension,suffix.c_str(),foreground,rowBackground,true,rowFont); + if(lavenderRow) paintRow(extension,suffix.c_str(),true); + else paintText(item.hDC,extension,suffix.c_str(),foreground,rowBackground,true,rowFont); } if(tree) text=treeRowPrefix(panel,path,folder)+text; const auto paintValue=[&](PanelColumn column,const std::wstring &value,bool align) { const auto &bounds=columns[column]; if(bounds.leftlinks?std::to_wstring(*extra->links):empty,true); if(columns[ownerColumn].leftowner.empty()?extra->owner:empty,false); - paintPanelColumnLines(item.hDC,columns); + if(!lavenderRow) paintPanelColumnLines(item.hDC,columns); } } if (item.CtlType==ODT_LISTBOX && !popupRow) @@ -9965,6 +10250,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) DispatchMessageW(&message); } for(auto font:fileStyleFonts) if(font) DeleteObject(font); + if(lavender::font) DeleteObject(lavender::font); DeleteObject(mono); DeleteObject(terminalFont); DeleteObject(blue); diff --git a/src/files_options.inl b/src/files_options.inl index 972f2db..200b98c 100644 --- a/src/files_options.inl +++ b/src/files_options.inl @@ -18,7 +18,9 @@ constexpr int wideColumnControls[]{275,276,201,202,204}; constexpr int statusColumnControls[]{277,203,205,206,207,208}; constexpr int colorOptionControls[]{279,280}; constexpr int appearanceControls[]{281,282}; -enum AppearanceSection { Font, DialogFrame, SystemThemes }; +enum AppearanceSection { Font, DialogFrame, SystemThemes, WindowStyle }; +constexpr int windowStyleChoice=417; +constexpr int windowStyleControls[]{416,windowStyleChoice}; constexpr int terminalScaleSection=1,areaScaleLabel=528,areaScaleControl=529; constexpr int systemLightChoice=531,systemDarkChoice=533; constexpr int systemThemeControls[]{530,systemLightChoice,532,systemDarkChoice,535}; @@ -105,6 +107,7 @@ void showPanelModeOptions(HWND dialog) struct OptionsBaseline { + FilesAppearance appearance=filesAppearance; LOGFONTW font=displayFont; int points=fontPoints; DialogFramePadding padding=dialogFramePadding; @@ -127,6 +130,7 @@ struct OptionsBaseline struct OptionsDraft { OptionsBaseline baseline; + FilesAppearance appearance=baseline.appearance; ks::files::TextSettings text=baseline.text; ComparisonAppearance comparison=baseline.comparison; FilesKeySettings keySettings=baseline.keySettings; @@ -144,7 +148,7 @@ struct OptionsDraft DWORD location{}; int markdownError{}; HTREEITEM wideColumnsNode{},markdownNode{}; - RECT initialClient{}; + RECT initialClient{}, resetBounds{}; UINT initialDpi=96; OptionsControl controls[10]{ {optionsTree,OptionsAnchor::StretchHeight}, @@ -185,7 +189,7 @@ void updateOptionsApply(HWND dialog,const OptionsDraft &draft) checked(rightClickMarksControl)!=base.mouseMarks || checked(driveButtonsControl)!=base.drives || checked(compactLayoutControl)!=base.compact || checked(restoreDocumentsControl)!=base.restoreLocal || fields!=base.fields || draft.palette!=base.palette || draft.styles!=base.styles || - draft.framePadding!=base.padding || optionsFontChanged(draft) || + draft.framePadding!=base.padding || optionsFontChanged(draft) || draft.appearance!=base.appearance || checked(optionsRemoteTerminal)!=base.remoteTerminal || checked(optionsRemoteHibernate)!=base.remoteHibernate || checked(optionsRemoteUpdate)!=base.remoteUpdate || @@ -202,7 +206,8 @@ LRESULT CALLBACK optionsGroupBackground(HWND group,UINT message,WPARAM wp,LPARAM const auto dc=reinterpret_cast(wp); RECT client{}; GetClientRect(group,&client); - FillRect(dc,&client,GetSysColorBrush(COLOR_3DFACE)); + if(lavenderFiles()) lavender::fill(dc,client,lavender::surface); + else FillRect(dc,&client,GetSysColorBrush(COLOR_3DFACE)); return TRUE; } return DefSubclassProc(group,message,wp,lp); @@ -221,6 +226,7 @@ void layoutOptionsPreview(HWND dialog) { const auto id=GetDlgCtrlID(child); if(child==preview || id==IDOK || id==IDCANCEL || id==optionsApply || + (lavenderFiles() && id==optionsReset) || !(GetWindowLongPtrW(child,GWL_STYLE)&WS_VISIBLE)) continue; const auto bounds=dialogControlBounds(dialog,id); if(id!=-1 && bounds.left>=title.left-4) top=std::max(top,bounds.bottom); @@ -254,6 +260,13 @@ void layoutOptions(HWND dialog,const OptionsDraft &draft) SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOCOPYBITS|SWP_NOREDRAW); } groupDialogButtons(dialog,{IDOK,IDCANCEL,optionsApply},true); + const auto reset=draft.resetBounds; + const auto ok=dialogControlBounds(dialog,IDOK); + const auto resetLeft=lavenderFiles()?dialogControlBounds(dialog,optionsTree).left:scale(reset.left); + const auto resetTop=lavenderFiles()?ok.top:scale(reset.top); + const auto resetHeight=lavenderFiles()?ok.bottom-ok.top:scale(reset.bottom-reset.top); + SetWindowPos(GetDlgItem(dialog,optionsReset),nullptr,resetLeft,resetTop, + scale(reset.right-reset.left),resetHeight,SWP_NOZORDER|SWP_NOACTIVATE|SWP_NOREDRAW); if(draft.page==PanelColors && draft.section==fileStyleSection) layoutFileStyleFields(dialog,false); layoutOptionsPreview(dialog); // Paint the final layout together, including the areas vacated by moved controls. @@ -583,7 +596,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) title=page==PanelModes?panelSectionNames[section]:page==PanelColors? (section==fileStyleSection?L"File type styles":colorNames[section]): page==CommandLine?(section==terminalScaleSection?L"Terminal appearance":L"Command history"): - section==SystemThemes?L"System themes":section==DialogFrame?L"Dialog frame":L"Font"; + section==WindowStyle?L"Window style":section==SystemThemes?L"System themes": + section==DialogFrame?L"Dialog frame":L"Font"; } SetDlgItemTextW(dialog,optionsTitle,title); const auto show=[&](auto &controls,bool visible) @@ -612,6 +626,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) show(statusColumnControls,page==PanelModes && section==StatusColumns); show(appearanceControls,page==Appearance && section==Font); show(systemThemeControls,page==Appearance && section==SystemThemes); + show(windowStyleControls,page==Appearance && section==WindowStyle); + SendDlgItemMessageW(dialog,windowStyleChoice,CB_SETCURSEL,static_cast(draft.appearance),0); if(page==Appearance && section==SystemThemes) showSystemThemeRoles(dialog,draft.text); showAreaScale(dialog,draft,optionsScaleArea(page,section)); show(comparisonControls,page==CompareFiles); @@ -633,7 +649,8 @@ void showOptionsPage(HWND dialog,OptionsDraft &draft,int page,int section) constexpr int fileStyleControls[]{287,288,289,290,291,292,293,294,295,296,297,298,300,fileStyleState}; show(fileStyleControls,fileTypes); const auto preview=GetDlgItem(dialog,fileStylePreview); - const bool panelPreview=page>=0 && page=0 && !(page==Appearance && section==SystemThemes); + const bool panelPreview=page>=0 && page=0 && + !(page==Appearance && (section==SystemThemes || section==WindowStyle)); ShowWindow(preview,panelPreview?SW_SHOW:SW_HIDE); layoutOptionsPreview(dialog); RedrawWindow(dialog,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN); @@ -756,6 +773,7 @@ void filterOptions(HWND dialog,OptionsDraft &draft) { addSection(L"Font",Font,matches(L"Display font") || matches(L"Panel scale")); addSection(L"System themes",SystemThemes,matches(L"Light mode palette") || matches(L"Dark mode palette")); + addSection(L"Window style",WindowStyle,matches(L"Interface style") || matches(L"Lavender") || matches(L"Far")); addSection(L"Dialog frame",DialogFrame, matches(L"Outer padding") || matches(L"Inner padding") || matches(L"Row text padding")); } @@ -776,6 +794,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) SetWindowLongPtrW(dialog,DWLP_USER,lp); draft.initialDpi=GetDpiForWindow(dialog); GetClientRect(dialog,&draft.initialClient); + draft.resetBounds=dialogControlBounds(dialog,optionsReset); for(auto &control:draft.controls) control.bounds=dialogControlBounds(dialog,control.id); // Group boxes are behind their sibling controls. Erase their full client // area on resize while clipping out the controls inside the frame. @@ -799,6 +818,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) SendDlgItemMessageW(dialog,comparisonColorCombo,CB_ADDSTRING,0,reinterpret_cast(label)); SendDlgItemMessageW(dialog,comparisonColorCombo,CB_SETCURSEL,0,0); SendDlgItemMessageW(dialog,optionsSearch,EM_SETLIMITTEXT,255,0); + for(const auto label:{L"Far",L"Lavender"}) + SendDlgItemMessageW(dialog,windowStyleChoice,CB_ADDSTRING,0,reinterpret_cast(label)); for(const auto &option:frameOptions) for(DWORD value=0;value<=option.maximum;++value) SendDlgItemMessageW(dialog,option.id,CB_ADDSTRING,0, @@ -824,11 +845,30 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) CheckDlgButton(dialog,optionsRemoteHibernate,ks::lan::remoteHibernateAllowed()); CheckDlgButton(dialog,optionsRemoteUpdate,ks::lan::remoteUpdateAllowed()); filterOptions(dialog,draft); + if(lavenderFiles()) layoutOptions(dialog,draft); updateOptionsApply(dialog,draft); return TRUE; } auto *draft=reinterpret_cast(GetWindowLongPtrW(dialog,DWLP_USER)); if(!draft) return FALSE; + if(message==WM_PAINT && lavenderFiles()) + { + PAINTSTRUCT paint{}; + const auto dc=BeginPaint(dialog,&paint); + RECT client{}; + GetClientRect(dialog,&client); + const LavenderMetrics metrics(dialog); + const auto title=dialogControlBounds(dialog,optionsTitle); + const auto tree=dialogControlBounds(dialog,optionsTree); + const auto apply=dialogControlBounds(dialog,optionsApply); + lavender::fill(dc,client,lavender::surface); + lavender::rounded(dc,{tree.left-metrics.px(4),metrics.px(4),tree.right+metrics.px(4), + tree.bottom+metrics.px(4)},metrics.px(7),lavender::path,lavender::line); + lavender::fill(dc,{title.left,title.bottom+metrics.px(3),title.right,title.bottom+metrics.px(3)+1},lavender::line); + lavender::fill(dc,{client.left,apply.top-metrics.px(5),client.right,apply.top-metrics.px(5)+1},lavender::line); + EndPaint(dialog,&paint); + return TRUE; + } if(message==WM_DRAWITEM && wp==fileStylePreview) { const auto &item=*reinterpret_cast(lp); @@ -855,6 +895,22 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } if(message==WM_NOTIFY && wp==optionsTree) { + if(lavenderFiles() && reinterpret_cast(lp)->code==NM_CUSTOMDRAW) + { + auto &draw=*reinterpret_cast(lp); + if(draw.nmcd.dwDrawStage==CDDS_PREPAINT) + { + SetWindowLongPtrW(dialog,DWLP_MSGRESULT,CDRF_NOTIFYITEMDRAW); + return TRUE; + } + if(draw.nmcd.dwDrawStage==CDDS_ITEMPREPAINT) + { + draw.clrText=lavender::ink; + draw.clrTextBk=(draw.nmcd.uItemState&CDIS_SELECTED)?lavender::selection:lavender::path; + SetWindowLongPtrW(dialog,DWLP_MSGRESULT,CDRF_NEWFONT); + return TRUE; + } + } const auto &change=*reinterpret_cast(lp); if(change.hdr.code==TVN_SELCHANGEDW && change.itemNew.hItem) { @@ -874,6 +930,14 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) if(changeTextOption(dialog,*draft,wp)) return TRUE; switch(LOWORD(wp)) { + case windowStyleChoice: + if(HIWORD(wp)==CBN_SELCHANGE) + { + draft->appearance=SendDlgItemMessageW(dialog,windowStyleChoice,CB_GETCURSEL,0,0)==1? + FilesAppearance::Lavender:FilesAppearance::Far; + updateOptionsApply(dialog,*draft); + } + return TRUE; case optionsSearch: if(HIWORD(wp)==EN_CHANGE) filterOptions(dialog,*draft); return TRUE; @@ -1007,6 +1071,8 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) } return TRUE; case optionsReset: + if(draft->page==allOptions || (draft->page==Appearance && (draft->section<0 || draft->section==WindowStyle))) + draft->appearance=FilesAppearance::Far; if(draft->page==allOptions) draft->scales=ks::files::defaultAppearanceScales; else if(const auto area=optionsScaleArea(draft->page,draft->section)) draft->scales[ks::files::appearanceIndex(*area)]=100; @@ -1244,6 +1310,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) saveChanged(dialogFrameOuterKey,draft->framePadding.outer,base.padding.outer); saveChanged(dialogFrameInnerKey,draft->framePadding.inner,base.padding.inner); saveChanged(dialogRowTextKey,draft->framePadding.rowText,base.padding.rowText); + saveChanged(filesAppearanceKey,static_cast(draft->appearance),static_cast(base.appearance)); for(size_t i=0;iscales.size();++i) saveChanged(areaScaleKeys[i],draft->scales[i],base.scales[i]); if(fontChanged) { @@ -1255,13 +1322,16 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) const auto mode=panelModeOption(dialog,index); if(mode!=base.modes[index]) savePanelMode(index,mode); } + const bool appearanceChanged=draft->appearance!=base.appearance; loadFilesPreferences(owner); + if(appearanceChanged) styleLavenderDialogControls(dialog); refreshFilesKeyBar(); notifyFilesPreferences(owner); const auto dialogOwner=GetWindow(dialog,GW_OWNER); if(dialogOwner!=owner) SendMessageW(dialogOwner,filesPreferencesChanged,reinterpret_cast(owner),0); draft->baseline=OptionsBaseline{}; + draft->appearance=draft->baseline.appearance; draft->text=draft->baseline.text; draft->comparison=draft->baseline.comparison; draft->keySettings=draft->baseline.keySettings; @@ -1289,6 +1359,7 @@ INT_PTR CALLBACK optionsDialog(HWND dialog,UINT message,WPARAM wp,LPARAM lp) if(draft->page==PanelColors && draft->section==fileStyleSection) updateFileStyleEditor(dialog,*draft,true); showOptionsPage(dialog,*draft,draft->page,draft->section); + if(appearanceChanged) layoutOptions(dialog,*draft); layout(owner); showFileDetails(panels[active]); RedrawWindow(owner,nullptr,nullptr,RDW_INVALIDATE|RDW_ERASE|RDW_ALLCHILDREN|RDW_UPDATENOW); diff --git a/src/files_path_navigation.inl b/src/files_path_navigation.inl index dd24c09..348d406 100644 --- a/src/files_path_navigation.inl +++ b/src/files_path_navigation.inl @@ -129,6 +129,12 @@ void paintPanelPath(HDC dc,RECT bounds,const Panel &panel,bool activePanel) for(const auto &part:panelPathParts(panel,bounds)) { const bool current=activePanel && part.current; + if(lavenderFiles()) + { + if(current) lavender::rounded(dc,part.rect,MulDiv(5,GetDeviceCaps(dc,LOGPIXELSX),96),lavender::key,lavender::key); + lavender::text(dc,part.rect,part.label.c_str(),!part.enabled || part.dim?lavender::muted:lavender::ink,DT_CENTER); + continue; + } FillRect(dc,&part.rect,current?teal:blue); SetTextColor(dc,!part.enabled || part.dim?RGB(160,170,190):colors[current?Text:Frame]); auto text=part.rect; diff --git a/src/update.h b/src/update.h index 291d4b2..682945a 100644 --- a/src/update.h +++ b/src/update.h @@ -2,7 +2,7 @@ #include "platform.h" namespace ks { -inline constexpr wchar_t AppVersion[] = L"0.8.1"; +inline constexpr wchar_t AppVersion[] = L"0.8.2"; inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; diff --git a/tests/files_activation.ps1 b/tests/files_activation.ps1 index 17e76b9..b898bbb 100644 --- a/tests/files_activation.ps1 +++ b/tests/files_activation.ps1 @@ -236,6 +236,7 @@ $extension = ".ksfiles$unique" $progId = "KSwitcher.Files.Test.$unique" $saved = @{} $profileValues = 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'LeftWide', 'RightWide', + 'LeftPanelMode', 'RightPanelMode', 'LeftViewOrder', 'RightViewOrder', 'AppearanceMode', 'ShowDetails', 'StatusFields', 'CommandHistory', 'CommandHistoryKey', 'PreviousCommandKey', 'WindowPlacement', 'FontPoints' $process = $null $trace = $null @@ -275,6 +276,8 @@ try { $profile.SetValue('RightPath', $rightDir) foreach ($name in 'LeftCursor', 'RightCursor') { $profile.DeleteValue($name, $false) } foreach ($name in 'LeftWide', 'RightWide', 'ShowDetails') { $profile.SetValue($name, 1) } + foreach ($name in 'LeftPanelMode', 'RightPanelMode') { $profile.SetValue($name, 1, 'DWord') } + foreach ($name in 'LeftViewOrder', 'RightViewOrder', 'AppearanceMode') { $profile.SetValue($name, 0, 'DWord') } $profile.SetValue('StatusFields', 3) if($TerminalOnly){ diff --git a/tests/files_lavender.ps1 b/tests/files_lavender.ps1 new file mode 100644 index 0000000..fe60f6e --- /dev/null +++ b/tests/files_lavender.ps1 @@ -0,0 +1,310 @@ +param( + [Parameter(Mandatory)][string]$Executable, + [string]$Screenshot, + [string]$DialogScreenshotDirectory +) +$ErrorActionPreference = 'Stop' +Add-Type -AssemblyName System.Drawing +Add-Type -AssemblyName System.Windows.Forms +Add-Type @' +using System; +using System.Runtime.InteropServices; +public static class LavenderWindow { + [StructLayout(LayoutKind.Sequential)] public struct Rect { public int Left, Top, Right, Bottom; } + [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr window, out Rect rect); + [DllImport("user32.dll")] public static extern IntPtr GetDlgItem(IntPtr window, int id); + [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] public static extern bool IsWindow(IntPtr window); + [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr window); + [DllImport("user32.dll")] public static extern IntPtr GetLastActivePopup(IntPtr window); + [DllImport("user32.dll")] public static extern IntPtr GetWindow(IntPtr window, uint command); + [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr window); + [DllImport("user32.dll")] static extern void keybd_event(byte key, byte scan, uint flags, UIntPtr extra); + public static bool Activate(IntPtr window) { + if (GetForegroundWindow() == window) return true; + keybd_event(0x12, 0, 0, UIntPtr.Zero); + keybd_event(0x12, 0, 2, UIntPtr.Zero); + SetForegroundWindow(window); + return GetForegroundWindow() == window; + } + [DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr window, IntPtr after, int x, int y, int width, int height, uint flags); + [DllImport("user32.dll")] public static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); + [DllImport("user32.dll")] public static extern uint GetDpiForWindow(IntPtr window); + [DllImport("user32.dll", EntryPoint="SendMessageW")] public static extern IntPtr Send(IntPtr window, uint message, IntPtr w, IntPtr l); + [DllImport("user32.dll", EntryPoint="PostMessageW")] public static extern bool Post(IntPtr window, uint message, IntPtr w, IntPtr l); + [DllImport("user32.dll", EntryPoint="SendMessageW", CharSet=CharSet.Unicode)] + public static extern IntPtr SendText(IntPtr window, uint message, IntPtr w, string text); + [DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr window, int attribute, out Rect rect, int size); +} +'@ + +function Wait-Until([scriptblock]$Condition) { + for ($attempt = 0; $attempt -lt 100; $attempt++) { + if (& $Condition) { return } + Start-Sleep -Milliseconds 50 + } + throw "Timed out waiting for $Condition" +} + +function Get-Bounds($Window) { + $bounds = [LavenderWindow+Rect]::new() + if (![LavenderWindow]::GetWindowRect($Window, [ref]$bounds)) { throw 'Missing window or control.' } + $bounds +} + +function Read-Window($Bounds) { + $image = [Drawing.Bitmap]::new(($Bounds.Right - $Bounds.Left), ($Bounds.Bottom - $Bounds.Top)) + $graphics = [Drawing.Graphics]::FromImage($image) + try { $graphics.CopyFromScreen($Bounds.Left, $Bounds.Top, 0, 0, $image.Size) } + finally { $graphics.Dispose() } + $image +} + +function Test-Pixel($Image, $Bounds, $X, $Y, $Expected, $Description) { + $actual = $Image.GetPixel($X - $Bounds.Left, $Y - $Bounds.Top) + if ($actual.ToArgb() -ne [Drawing.ColorTranslator]::FromHtml($Expected).ToArgb()) { + throw "$Description expected $Expected, got $($actual.Name)." + } +} + +function Open-LavenderOptions($Window) { + $keyboard.SendKeys('{F9}') + Wait-Until { [LavenderWindow]::IsWindowVisible([LavenderWindow]::GetDlgItem($Window, 133)) } + [void][LavenderWindow]::Post($Window, 0x111, [IntPtr]133, [IntPtr]::Zero) + Wait-Until { + $popup = [LavenderWindow]::GetLastActivePopup($Window) + [LavenderWindow]::IsWindowVisible($popup) -and + [LavenderWindow]::GetDlgItem($popup, 270) -ne [IntPtr]::Zero + } + [LavenderWindow]::GetLastActivePopup($Window) +} + +function Set-Style($Window, [int]$Style) { + $dialog = Open-LavenderOptions $Window + $search = [LavenderWindow]::GetDlgItem($dialog, 270) + [void][LavenderWindow]::SendText($search, 0xC, [IntPtr]::Zero, 'Interface style') + $combo = [LavenderWindow]::GetDlgItem($dialog, 417) + Wait-Until { [LavenderWindow]::IsWindowVisible($combo) } + [void][LavenderWindow]::Send($combo, 0x14E, [IntPtr]$Style, [IntPtr]::Zero) + if ([LavenderWindow]::Send($combo, 0x147, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $Style) { + throw "Could not select Files style $Style." + } + [void][LavenderWindow]::Send($dialog, 0x111, [IntPtr](417 + (1 -shl 16)), $combo) + [void][LavenderWindow]::Post($dialog, 0x111, [IntPtr]1, [IntPtr]::Zero) + Wait-Until { ![LavenderWindow]::IsWindow($dialog) } + Wait-Until { [LavenderWindow]::Activate($Window) } +} + +function Test-LavenderDialog($Window, [string]$Keys, [int]$ControlId, [string]$Name) { + $keyboard.SendKeys($Keys) + try { + Wait-Until { [LavenderWindow]::GetDlgItem([LavenderWindow]::GetLastActivePopup($Window), $ControlId) -ne [IntPtr]::Zero } + } catch { throw "$Name dialog did not open after $Keys. $_" } + $dialog = [LavenderWindow]::GetLastActivePopup($Window) + Start-Sleep -Milliseconds 160 + $bounds = Get-Bounds $dialog + $image = Read-Window $bounds + try { + $sampleX = $bounds.Right - [int](8 * $scale) + Test-Pixel $image $bounds $sampleX ($bounds.Top + [int](12 * $scale)) '#4648BB' "$Name title band" + Test-Pixel $image $bounds $sampleX ($bounds.Bottom - [int](12 * $scale)) '#F2EFFB' "$Name surface" + if ($Name -eq 'Copy') { + $field = Get-Bounds ([LavenderWindow]::GetDlgItem($dialog, $ControlId)) + Test-Pixel $image $bounds ($field.Right - [int](12 * $scale)) ` + ([int](($field.Top + $field.Bottom) / 2)) '#FFFFFF' 'Copy destination field' + } + if ($DialogScreenshotDirectory -and $Name -eq 'Copy') { + $owner = Get-Bounds $Window + $horizontal = [int](105 * $scale) + $vertical = [int](88 * $scale) + $context = [LavenderWindow+Rect]::new() + $context.Left = [Math]::Max($owner.Left, $bounds.Left - $horizontal) + $context.Right = [Math]::Min($owner.Right, $bounds.Right + $horizontal) + $context.Top = [Math]::Max($owner.Top, $bounds.Top - $vertical) + $context.Bottom = [Math]::Min($owner.Bottom, $bounds.Bottom + $vertical) + $scene = Read-Window $context + try { $scene.Save((Join-Path $DialogScreenshotDirectory 'files-lavender-copy.png'), [Drawing.Imaging.ImageFormat]::Png) } + finally { $scene.Dispose() } + } + } finally { $image.Dispose() } + $keyboard.SendKeys('{ESC}') + Wait-Until { ![LavenderWindow]::IsWindow($dialog) -and [LavenderWindow]::Activate($Window) } +} + +$exe = (Resolve-Path $Executable).Path +$key = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\KSwitcher\Files') +$names = 'AppearanceMode', 'LeftPanelMode', 'RightPanelMode', 'LeftViewOrder', 'RightViewOrder', 'LeftPath', 'RightPath', 'LeftCursor', 'RightCursor', 'WindowPlacement', 'OptionsLocation' +$saved = @{} +foreach ($name in $names) { + if ($name -in $key.GetValueNames()) { $saved[$name] = @($key.GetValue($name), $key.GetValueKind($name)) } +} +$fixture = if ($Screenshot) { + $target = [IO.Path]::GetFullPath($Screenshot) + $demoName = 'Demo-' + [Guid]::NewGuid().ToString('N').Substring(0, 6) + [IO.Directory]::CreateDirectory((Join-Path (Split-Path $target) $demoName)) +} else { [IO.Directory]::CreateTempSubdirectory('ks-files-lavender-') } +$previousDpi = [LavenderWindow]::SetThreadDpiAwarenessContext([IntPtr](-4)) +try { + $left = $fixture.CreateSubdirectory('Projects') + $right = $fixture.CreateSubdirectory('KSwitcher') + foreach ($name in 'Archives', 'Design assets', 'KSwitcher', 'Release notes', 'Screenshots') { + [void]$left.CreateSubdirectory($name) + } + foreach ($name in 'cmake', 'dictionaries', 'resources', 'src', 'tests', 'tools') { + [void]$right.CreateSubdirectory($name) + } + foreach ($name in '.gitignore', 'CMakeLists.txt', 'FILES-UI.md', 'LICENSE', 'README.md') { + [IO.File]::WriteAllText((Join-Path $right.FullName $name), ('Example content' * (40 + 54 * $name.Length))) + } + $key.SetValue('AppearanceMode', 0, 'DWord') + $key.SetValue('LeftPanelMode', 1, 'DWord') + $key.SetValue('RightPanelMode', 1, 'DWord') + $key.SetValue('LeftViewOrder', 0, 'DWord') + $key.SetValue('RightViewOrder', 0, 'DWord') + $key.SetValue('LeftPath', $left.FullName, 'String') + $key.SetValue('RightPath', $right.FullName, 'String') + $key.SetValue('LeftCursor', (Join-Path $left.FullName 'KSwitcher'), 'String') + $key.SetValue('RightCursor', (Join-Path $right.FullName 'src'), 'String') + $key.DeleteValue('WindowPlacement', $false) + $keyboard = New-Object -ComObject WScript.Shell + $process = Start-Process -FilePath $exe -PassThru + Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero -and [LavenderWindow]::Activate($process.MainWindowHandle) } + $window = $process.MainWindowHandle + $work = [Windows.Forms.Screen]::FromHandle($window).WorkingArea + $scale = [LavenderWindow]::GetDpiForWindow($window) / 96 + $width = [Math]::Min($work.Width - 30, [int](1220 * $scale)) + $height = [Math]::Min($work.Height - 30, [int](665 * $scale)) + [void][LavenderWindow]::SetWindowPos($window, [IntPtr]::Zero, $work.Left + 15, $work.Top + 15, $width, $height, 0x14) + [void][LavenderWindow]::SetForegroundWindow($window) + $leftList = [LavenderWindow]::GetDlgItem($window, 102) + $rightList = [LavenderWindow]::GetDlgItem($window, 103) + Wait-Until { [LavenderWindow]::Send($leftList, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq 6 -and + [LavenderWindow]::Send($rightList, 0x18B, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq 12 } + $farRow = [LavenderWindow]::Send($leftList, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() + Set-Style $window 1 + $rowHeight = [LavenderWindow]::Send($leftList, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() + $expectedHeight = [Math]::Max($farRow, [Math]::Round(25 * $scale, [MidpointRounding]::AwayFromZero)) + if ($rowHeight -ne $expectedHeight -or $key.GetValue('AppearanceMode') -ne 1) { + throw "Applying Lavender returned row height $rowHeight at scale $scale and saved mode $($key.GetValue('AppearanceMode'))." + } + $keyboard.SendKeys('{TAB}') + Start-Sleep -Milliseconds 250 + $bounds = Get-Bounds $window + $leftBounds = Get-Bounds $leftList + $rightBounds = Get-Bounds $rightList + $leftIndex = [LavenderWindow]::Send($leftList, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() + $rightIndex = [LavenderWindow]::Send($rightList, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() + if ($leftIndex -lt 0 -or $rightIndex -lt 0) { throw 'Missing current row for the appearance check.' } + $command = Get-Bounds ([LavenderWindow]::GetDlgItem($window, 113)) + $leftPath = Get-Bounds ([LavenderWindow]::GetDlgItem($window, 142)) + $rightPath = Get-Bounds ([LavenderWindow]::GetDlgItem($window, 143)) + $pad = [int](8 * $scale) + $image = Read-Window $bounds + try { + Test-Pixel $image $bounds ($leftPath.Left - $pad) ($leftPath.Top - $pad) '#EEF0FA' 'Rounded panel corner' + Test-Pixel $image $bounds ($rightPath.Left + 30) ($rightPath.Top - $pad) '#9797F4' 'Active panel outline' + Test-Pixel $image $bounds ([int](($leftBounds.Left + $leftBounds.Right) / 2)) ($leftBounds.Top + $leftIndex * $rowHeight + 5) '#F0F1F9' 'Inactive row' + Test-Pixel $image $bounds ([int](($rightBounds.Left + $rightBounds.Right) / 2)) ($rightBounds.Top + $rightIndex * $rowHeight + 5) '#E7E3FD' 'Active row after Tab' + Test-Pixel $image $bounds ($command.Right - 9) ($command.Top + 5) '#F7F7FD' 'Command button surface' + if ($Screenshot) { + $crop = [LavenderWindow+Rect]::new() + if ([LavenderWindow]::DwmGetWindowAttribute($window, 9, [ref]$crop, 16) -ne 0) { $crop = $bounds } + $area = [Drawing.Rectangle]::new(($crop.Left - $bounds.Left), ($crop.Top - $bounds.Top), + ($crop.Right - $crop.Left), ($crop.Bottom - $crop.Top)) + $visible = $image.Clone($area, [Drawing.Imaging.PixelFormat]::Format24bppRgb) + try { $visible.Save($Screenshot, [Drawing.Imaging.ImageFormat]::Png) } + finally { $visible.Dispose() } + } + } finally { $image.Dispose() } + + if ($DialogScreenshotDirectory) { [void][IO.Directory]::CreateDirectory($DialogScreenshotDirectory) } + Test-LavenderDialog $window '{F5}' 211 'Copy' + Test-LavenderDialog $window '{F6}' 211 'Rename/Move' + Test-LavenderDialog $window '{F7}' 361 'Make folder' + Test-LavenderDialog $window '{F8}' 241 'Delete' + + $keyboard.SendKeys('{F5}') + Wait-Until { [LavenderWindow]::GetDlgItem([LavenderWindow]::GetLastActivePopup($window), 211) -ne [IntPtr]::Zero } + $copy = [LavenderWindow]::GetLastActivePopup($window) + [void][LavenderWindow]::SendText([LavenderWindow]::GetDlgItem($copy, 211), 0xC, [IntPtr]::Zero, 'invalid*name') + [void][LavenderWindow]::Post($copy, 0x111, [IntPtr]1, [IntPtr]::Zero) + Wait-Until { + $popup = [LavenderWindow]::GetForegroundWindow() + [LavenderWindow]::GetWindow($popup, 4) -eq $copy -and + [LavenderWindow]::GetDlgItem($popup, 100) -ne [IntPtr]::Zero + } + $warning = [LavenderWindow]::GetForegroundWindow() + Start-Sleep -Milliseconds 160 + $warningBounds = Get-Bounds $warning + $warningButton = Get-Bounds ([LavenderWindow]::GetDlgItem($warning, 1)) + $warningImage = Read-Window $warningBounds + try { + Test-Pixel $warningImage $warningBounds ($warningBounds.Right - [int](8 * $scale)) ` + ($warningBounds.Top + [int](8 * $scale)) '#A12B48' 'Nested warning title band' + Test-Pixel $warningImage $warningBounds ($warningButton.Left + [int](9 * $scale)) ` + ([int](($warningButton.Top + $warningButton.Bottom) / 2)) '#A12B48' 'Nested warning action' + } finally { $warningImage.Dispose() } + $keyboard.SendKeys('{ESC}') + Wait-Until { ![LavenderWindow]::IsWindow($warning) } + $keyboard.SendKeys('{ESC}') + Wait-Until { ![LavenderWindow]::IsWindow($copy) -and [LavenderWindow]::Activate($window) } + + $options = Open-LavenderOptions $window + Start-Sleep -Milliseconds 160 + $optionsBounds = Get-Bounds $options + $visibleOptions = [LavenderWindow+Rect]::new() + if ([LavenderWindow]::DwmGetWindowAttribute($options, 9, [ref]$visibleOptions, 16) -eq 0) { + $optionsBounds = $visibleOptions + } + $searchBounds = Get-Bounds ([LavenderWindow]::GetDlgItem($options, 270)) + $optionsImage = Read-Window $optionsBounds + try { + Test-Pixel $optionsImage $optionsBounds ($searchBounds.Right - [int](12 * $scale)) ` + ([int](($searchBounds.Top + $searchBounds.Bottom) / 2)) '#F7F7FD' 'Options search field' + if ($DialogScreenshotDirectory) { + $optionsImage.Save((Join-Path $DialogScreenshotDirectory 'files-lavender-options.png'), [Drawing.Imaging.ImageFormat]::Png) + } + } finally { $optionsImage.Dispose() } + [void][LavenderWindow]::Post($options, 0x111, [IntPtr]2, [IntPtr]::Zero) + Wait-Until { ![LavenderWindow]::IsWindow($options) -and [LavenderWindow]::Activate($window) } + + $keyboard.SendKeys('{DOWN}') + Wait-Until { [LavenderWindow]::Send($rightList, 0x188, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -eq ($rightIndex + 1) } + $keyboard.SendKeys('^{F1}') + Wait-Until { $key.GetValue('RightPanelMode') -eq 0 } + $keyboard.SendKeys('^{F2}') + Wait-Until { $key.GetValue('RightPanelMode') -eq 1 } + [void][LavenderWindow]::SetWindowPos($window, [IntPtr]::Zero, $work.Left + 15, $work.Top + 15, + [int](580 * $scale), [int](420 * $scale), 0x14) + $compact = Get-Bounds ([LavenderWindow]::GetDlgItem($window, 113)) + if (($compact.Bottom - $compact.Top) -le ($command.Bottom - $command.Top)) { + throw 'The command bar did not switch to its compact layout.' + } + [void]$process.CloseMainWindow() + if (!$process.WaitForExit(4000)) { throw 'Files did not close.' } + $process = Start-Process -FilePath $exe -PassThru + Wait-Until { $process.Refresh(); $process.MainWindowHandle -ne [IntPtr]::Zero -and [LavenderWindow]::Activate($process.MainWindowHandle) } + $window = $process.MainWindowHandle + $leftList = [LavenderWindow]::GetDlgItem($window, 102) + if ([LavenderWindow]::Send($leftList, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $rowHeight) { + throw 'Lavender did not survive restart.' + } + Set-Style $window 0 + if ([LavenderWindow]::Send($leftList, 0x1A1, [IntPtr]::Zero, [IntPtr]::Zero).ToInt32() -ne $farRow) { + throw 'Far did not restore its row geometry.' + } + 'Lavender and Far switching, restart, keyboard navigation, Brief/Wide shortcuts, and rendered panels and dialogs verified.' +} finally { + if ($process -and !$process.HasExited) { + [void]$process.CloseMainWindow() + if (!$process.WaitForExit(3000)) { $process.Kill(); $process.WaitForExit() } + } + foreach ($name in $names) { + if ($saved.ContainsKey($name)) { $key.SetValue($name, $saved[$name][0], $saved[$name][1]) } + else { $key.DeleteValue($name, $false) } + } + $key.Dispose() + $resolvedFixture = (Resolve-Path -LiteralPath $fixture.FullName).Path + if ($resolvedFixture -eq $fixture.FullName) { $fixture.Delete($true) } + if ($previousDpi) { [void][LavenderWindow]::SetThreadDpiAwarenessContext($previousDpi) } +} From e7ef2e600bf5b6dcdfa8db9c16e219210513cbea Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Thu, 26 Nov 2026 21:18:21 +0200 Subject: [PATCH 57/61] Use compact breadcrumbs above Files panels in Lavender Refs #201 --- FILES-UI.md | 3 + src/files_lavender.inl | 17 ++- src/files_main.cpp | 25 ++-- src/files_path_bar.inl | 217 ++++++++++++++++++++++++++++++++++ src/files_path_navigation.inl | 127 +------------------- tests/files_lavender.ps1 | 37 +++++- 6 files changed, 281 insertions(+), 145 deletions(-) create mode 100644 src/files_path_bar.inl diff --git a/FILES-UI.md b/FILES-UI.md index 3b9a76c..8d46061 100644 --- a/FILES-UI.md +++ b/FILES-UI.md @@ -732,6 +732,9 @@ Warning і початковий фокус на No. попередньої гілки. Клік по поточній папці або кнопці редагування та Ctrl+L відкривають поле шляху. Tab доповнює назву папки, Enter відкриває шлях, а Esc повертає до тих самих панелей і курсора. +- Над обома панелями працює спільний компонент рядка шляху. У Lavender кнопки + навігації стоять ліворуч, а сегменти за шириною підпису розділяються знаком `›`. + Назва поточної папки виділена напівжирним шрифтом і заокругленим фоном. - У заголовку FTP- чи SFTP-папки клік по назві профілю відкриває збережені підключення. У LAN-папці клік по назві ПК відкриває спарені комп’ютери diff --git a/src/files_lavender.inl b/src/files_lavender.inl index 852f740..80b3cab 100644 --- a/src/files_lavender.inl +++ b/src/files_lavender.inl @@ -6,13 +6,19 @@ constexpr COLORREF activeEdge=RGB(151,151,244), selection=RGB(231,227,253), idle constexpr COLORREF folder=RGB(124,133,227), key=RGB(231,230,252), path=RGB(247,247,253); constexpr COLORREF marked=RGB(105,52,170), markedSelection=RGB(219,209,250); -HFONT font{}; +HFONT font{}, emphasis{}; void setFont(UINT dpi) { if(font) DeleteObject(font); - font=CreateFontW(-MulDiv(14,dpi,96),0,0,0,FW_NORMAL,FALSE,FALSE,FALSE,DEFAULT_CHARSET, - OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI"); + if(emphasis) DeleteObject(emphasis); + const auto create=[&](int weight) + { + return CreateFontW(-MulDiv(14,dpi,96),0,0,0,weight,FALSE,FALSE,FALSE,DEFAULT_CHARSET, + OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,CLEARTYPE_QUALITY,DEFAULT_PITCH,L"Segoe UI"); + }; + font=create(FW_NORMAL); + emphasis=create(FW_SEMIBOLD); } void fill(HDC dc,const RECT &rect,COLORREF color) @@ -34,10 +40,11 @@ void rounded(HDC dc,RECT rect,int radius,COLORREF color,COLORREF border) } void text(HDC dc,RECT rect,const wchar_t *label,COLORREF color,UINT alignment=DT_LEFT, - UINT ellipsis=DT_END_ELLIPSIS) + UINT ellipsis=DT_END_ELLIPSIS,HFONT textFont=nullptr) { if(rect.right<=rect.left) return; - const auto previous=SelectObject(dc,font?font:GetStockObject(DEFAULT_GUI_FONT)); + if(!textFont) textFont=font; + const auto previous=SelectObject(dc,textFont?textFont:GetStockObject(DEFAULT_GUI_FONT)); const auto background=SetBkMode(dc,TRANSPARENT); const auto inkColor=SetTextColor(dc,color); DrawTextW(dc,label,-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_NOPREFIX|alignment|ellipsis); diff --git a/src/files_main.cpp b/src/files_main.cpp index 474f2d4..ed1ee03 100644 --- a/src/files_main.cpp +++ b/src/files_main.cpp @@ -8847,6 +8847,7 @@ void handleFilesReturn(bool shift) } #include "files_smb.inl" +#include "files_path_bar.inl" #include "files_path_navigation.inl" LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) @@ -9260,22 +9261,11 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) { auto bounds=item.rcItem; const auto &panel=panels[item.CtlID-142]; - const auto path=panelCaption(panel); + const bool highlighted=static_cast(item.CtlID)-142==active; + const bool navigable=pathNavigationAvailable(panel); if(lavenderFiles()) { - const LavenderMetrics metrics(window); - const bool highlighted=static_cast(item.CtlID)-142==active; - lavender::fill(item.hDC,bounds,lavender::surface); - lavender::rounded(item.hDC,bounds,metrics.px(7),lavender::path, - highlighted?lavender::activeEdge:lavender::line); - if(pathNavigationAvailable(panel)) paintPanelPath(item.hDC,bounds,panel,highlighted); - else - { - paintLavenderFileIcon(item.hDC,bounds,metrics,true); - bounds.left+=metrics.px(30); - bounds.right-=metrics.px(9); - lavender::text(item.hDC,bounds,path.c_str(),lavender::ink,DT_LEFT,DT_PATH_ELLIPSIS); - } + paintLavenderPanelPath(item,panel,navigable,highlighted); return TRUE; } FillRect(item.hDC,&bounds,blue); @@ -9298,12 +9288,12 @@ LRESULT CALLBACK filesWindow(HWND window, UINT message, WPARAM wp, LPARAM lp) FillRect(item.hDC,&column,lineBrush); } } - const bool highlighted=static_cast(item.CtlID)-142==active; - if(pathNavigationAvailable(panel)) + if(navigable) { - paintPanelPath(item.hDC,bounds,panel,highlighted); + paintPanelPath(item.hDC,item.hwndItem,bounds,panel,highlighted); return TRUE; } + const auto path=panelCaption(panel); if(path.empty()) return TRUE; const int saved=SaveDC(item.hDC); SelectObject(item.hDC,mono); @@ -10251,6 +10241,7 @@ int WINAPI wWinMain(HINSTANCE instance, HINSTANCE, PWSTR, int show) } for(auto font:fileStyleFonts) if(font) DeleteObject(font); if(lavender::font) DeleteObject(lavender::font); + if(lavender::emphasis) DeleteObject(lavender::emphasis); DeleteObject(mono); DeleteObject(terminalFont); DeleteObject(blue); diff --git a/src/files_path_bar.inl b/src/files_path_bar.inl new file mode 100644 index 0000000..473fd10 --- /dev/null +++ b/src/files_path_bar.inl @@ -0,0 +1,217 @@ +enum class PathAction { back, forward, up, edit, source, ancestors, previous, folder }; + +struct PathPart +{ + PathAction action{}; + std::wstring label; + fs::path target; + std::vector hidden; + RECT rect{}; + RECT separator{}; + bool current{}, dim{}, enabled=true; +}; + +std::wstring pathSegmentLabel(const fs::path &path,FolderProvider provider,bool compact) +{ + if(isTransferFolder(provider) && path==ftpRoot) return L"/"; + if(compact && provider==FolderProvider::local && !path.has_relative_path()) + { + auto drive=path.root_name().native(); + if(drive.size()==2 && drive.back()==L':') return drive; + } + return panelParentPath(path,provider==FolderProvider::local).empty()?path.native():path.filename().native(); +} + +struct PathBarMetrics +{ + bool compact; + LavenderMetrics dpi; + LONG button, padding, separator; + + PathBarMetrics(HWND window,RECT bounds): compact(lavenderFiles()),dpi(window), + button(std::max(1L,std::min(compact?static_cast(dpi.px(21)):2L*cellWidth, + (bounds.right-bounds.left)/7))), + padding(compact?dpi.px(7):0),separator(compact?dpi.px(9):0) {} + + RECT breadcrumbBounds(RECT bounds) const + { + bounds.left=std::min(bounds.right,bounds.left+4*button+dpi.px(2)); + return bounds; + } +}; + +std::vector panelPathParts(HDC dc,const Panel &panel,RECT bounds,const PathBarMetrics &metrics) +{ + if(bounds.right<=bounds.left) return {}; + const LONG width=metrics.button; + const auto breadcrumb=metrics.breadcrumbBounds(bounds); + const auto font=metrics.compact && dc?SelectObject(dc,lavender::font?lavender::font:GetStockObject(DEFAULT_GUI_FONT)):nullptr; + const auto measure=[&](const std::wstring &label,bool current=false) + { + SIZE size{}; + if(font) + { + const auto regular=current && lavender::emphasis?SelectObject(dc,lavender::emphasis):nullptr; + const auto measured=GetTextExtentPoint32W(dc,label.c_str(),static_cast(label.size()),&size); + if(regular) SelectObject(dc,regular); + if(measured) return size.cx+2*metrics.padding; + } + return static_cast(label.size()+2)*cellWidth; + }; + std::vector parts; + bool hasCrumb=false; + const auto add=[&](PathPart part,LONG length,bool crumb=false) + { + if(length<=0 || bounds.left>=bounds.right) return; + if(crumb && hasCrumb && metrics.separator) + { + const auto end=std::min(bounds.right-1,bounds.left+metrics.separator); + part.separator={bounds.left,bounds.top,end,bounds.bottom}; + bounds.left=end; + } + part.rect={bounds.left,bounds.top,std::min(bounds.right,bounds.left+length),bounds.bottom}; + bounds.left=part.rect.right; + parts.push_back(std::move(part)); + hasCrumb|=crumb; + }; + const auto location=folderLocation(panel,panel.directory); + const auto provider=location.provider; + const auto local=provider==FolderProvider::local; + const auto parent=panelParentPath(panel.directory,local); + add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width); + add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width); + add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width); + add({.action=PathAction::edit,.label=L"✎"},width); + + if(metrics.compact) + { + bounds.left=std::min(bounds.right,breadcrumb.left+metrics.dpi.px(1)); + bounds.right=std::max(bounds.left,bounds.right-metrics.dpi.px(1)); + } + if(!local && (!metrics.compact || !location.label.empty())) + { + const auto available=std::max(1L,(bounds.right-bounds.left)/2); + add({.action=PathAction::source,.label=location.label},std::min(available,measure(location.label)),true); + } + + std::vector ancestors, previous; + for(auto path=parent;!path.empty();path=panelParentPath(path,local)) ancestors.push_back(path); + std::reverse(ancestors.begin(),ancestors.end()); + if(inFolderBranch(panel.directory,panel.navigation.previousBranch,provider)) + { + for(auto path=panel.navigation.previousBranch;!sameFolderPath(path,panel.directory,provider); + path=panelParentPath(path,local)) + previous.push_back(path); + std::reverse(previous.begin(),previous.end()); + } + + const LONG room=bounds.right-bounds.left; + const auto label=[&](const fs::path &path) { return pathSegmentLabel(path,provider,metrics.compact); }; + const auto segmentWidth=[&](const fs::path &path) { return measure(label(path))+metrics.separator; }; + const LONG overflowWidth=width+metrics.separator; + LONG currentWidth=measure(label(panel.directory),true); + LONG required=currentWidth+metrics.separator; + for(const auto &path:ancestors) required+=segmentWidth(path); + for(const auto &path:previous) required+=segmentWidth(path); + if(!hasCrumb) required-=metrics.separator; + size_t firstAncestor=0,visiblePrevious=previous.size(); + if(required>room) + { + const LONG reserved=(!ancestors.empty()?overflowWidth:0)+(!previous.empty()?overflowWidth:0)+ + (hasCrumb?metrics.separator:0); + currentWidth=std::min(currentWidth,std::max(1L,room-reserved)); + LONG remaining=room-currentWidth-reserved; + firstAncestor=ancestors.size(); + while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1])) + remaining-=segmentWidth(ancestors[--firstAncestor]); + visiblePrevious=0; + while(visiblePrevious=segmentWidth(previous[visiblePrevious])) + remaining-=segmentWidth(previous[visiblePrevious++]); + } + + if(firstAncestor) + add({.action=PathAction::ancestors,.label=L"…", + .hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width,true); + for(size_t i=firstAncestor;i2*radius) + { + const LONG x=(gap.left+gap.right)/2, y=(gap.top+gap.bottom)/2; + const auto pen=SelectObject(dc,separatorPen?separatorPen:GetStockObject(DC_PEN)); + if(!separatorPen) SetDCPenColor(dc,lavender::muted); + MoveToEx(dc,x-1,y-radius,nullptr); + LineTo(dc,x+radius-1,y); + LineTo(dc,x-1,y+radius+1); + SelectObject(dc,pen); + } + if(part.current) + { + auto chip=part.rect; + InflateRect(&chip,0,-metrics.dpi.px(3)); + lavender::rounded(dc,chip,metrics.dpi.px(5),lavender::key,lavender::key); + InflateRect(&label,-metrics.dpi.px(4),0); + } + lavender::text(dc,label,part.label.c_str(),!part.enabled || part.dim?lavender::muted:lavender::ink, + DT_CENTER,DT_END_ELLIPSIS,part.current?lavender::emphasis:nullptr); + continue; + } + FillRect(dc,&part.rect,current?teal:blue); + SetTextColor(dc,!part.enabled || part.dim?RGB(160,170,190):colors[current?Text:Frame]); + auto text=part.rect; + DrawTextW(dc,part.label.c_str(),static_cast(part.label.size()),&text, + DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX); + } + if(separatorPen) DeleteObject(separatorPen); + if(saved) RestoreDC(dc,saved); +} + +void paintLavenderPanelPath(const DRAWITEMSTRUCT &item,const Panel &panel,bool navigable,bool activePanel) +{ + auto bounds=item.rcItem; + lavender::fill(item.hDC,bounds,lavender::surface); + if(navigable) + { + paintPanelPath(item.hDC,item.hwndItem,bounds,panel,activePanel); + return; + } + const LavenderMetrics metrics(item.hwndItem); + lavender::rounded(item.hDC,bounds,metrics.px(7),lavender::path, + activePanel?lavender::activeEdge:lavender::line); + paintLavenderFileIcon(item.hDC,bounds,metrics,true); + bounds.left+=metrics.px(30); + bounds.right-=metrics.px(9); + const auto caption=panelCaption(panel); + lavender::text(item.hDC,bounds,caption.c_str(),lavender::ink,DT_LEFT,DT_PATH_ELLIPSIS); +} diff --git a/src/files_path_navigation.inl b/src/files_path_navigation.inl index 348d406..e0a9a7b 100644 --- a/src/files_path_navigation.inl +++ b/src/files_path_navigation.inl @@ -4,8 +4,6 @@ bool pathNavigationAvailable(const Panel &panel) return !transferProfileList(panel) && !panel.findOrigin && !panel.archive && !panel.directory.empty(); } -enum class PathAction { back, forward, up, edit, source, ancestors, previous, folder }; - void navigatePanelPath(Panel &panel,const fs::path &path) { if(path.empty()) return; @@ -25,125 +23,6 @@ void navigatePanelHistory(Panel &panel,int direction) } } -struct PathPart -{ - PathAction action{}; - std::wstring label; - fs::path target; - std::vector hidden; - RECT rect{}; - bool current{}, dim{}, enabled=true; -}; - -std::wstring pathSegmentLabel(const fs::path &path,FolderProvider provider) -{ - if(isTransferFolder(provider) && path==ftpRoot) return L"/"; - return panelParentPath(path,provider==FolderProvider::local).empty()?path.native():path.filename().native(); -} - -LONG segmentWidth(const fs::path &path,FolderProvider provider) -{ - return static_cast(pathSegmentLabel(path,provider).size()+2)*cellWidth; -} - -std::vector panelPathParts(const Panel &panel,RECT bounds) -{ - const LONG total=bounds.right-bounds.left; - if(total<=0) return {}; - const LONG width=std::max(1L,std::min(2L*cellWidth,total/7)); - std::vector parts; - const auto add=[&](PathPart part,LONG length) - { - if(length<=0 || bounds.left>=bounds.right) return; - part.rect={bounds.left,bounds.top,std::min(bounds.right,bounds.left+length),bounds.bottom}; - bounds.left=part.rect.right; - parts.push_back(std::move(part)); - }; - const auto location=folderLocation(panel,panel.directory); - const auto provider=location.provider; - const auto local=provider==FolderProvider::local; - const auto parent=panelParentPath(panel.directory,local); - add({.action=PathAction::back,.label=L"←",.enabled=panel.navigation.neighbor(-1).has_value()},width); - add({.action=PathAction::forward,.label=L"→",.enabled=panel.navigation.neighbor(1).has_value()},width); - add({.action=PathAction::up,.label=L"↑",.target=parent,.enabled=!parent.empty()},width); - add({.action=PathAction::edit,.label=L"✎"},width); - - if(!local) - { - const auto available=std::max(1L,(bounds.right-bounds.left)/2); - const auto sourceWidth=std::min(available,static_cast(location.label.size()+2)*cellWidth); - add({.action=PathAction::source,.label=location.label},sourceWidth); - } - - std::vector ancestors, previous; - for(auto path=parent;!path.empty();path=panelParentPath(path,local)) ancestors.push_back(path); - std::reverse(ancestors.begin(),ancestors.end()); - if(inFolderBranch(panel.directory,panel.navigation.previousBranch,provider)) - { - for(auto path=panel.navigation.previousBranch;!sameFolderPath(path,panel.directory,provider); - path=panelParentPath(path,local)) - previous.push_back(path); - std::reverse(previous.begin(),previous.end()); - } - - const LONG room=bounds.right-bounds.left; - LONG required=segmentWidth(panel.directory,provider); - for(const auto &path:ancestors) required+=segmentWidth(path,provider); - for(const auto &path:previous) required+=segmentWidth(path,provider); - size_t firstAncestor=0,visiblePrevious=previous.size(); - LONG currentWidth=segmentWidth(panel.directory,provider); - if(required>room) - { - const LONG reserved=(!ancestors.empty()?width:0)+(!previous.empty()?width:0); - currentWidth=std::min(currentWidth,std::max(1L,room-reserved)); - LONG remaining=room-currentWidth-reserved; - firstAncestor=ancestors.size(); - while(firstAncestor && remaining>=segmentWidth(ancestors[firstAncestor-1],provider)) - remaining-=segmentWidth(ancestors[--firstAncestor],provider); - visiblePrevious=0; - while(visiblePrevious=segmentWidth(previous[visiblePrevious],provider)) - remaining-=segmentWidth(previous[visiblePrevious++],provider); - } - - if(firstAncestor) - add({.action=PathAction::ancestors,.label=L"…", - .hidden={ancestors.begin(),ancestors.begin()+firstAncestor}},width); - for(size_t i=firstAncestor;i(part.label.size()),&text, - DT_CENTER|DT_VCENTER|DT_SINGLELINE|DT_END_ELLIPSIS|DT_NOPREFIX); - } - if(saved) RestoreDC(dc,saved); -} - constexpr int addressField=485,addressLabel=486,addressFooter=487; struct PathPrompt @@ -439,7 +318,11 @@ LRESULT CALLBACK pathBarInput(HWND window,UINT message,WPARAM wp,LPARAM lp,UINT_ RECT bounds{}; GetClientRect(window,&bounds); const POINT mouse{GET_X_LPARAM(lp),GET_Y_LPARAM(lp)}; - const auto parts=panelPathParts(panel,bounds); + const PathBarMetrics metrics(window,bounds); + const auto dc=metrics.compact?GetDC(window):nullptr; + if(metrics.compact && !dc) return 0; + const auto parts=panelPathParts(dc,panel,bounds,metrics); + if(dc) ReleaseDC(window,dc); for(const auto &part:parts) { if(!part.enabled || !PtInRect(&part.rect,mouse)) continue; diff --git a/tests/files_lavender.ps1 b/tests/files_lavender.ps1 index fe60f6e..2e83d81 100644 --- a/tests/files_lavender.ps1 +++ b/tests/files_lavender.ps1 @@ -67,6 +67,29 @@ function Test-Pixel($Image, $Bounds, $X, $Y, $Expected, $Description) { } } +function Test-PathBar($Image, $Bounds, $Path, [double]$Scale, [string]$Name) { + $chip = [Drawing.ColorTranslator]::FromHtml('#E7E6FC').ToArgb() + $separator = [Drawing.ColorTranslator]::FromHtml('#5B6185').ToArgb() + $chipColumns = [Collections.Generic.List[int]]::new() + $chevrons = 0 + $chipY = $Path.Top - $Bounds.Top + [int](5 * $Scale) + $centerY = [int][Math]::Floor(($Path.Top + $Path.Bottom) / 2) - $Bounds.Top + for ($x = $Path.Left - $Bounds.Left + [int](85 * $Scale); $x -lt $Path.Right - $Bounds.Left; $x++) { + if ($Image.GetPixel($x, $chipY).ToArgb() -eq $chip) { $chipColumns.Add($x) } + if ($Image.GetPixel($x, $centerY).ToArgb() -eq $separator) { $chevrons++ } + } + if ($chevrons -eq 0) { throw "$Name does not render a breadcrumb chevron." } + if ($chipColumns.Count -lt [int](35 * $Scale) -or $chipColumns.Count -gt [int](93 * $Scale)) { + throw "$Name does not fit the current-folder chip to its label ($($chipColumns.Count) pixels)." + } + $edgeY = $Path.Top - $Bounds.Top + [int][Math]::Floor($Scale) + $chipCenter = $chipColumns[[int][Math]::Floor($chipColumns.Count / 2)] + if ($Image.GetPixel($chipCenter, $edgeY).ToArgb() -eq $chip) { + throw "$Name current-folder chip touches the top edge of the bar." + } + $chipCenter + $Bounds.Left - $Path.Left +} + function Open-LavenderOptions($Window) { $keyboard.SendKeys('{F9}') Wait-Until { [LavenderWindow]::IsWindowVisible([LavenderWindow]::GetDlgItem($Window, 133)) } @@ -197,12 +220,15 @@ try { if ($leftIndex -lt 0 -or $rightIndex -lt 0) { throw 'Missing current row for the appearance check.' } $command = Get-Bounds ([LavenderWindow]::GetDlgItem($window, 113)) $leftPath = Get-Bounds ([LavenderWindow]::GetDlgItem($window, 142)) - $rightPath = Get-Bounds ([LavenderWindow]::GetDlgItem($window, 143)) + $rightPathWindow = [LavenderWindow]::GetDlgItem($window, 143) + $rightPath = Get-Bounds $rightPathWindow $pad = [int](8 * $scale) $image = Read-Window $bounds try { Test-Pixel $image $bounds ($leftPath.Left - $pad) ($leftPath.Top - $pad) '#EEF0FA' 'Rounded panel corner' Test-Pixel $image $bounds ($rightPath.Left + 30) ($rightPath.Top - $pad) '#9797F4' 'Active panel outline' + [void](Test-PathBar $image $bounds $leftPath $scale 'Inactive panel path') + $currentFolderX = Test-PathBar $image $bounds $rightPath $scale 'Active panel path' Test-Pixel $image $bounds ([int](($leftBounds.Left + $leftBounds.Right) / 2)) ($leftBounds.Top + $leftIndex * $rowHeight + 5) '#F0F1F9' 'Inactive row' Test-Pixel $image $bounds ([int](($rightBounds.Left + $rightBounds.Right) / 2)) ($rightBounds.Top + $rightIndex * $rowHeight + 5) '#E7E3FD' 'Active row after Tab' Test-Pixel $image $bounds ($command.Right - 9) ($command.Top + 5) '#F7F7FD' 'Command button surface' @@ -217,6 +243,15 @@ try { } } finally { $image.Dispose() } + $middleY = [int](($rightPath.Bottom - $rightPath.Top) / 2) + $click = [IntPtr](($middleY -shl 16) + $currentFolderX) + [void][LavenderWindow]::Post($rightPathWindow, 0x201, [IntPtr]1, $click) + [void][LavenderWindow]::Post($rightPathWindow, 0x202, [IntPtr]::Zero, $click) + Wait-Until { [LavenderWindow]::GetDlgItem([LavenderWindow]::GetLastActivePopup($window), 485) -ne [IntPtr]::Zero } + $address = [LavenderWindow]::GetLastActivePopup($window) + [void][LavenderWindow]::Post($address, 0x111, [IntPtr]2, [IntPtr]::Zero) + Wait-Until { ![LavenderWindow]::IsWindow($address) -and [LavenderWindow]::Activate($window) } + if ($DialogScreenshotDirectory) { [void][IO.Directory]::CreateDirectory($DialogScreenshotDirectory) } Test-LavenderDialog $window '{F5}' 211 'Copy' Test-LavenderDialog $window '{F6}' 211 'Rename/Move' From e2b9a65237737b66c665959f86e85c763af3d243 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Thu, 26 Nov 2026 22:00:30 +0200 Subject: [PATCH 58/61] Prepare KSwitcher v0.8.3 for delivery Refs #201 --- CMakeLists.txt | 2 +- Release/README.md | 8 ++++ Release/SHA256SUMS.txt | 2 +- Release/release-files.json | 76 +++++++++++++++++++------------------- resources/app.rc | 6 +-- src/update.h | 2 +- 6 files changed, 52 insertions(+), 44 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index a4a2460..2d84959 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.8.2 LANGUAGES C CXX RC) +project(KSwitcher VERSION 0.8.3 LANGUAGES C CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() diff --git a/Release/README.md b/Release/README.md index a0512c5..41d5f90 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,13 @@ # Latest Windows release +## v0.8.3 — 2026-11-26 + +- **Files.** Lavender now shows compact path segments with chevrons above both panes. The current folder has a rounded highlight. Click an ancestor to open it, the current folder to edit the path, or an ellipsis to reveal hidden folders. + +**Українською.** + +- **Files.** У Lavender над обома панелями тепер видно компактні сегменти шляху з роздільниками `›`. Поточна папка має заокруглене виділення. Клік на батьківській папці відкриває її, клік на поточній відкриває введення шляху, а трикрапка показує приховані папки. + ## v0.8.2 — 2026-11-26 - **Files.** Choose **F9 → Options → Appearance → Window style → Lavender** for light panes, clearer selection and a redesigned command bar. File operation dialogs have a dark title band, with a red band for warnings. Far remains the default, and keyboard shortcuts work in both styles. diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index d75d2d2..280a319 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -01cc0f4cf1555c6e038ab6ff4d00439c28f4a79ca8452fd5e3f4158947e5ceab KSwitcher-win-x64.zip +0726c819b43cd1508c4fa22b717ab13b0da826f5a48bbc3a4b0f10e6418d207a KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index 0d78217..b91d925 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,180 +1,180 @@ { + "version": "0.8.3", "schema": 1, - "version": "0.8.2", "files": [ { + "sha256": "134aff7d86cdba13eecf9e32a0556e0267c0900800bd6dc1e9b005729190eb7a", "path": "KSwitcher.exe", - "sha256": "37cdbed818cb6351e606c8ef4a052a8d1218c515863787b2d407c97cb88858c7", - "size": 3244544 + "size": 3247616 }, { + "sha256": "7f90f6af18c9ac7f9e0f8255bfd339c49c9ea28e2da88d6b6e3443f6a867a1dd", "path": "KSwitcher.Config.exe", - "sha256": "6ab516b657c95c9fe5461b71e020831337831bd7807b1991a71a4bb40f26889e", "size": 2849792 }, { + "sha256": "f010f82aba8ace45abf0b90db991804964c1ec18f783a4169add56f478c96344", "path": "KSwitcher.Screenshot.exe", - "sha256": "dbc7f702c25ea63e5c8b64bb0a76b8a058cf75938262fb0a20113e80b00d88b7", "size": 3193344 }, { + "sha256": "caa66e3d8cddd094f1de317fb1a6410d4413f30034cdb61f130d7fcee21004bb", "path": "KSwitcher.Files.exe", - "sha256": "98326211b088d838720068863edfc38988f54b27326e62ed1b4ab79c3f455ab8", - "size": 5998592 + "size": 6000640 }, { - "path": "WebView2Loader.dll", "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6", + "path": "WebView2Loader.dll", "size": 194912 }, { - "path": "terminal/addon-fit-LICENSE.txt", "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f", + "path": "terminal/addon-fit-LICENSE.txt", "size": 1103 }, { - "path": "terminal/addon-fit.js", "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527", + "path": "terminal/addon-fit.js", "size": 1521 }, { - "path": "terminal/index.html", "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef", + "path": "terminal/index.html", "size": 527 }, { - "path": "terminal/markdown-it-LICENSE.txt", "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473", + "path": "terminal/markdown-it-LICENSE.txt", "size": 1073 }, { - "path": "terminal/markdown-it.js", "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e", + "path": "terminal/markdown-it.js", "size": 100786 }, { - "path": "terminal/markdown.html", "sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2", + "path": "terminal/markdown.html", "size": 3800 }, { - "path": "terminal/markdown.js", "sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96", + "path": "terminal/markdown.js", "size": 18721 }, { - "path": "terminal/mermaid-LICENSE.txt", "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80", + "path": "terminal/mermaid-LICENSE.txt", "size": 1089 }, { - "path": "terminal/mermaid.js", "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3", + "path": "terminal/mermaid.js", "size": 5537838 }, { - "path": "terminal/terminal.js", "sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7", + "path": "terminal/terminal.js", "size": 6627 }, { - "path": "terminal/xterm-LICENSE.txt", "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd", + "path": "terminal/xterm-LICENSE.txt", "size": 1261 }, { - "path": "terminal/xterm.css", "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6", + "path": "terminal/xterm.css", "size": 7112 }, { - "path": "terminal/xterm.js", "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972", + "path": "terminal/xterm.js", "size": 488663 }, { - "path": "LICENSE", "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c", + "path": "LICENSE", "size": 4401 }, { - "path": "json-LICENSE.txt", "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831", + "path": "json-LICENSE.txt", "size": 1096 }, { - "path": "files-text-license.txt", "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625", + "path": "files-text-license.txt", "size": 883 }, { - "path": "files-archive-license.txt", "sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d", + "path": "files-archive-license.txt", "size": 4990 }, { - "path": "files-image-license.txt", "sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4", + "path": "files-image-license.txt", "size": 3044 }, { - "path": "files-sftp-license.txt", "sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594", + "path": "files-sftp-license.txt", "size": 2064 }, { - "path": "README.md", "sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01", + "path": "README.md", "size": 105515 }, { - "path": "LAN-PREVIEW.md", "sha256": "917c2f41b3943647fdfafa911d93f72b8c6fb0d08592016ce1a698d256e038bb", + "path": "LAN-PREVIEW.md", "size": 16722 }, { - "path": "dictionaries/en.txt", "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9", + "path": "dictionaries/en.txt", "size": 732485 }, { - "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt", "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5", + "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt", "size": 20566 }, { - "path": "dictionaries/README.md", "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311", + "path": "dictionaries/README.md", "size": 2265 }, { - "path": "dictionaries/ru.txt", "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849", + "path": "dictionaries/ru.txt", "size": 1109134 }, { - "path": "dictionaries/sources.json", "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408", + "path": "dictionaries/sources.json", "size": 1280 }, { - "path": "dictionaries/uk.txt", "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf", + "path": "dictionaries/uk.txt", "size": 940799 }, { - "path": "tools/README.txt", "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a", + "path": "tools/README.txt", "size": 993 }, { + "sha256": "b6a36bcdc26fc6bb55083e023e2fafb60236e541e9b1b7e598c66816a3089175", "path": "tools/StayHere.exe", - "sha256": "87f842e25d07bf95dee8116733a10fd2e24fa9a10d645c5ea1f374908aaf0e0b", "size": 133120 }, { - "path": "tools/StayHere-README.md", "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413", + "path": "tools/StayHere-README.md", "size": 2796 } ] diff --git a/resources/app.rc b/resources/app.rc index 52ec714..53356b4 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -14,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur" 1 RT_MANIFEST "app.manifest" 201 RCDATA "update.ps1" 1 VERSIONINFO - FILEVERSION 0,8,2,0 - PRODUCTVERSION 0,8,2,0 + FILEVERSION 0,8,3,0 + PRODUCTVERSION 0,8,3,0 FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN @@ -25,7 +25,7 @@ BEGIN BEGIN VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility" VALUE "ProductName", "KSwitcher" - VALUE "FileVersion", "0.8.2" + VALUE "FileVersion", "0.8.3" END END BLOCK "VarFileInfo" diff --git a/src/update.h b/src/update.h index 682945a..66a40aa 100644 --- a/src/update.h +++ b/src/update.h @@ -2,7 +2,7 @@ #include "platform.h" namespace ks { -inline constexpr wchar_t AppVersion[] = L"0.8.2"; +inline constexpr wchar_t AppVersion[] = L"0.8.3"; inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; From 20bd93b76b9bd918575e8af8dfaab11f5b03a38c Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Fri, 27 Nov 2026 03:26:54 +0200 Subject: [PATCH 59/61] Move chat language profiles into Settings Refs #204 --- README.md | 18 ++- src/ui.cpp | 337 +++++++++++++++++----------------------- tests/chat_profiles.cpp | 107 +++++++------ 3 files changed, 216 insertions(+), 246 deletions(-) diff --git a/README.md b/README.md index ef4aff8..4483561 100644 --- a/README.md +++ b/README.md @@ -440,9 +440,10 @@ Drag the divider to resize navigation. The window remembers its size, position, Switching sections preserves your edits. Save, Cancel, Import and Export stay below every page. Open the desired chat in Telegram Desktop or Microsoft Teams, then open Settings → Languages → -**Languages for a chat…**. Select the chat and click the languages to include. Choose -**Use languages**, then **Save** in Settings. The subset order is saved from the main -layout list when editing the profile; one-language profiles are supported. **Remove profile** restores default behavior. +**Languages for a chat** in the navigation tree. Find the contact, select the chat and +choose the layouts to include. Click **Apply** to keep Settings open or **Save** to close it. +A profile can contain a single layout and cycles through its layouts in the order shown. +Use **Remove profile** and apply or save the change to restore default behavior. For a matching chat, **Alt+Shift**, **Win+Space** (and reverse **Win+Shift+Space**) cycle through that subset. KSwitcher's **Next layout** conversion uses the same subset. @@ -461,10 +462,11 @@ From v0.6.53, chat profiles (application, visible chat name and ordered language **Українською.** Вибирайте розділ у дереві Settings або шукайте окремий параметр через **Search settings**. Перетягніть розділювач, щоб змінити ширину дерева. Settings запам’ятовує розмір і положення вікна та активний розділ. Перехід між розділами зберігає чернетку. Save, Cancel, Import і Export доступні знизу. Відкрий потрібний чат у Telegram або Teams, потім **Settings → Languages → Languages -for a chat…**. Вибери чат і потрібні мови, натисни **Use languages**, а потім **Save**. +for a chat** у дереві налаштувань. Знайдіть контакт, виберіть чат і потрібні розкладки. +Натисніть **Apply**, щоб залишити Settings відкритим, або **Save**, щоб закрити його. Набір діє для **Alt+Shift**, **Win+Space**, **Win+Shift+Space** та **Next layout** KSwitcher. -Можна вибрати й одну мову; порядок зберігається із загального списку під час редагування профілю. **Remove profile** -повертає звичайну поведінку. Без профілю системні комбінації працюють як раніше, +Можна вибрати одну розкладку. Розкладки перемикаються в порядку, показаному в списку. +Натисніть **Remove profile** і застосуйте або збережіть зміни, щоб повернути звичайну поведінку. Без профілю системні комбінації працюють як раніше, а Next layout використовує загальний набір. Видалені з Windows розкладки пропускаються; якщо доступних мов профілю не залишилося, використовується загальний набір. Прямі комбінації мов не змінюються; явно задані комбінації KSwitcher мають пріоритет. @@ -478,11 +480,11 @@ Telegram ігнорується. Teams підтримує зазначений ### Telegram Web in Chrome — v0.6.51 -Open a chat in Telegram Web K (`https://web.telegram.org/k/`) in Chrome, then use **Settings → Languages → Languages for a chat...** and select **Telegram Web: name**. Choose languages, then **Use languages → Save**. The same subset applies to Alt+Shift, Win+Space, Win+Shift+Space and Next layout. Web profiles are separate from desktop Telegram profiles. Same-name chats across browser profiles/accounts share a web profile. +Open a chat in Telegram Web K (`https://web.telegram.org/k/`) in Chrome, then use **Settings → Languages → Languages for a chat** and select the contact with **Telegram Web** in the App column. Choose layouts and click **Apply** or **Save**. The same subset applies to Alt+Shift, Win+Space, Win+Shift+Space and Next layout. Web profiles are separate from desktop Telegram profiles. Same-name chats across browser profiles/accounts share a web profile. Recognition uses Chrome accessibility: the address bar and active document must both identify a Telegram chat, then the visible header supplies the name. The app watches foreground/focus and address/header-change events; it does not use OCR, a polling timer, an extension, or message-history extraction. The address bar, home page and unsupported URLs do not match. Web A and other browsers have not been validated and are not advertised as supported. Page or accessibility changes can make a chat unavailable instead of guessing. -**Українською.** З v0.6.51 підтримано Telegram Web K у Chrome. Відкрий чат, потім **Settings → Languages → Languages for a chat...**, вибери **Telegram Web: ім’я**, мови та **Use languages → Save**. Набір діє для Alt+Shift, Win+Space, Win+Shift+Space і Next layout. Вебпрофілі окремі від Telegram Desktop; однакові назви в різних акаунтах/профілях браузера мають спільний вебпрофіль. Адреса й назва беруться через accessibility, без OCR, таймера, розширення та читання історії повідомлень. В адресному рядку, на головній сторінці й для непідтримуваних адрес профіль не діє. Web A та інші браузери не перевірені й не заявлені як підтримувані. +**Українською.** З v0.6.51 підтримано Telegram Web K у Chrome. Відкрий чат, потім **Settings → Languages → Languages for a chat**, вибери контакт із **Telegram Web** у колонці App та потрібні розкладки, а потім натисни **Apply** або **Save**. Набір діє для Alt+Shift, Win+Space, Win+Shift+Space і Next layout. Вебпрофілі окремі від Telegram Desktop; однакові назви в різних акаунтах/профілях браузера мають спільний вебпрофіль. Адреса й назва беруться через accessibility, без OCR, таймера, розширення та читання історії повідомлень. В адресному рядку, на головній сторінці й для непідтримуваних адрес профіль не діє. Web A та інші браузери не перевірені й не заявлені як підтримувані. ### Snippet autocomplete — v0.6.69 diff --git a/src/ui.cpp b/src/ui.cpp index bf3407c..7892fcd 100644 --- a/src/ui.cpp +++ b/src/ui.cpp @@ -1210,7 +1210,8 @@ LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) #ifndef KS_RESIDENT_APP constexpr int LanguagesPage = 1, ShortcutsPage = 2, ClipboardPage = 3, SnippetsPage = 4, MousePage = 5; constexpr int ExceptionsPage = 13, PersonalDictionariesPage = 14, WordBoundariesPage = 15, SnippetMacros = 320; -constexpr int CustomReplacementsPage = 16; +constexpr int CustomReplacementsPage = 16, ChatLanguagesPage = 20; +constexpr int ChatContacts = 710, ChatLayouts = 711, ChatProfileStatus = 712, ChatRemoveProfile = 713, ChatSearch = 714; constexpr int ClipboardExcludedApps = 243, ClipboardAppName = 244, ClipboardAddApp = 245, ClipboardRemoveApp = 246, ClipboardAppPicker = 247; constexpr UINT AppWindowPicked = WM_APP + 78; @@ -1254,6 +1255,7 @@ constexpr struct SettingsSection {"openbao", L"OpenBao", L"Connect to OpenBao and synchronize your saved settings.", SyncPage}, {"google-drive", L"Google Drive", L"Synchronize settings across PCs or manage manual backups.", SyncPage}, {"ocr", L"Image text recognition", L"Choose Windows OCR or Tesseract. Recognition runs on this computer.", ClipboardPage}, + {"chat-languages", L"Languages for a chat", L"Choose which keyboard layouts to cycle through in a chat.", LanguagesPage}, }; constexpr wchar_t SettingsWindowFile[] = L"configurator-window.json"; struct SettingsWindowState @@ -1353,6 +1355,9 @@ struct SettingsView SIZE mouseProfileCheckSize{}; unsigned mouseEvents{}, rawMouseEvents{}; bool rawMouseRegistered{}; + std::vector chatKeys; + int chatSelection = -1; + bool updatingChatContacts{}; SnippetView snippets; HWND clipboardPickerOutline{}; }; @@ -1863,6 +1868,8 @@ void reflowSettingsPage(HWND pane, WindowLayout &layout, int width, int height) } layout.height = fitSettingsColumns(layout, page.first, page.end, available, grid); const int extra = height * 96 / static_cast(dpi) - layout.height; + if (v.selectedPage == ChatLanguagesPage) + stretchSettingsEditors(layout, page.first, page.end, std::min(extra, 160), {ChatContacts, ChatLayouts}, true); if (v.selectedPage == SnippetsPage) stretchSettingsEditors(layout, page.first, page.end, extra, {301, 303}, available < grid.wrapAt); if (v.selectedPage == MousePage) @@ -1954,6 +1961,7 @@ void reflowClipboard(HWND pane, WindowLayout &layout, int width, int height) if (scale(pane, layout.height) > height) fit(width - GetSystemMetricsForDpi(SM_CXVSCROLL, dpi)); } +void refreshChatLanguages(SettingsView &v); void selectSettingsPage(SettingsView &v, int selected) { if (selected < 0 || selected >= (int)v.pages.size() || selected == v.selectedPage) return; @@ -1968,6 +1976,7 @@ void selectSettingsPage(SettingsView &v, int selected) ShowWindow(layout.controls[i].first, SW_HIDE); } v.selectedPage = selected; + if (selected == ChatLanguagesPage) refreshChatLanguages(v); SetWindowTextW(v.heading, settingsSections[selected].name); SetWindowTextW(v.description, settingsSections[selected].description); const auto &page = v.pages[selected]; @@ -2274,81 +2283,42 @@ void indexSettingsControl(SettingsView &v, int page, HWND child) } v.searchEntries.push_back({page, child, target, std::move(text), aliases}); } -struct ChatLanguagesView +void fillChatLanguages(SettingsView &v) { - HWND parent{}; - SettingsView *settings{}; - std::vector keys; - Settings draft; - int selection = -1; - bool dirty{}; - bool updatingList{}; - std::wstring search; -}; -void collectChatLanguages(HWND w, ChatLanguagesView *v) -{ - if (!v->dirty || v->selection < 0) return; - std::vector cycle; - for (size_t i = 0; i < v->settings->order.size(); ++i) - if (SendDlgItemMessageW(w, 711, LB_GETSEL, i, 0) > 0) - cycle.push_back(v->settings->app->layouts[v->settings->order[i]].id); - if (cycle.empty()) throw std::runtime_error("Select at least one language."); - v->draft.chatCycles[v->keys[v->selection]] = std::move(cycle); - v->dirty = false; -} -void fillChatLanguages(HWND w, ChatLanguagesView *v) -{ - int index = v->selection; - EnableWindow(GetDlgItem(w, 711), index >= 0); - EnableWindow(GetDlgItem(w, IDOK), index >= 0); - if (index < 0) + HWND pane = v.viewport; + const bool selected = v.chatSelection >= 0; + EnableWindow(GetDlgItem(pane, ChatLayouts), selected && !v.order.empty()); + if (!selected) { - SendDlgItemMessageW(w, 711, LB_SETSEL, FALSE, -1); - EnableWindow(GetDlgItem(w, 713), FALSE); - value(w, 712, v->keys.empty() ? L"Open a chat, then reopen this dialog to add it." : - L"No contacts match your search."); + SendDlgItemMessageW(pane, ChatLayouts, LB_SETSEL, FALSE, -1); + EnableWindow(GetDlgItem(pane, ChatRemoveProfile), FALSE); + value(pane, ChatProfileStatus, v.chatKeys.empty() ? + L"Open a chat, then return to this page." : L"No matching chat selected."); return; } - const auto &draft = v->draft; - auto saved = draft.chatCycles.find(v->keys[index]); - const auto &cycle = saved == draft.chatCycles.end() ? draft.cycle : saved->second; - for (size_t i = 0; i < v->settings->order.size(); ++i) + const auto saved = v.draft.chatCycles.find(v.chatKeys[v.chatSelection]); + const bool hasProfile = saved != v.draft.chatCycles.end(); + const auto &cycle = hasProfile ? saved->second : v.draft.cycle; + for (size_t i = 0; i < v.order.size(); ++i) { - auto &layout = v->settings->app->layouts[v->settings->order[i]]; - SendDlgItemMessageW(w, 711, LB_SETSEL, - std::find(cycle.begin(), cycle.end(), layout.id) != cycle.end(), i); + const auto &layout = v.app->layouts[v.order[i]]; + SendDlgItemMessageW(pane, ChatLayouts, LB_SETSEL, std::ranges::find(cycle, layout.id) != cycle.end(), i); } - value(w, 712, saved == draft.chatCycles.end() ? L"No profile yet. Select the languages for this chat." : - L"Chat profile. Select languages, or remove it to use the defaults."); - EnableWindow(GetDlgItem(w, 713), saved != draft.chatCycles.end()); + value(pane, ChatProfileStatus, hasProfile ? L"Chat profile" : L"Using the default language cycle"); + EnableWindow(GetDlgItem(pane, ChatRemoveProfile), hasProfile); } -void selectChatRow(HWND list, int index) +void filterChatRows(SettingsView &v, const std::wstring &previous) { - int row = -1; - if (index >= 0) - { - LVFINDINFOW find{LVFI_PARAM}; - find.lParam = index; - row = ListView_FindItem(list, -1, &find); - } - ListView_SetItemState(list, -1, 0, LVIS_SELECTED | LVIS_FOCUSED); - if (row >= 0) - { - ListView_SetItemState(list, row, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); - ListView_EnsureVisible(list, row, FALSE); - } -} -void filterChatRows(HWND w, ChatLanguagesView *v) -{ - auto list = GetDlgItem(w, 710); - auto search = lower(v->search); - int selection = -1; - v->updatingList = true; + auto list = GetDlgItem(v.viewport, ChatContacts); + const auto search = lower(value(v.viewport, ChatSearch)); + int selectedRow = -1; + v.chatSelection = -1; + v.updatingChatContacts = true; SendMessageW(list, WM_SETREDRAW, FALSE, 0); ListView_DeleteAllItems(list); - for (size_t i = 0; i < v->keys.size(); ++i) + for (size_t i = 0; i < v.chatKeys.size(); ++i) { - const auto &key = v->keys[i]; + const auto &key = v.chatKeys[i]; auto contact = key.substr(key.find(L'\n') + 1); if (lower(contact).find(search) == std::wstring::npos) continue; auto app = key.starts_with(L"telegram\n") ? L"Telegram" : @@ -2358,153 +2328,99 @@ void filterChatRows(HWND w, ChatLanguagesView *v) item.iItem = ListView_GetItemCount(list); item.pszText = contact.data(); item.lParam = static_cast(i); - int row = ListView_InsertItem(list, &item); + const int row = ListView_InsertItem(list, &item); if (row < 0) continue; ListView_SetItemText(list, row, 1, const_cast(app)); - if (selection < 0 || static_cast(i) == v->selection) selection = static_cast(i); + if (selectedRow < 0 || key == previous) + { + selectedRow = row; + v.chatSelection = static_cast(i); + } + } + if (selectedRow >= 0) + { + ListView_SetItemState(list, selectedRow, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); + ListView_EnsureVisible(list, selectedRow, FALSE); } - selectChatRow(list, selection); SendMessageW(list, WM_SETREDRAW, TRUE, 0); InvalidateRect(list, nullptr, TRUE); - v->updatingList = false; - v->selection = selection; - fillChatLanguages(w, v); + v.updatingChatContacts = false; + fillChatLanguages(v); } -LRESULT CALLBACK chatLanguagesProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) +std::wstring selectedChatKey(const SettingsView &v) { - auto *v = (ChatLanguagesView *)GetWindowLongPtrW(w, GWLP_USERDATA); - if (!v) return DefWindowProcW(w, msg, wp, lp); - try - { - if (msg == WM_NOTIFY && !v->updatingList) - { - auto *change = reinterpret_cast(lp); - if (change->hdr.idFrom == 710 && change->hdr.code == LVN_ITEMCHANGED && - (change->uNewState & LVIS_SELECTED) && !(change->uOldState & LVIS_SELECTED)) - { - int selected = static_cast(change->lParam); - if (selected == v->selection) return 0; - try { collectChatLanguages(w, v); } - catch (...) - { - v->updatingList = true; - selectChatRow(change->hdr.hwndFrom, v->selection); - v->updatingList = false; - throw; - } - v->selection = selected; - fillChatLanguages(w, v); - return 0; - } - } - if (msg == WM_COMMAND) - { - int id = LOWORD(wp); - if (id == 711 && HIWORD(wp) == LBN_SELCHANGE) { v->dirty = true; return 0; } - if (id == 714 && HIWORD(wp) == EN_CHANGE && !v->updatingList) - { - try { collectChatLanguages(w, v); } - catch (...) - { - v->updatingList = true; - value(w, 714, v->search); - v->updatingList = false; - throw; - } - v->search = value(w, 714); - filterChatRows(w, v); - return 0; - } - if (id == IDOK || id == 713) - { - int selected = v->selection; - if (id == IDOK && selected < 0) return 0; - if (selected < 0 || selected >= (int)v->keys.size()) - throw std::runtime_error("Open a Telegram or Teams chat, then reopen this dialog."); - if (id == 713) - { - v->draft.chatCycles.erase(v->keys[selected]); - v->dirty = false; - fillChatLanguages(w, v); - return 0; - } - collectChatLanguages(w, v); - validateSettings(v->draft); - v->settings->draft.chatCycles = std::move(v->draft.chatCycles); - DestroyWindow(w); - return 0; - } - if (id == IDCANCEL) { DestroyWindow(w); return 0; } - } - if (msg == WM_CLOSE) { DestroyWindow(w); return 0; } - if (msg == WM_DPICHANGED) - { - resizeForDpi(w, wp, lp); - auto list = GetDlgItem(w, 710); - ListView_SetColumnWidth(list, 0, scale(w, 442)); - ListView_SetColumnWidth(list, 1, scale(w, 140)); - return 0; - } - if (msg == WM_NCDESTROY) - { - EnableWindow(v->parent, TRUE); - SetForegroundWindow(v->parent); - disposeFont(w); - delete v; - SetWindowLongPtrW(w, GWLP_USERDATA, 0); - } - } - catch (const std::exception &e) { error(w, e); } - return DefWindowProcW(w, msg, wp, lp); + return v.chatSelection < 0 ? std::wstring{} : v.chatKeys[v.chatSelection]; } -void showChatLanguages(HWND parent, SettingsView *settings) +void refreshChatLanguages(SettingsView &v) { + const auto previous = selectedChatKey(v); std::set keys; - for (const auto &[key, cycle] : settings->draft.chatCycles) keys.insert(key); - struct Context { std::set &keys; const Settings &settings; } context{keys, settings->draft}; + for (const auto &[key, cycle] : v.draft.chatCycles) keys.insert(key); EnumWindows([](HWND candidate, LPARAM context) -> BOOL { if (!IsWindowVisible(candidate)) return TRUE; - auto &data = *(Context *)context; + auto &contacts = *reinterpret_cast *>(context); auto key = lower(processName(candidate)) == L"chrome" ? readChromeChat(candidate) : windowChatKey(candidate); - if (!key.empty()) data.keys.insert(std::move(key)); + if (!key.empty()) contacts.insert(std::move(key)); return TRUE; - }, (LPARAM)&context); + }, reinterpret_cast(&keys)); + v.chatKeys.assign(keys.begin(), keys.end()); + SendDlgItemMessageW(v.viewport, ChatLayouts, LB_RESETCONTENT, 0, 0); + for (int index : v.order) + SendDlgItemMessageW(v.viewport, ChatLayouts, LB_ADDSTRING, 0, + reinterpret_cast(v.app->layouts[index].name.c_str())); + filterChatRows(v, previous); +} +void editChatLanguages(SettingsView &v) +{ + if (v.chatSelection < 0) return; + std::vector cycle; + for (size_t i = 0; i < v.order.size(); ++i) + if (SendDlgItemMessageW(v.viewport, ChatLayouts, LB_GETSEL, i, 0) > 0) + cycle.push_back(v.app->layouts[v.order[i]].id); + const bool hasLayouts = !cycle.empty(); + if (hasLayouts) v.draft.chatCycles[v.chatKeys[v.chatSelection]] = std::move(cycle); + fillChatLanguages(v); + if (!hasLayouts) value(v.viewport, ChatProfileStatus, L"Select at least one layout, or remove the profile."); +} +void sizeChatContactColumns(HWND list) +{ + RECT bounds{}; + GetClientRect(list, &bounds); + const int appWidth = scale(list, 140); + const int scrollWidth = GetSystemMetricsForDpi(SM_CXVSCROLL, GetDpiForWindow(list)); + ListView_SetColumnWidth(list, 0, std::max(0L, bounds.right - appWidth - scrollWidth)); + ListView_SetColumnWidth(list, 1, appWidth); +} +LRESULT CALLBACK chatContactsProc(HWND list, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR) +{ + const auto result = DefSubclassProc(list, msg, wp, lp); + if (msg == WM_SIZE) sizeChatContactColumns(list); + return result; +} +void createChatLanguages(HWND pane) +{ INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES}; InitCommonControlsEx(&controls); - HWND w = makeWindow(*settings->app, L"KSwitcher.ChatLanguages", L"Languages for a chat", chatLanguagesProc, 640, 524); - auto *v = new ChatLanguagesView{parent, settings, {keys.begin(), keys.end()}}; - v->draft = settings->draft; - v->updatingList = true; - SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent); - SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v); - label(w, L"&Find contact", 18, 19, 106); - edit(w, 714, 130, 14, 492); - auto list = control(w, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SINGLESEL | - LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, 710, 18, 48, 604, 136); + label(pane, L"&Find contact", 24, 68, 660); + edit(pane, ChatSearch, 24, 94, 660); + const auto list = control(pane, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SINGLESEL | + LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, ChatContacts, 24, 126, 660, 106); ListView_SetExtendedListViewStyle(list, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | LVS_EX_LABELTIP); - for (const auto &[title, width] : {std::pair{L"Contact", 442}, std::pair{L"App", 140}}) + for (const auto *title : {L"Contact", L"App"}) { - LVCOLUMNW column{LVCF_TEXT | LVCF_WIDTH}; + LVCOLUMNW column{LVCF_TEXT}; column.pszText = const_cast(title); - column.cx = scale(w, width); ListView_InsertColumn(list, Header_GetItemCount(ListView_GetHeader(list)), &column); } - control(w, L"STATIC", L"Open a chat, then reopen this dialog to add it.", 0, 712, 18, 194, 604, 26); - label(w, L"Click languages to include (saved in the order shown)", 18, 228, 604); - control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_MULTIPLESEL | LBS_NOINTEGRALHEIGHT | WS_BORDER, - 711, 18, 256, 604, 132); - for (int i : settings->order) - SendDlgItemMessageW(w, 711, LB_ADDSTRING, 0, (LPARAM)settings->app->layouts[i].name.c_str()); - label(w, L"Applies to Alt+Shift, Win+Space and KSwitcher Next layout.", 18, 402, 604); - label(w, L"Switch chats freely. Use languages, then Save settings.", 18, 430, 604); - button(w, L"&Remove profile", 713, 18, 476, 170); - button(w, L"&Use languages", IDOK, 300, 476, 170); - button(w, L"&Cancel", IDCANCEL, 486, 476, 136); - filterChatRows(w, v); - EnableWindow(parent, FALSE); - showRequestedWindow(w); - SetFocus(GetDlgItem(w, 714)); + SetWindowSubclass(list, chatContactsProc, 1, 0); + sizeChatContactColumns(list); + control(pane, L"STATIC", L"", 0, ChatProfileStatus, 24, 242, 660, 24); + label(pane, L"Select layouts to include, in the order shown.", 24, 270, 660); + control(pane, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_MULTIPLESEL | LBS_NOINTEGRALHEIGHT | + WS_BORDER, ChatLayouts, 24, 296, 660, 80); + button(pane, L"&Remove profile", ChatRemoveProfile, 24, 388, 170); + label(pane, L"Applies to Alt+Shift, Win+Space, Win+Shift+Space and KSwitcher Next layout.", 24, 424, 660); } #include "ui_app_languages.inl" #include "ui_mouse_buttons.inl" @@ -2647,6 +2563,7 @@ void fillSettings(HWND root, SettingsView *v) v->order.push_back(i); v->selection = 0; fillLayouts(v); + if (v->selectedPage == ChatLanguagesPage) refreshChatLanguages(*v); fillMouseProfiles(root, *v); fillCorrectionOptions(w, s); v->filling = false; @@ -3057,6 +2974,20 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) if (LOWORD(wp) != WA_INACTIVE) updateSettingsState(w, v); break; case WM_NOTIFY: + if (reinterpret_cast(lp)->idFrom == ChatContacts && + reinterpret_cast(lp)->code == LVN_ITEMCHANGED) + { + const auto &change = *reinterpret_cast(lp); + if (!v->updatingChatContacts && ((change.uNewState ^ change.uOldState) & LVIS_SELECTED)) + { + if (change.uNewState & LVIS_SELECTED) + v->chatSelection = static_cast(change.lParam); + else if (!ListView_GetSelectedCount(change.hdr.hwndFrom)) + v->chatSelection = -1; + fillChatLanguages(*v); + } + return 0; + } if (reinterpret_cast(lp)->idFrom == SettingsNavigation) { const auto code = reinterpret_cast(lp)->code; @@ -3189,7 +3120,25 @@ LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp) } if (id == 263) { collectLayout(v); showAppLanguages(w, v); return 0; } if (handleMouseBindings(w, *v, wp)) return 0; - if (id == 259) { collectLayout(v); showChatLanguages(w, v); return 0; } + if (id == ChatSearch && HIWORD(wp) == EN_CHANGE) + { + if (v->ready) filterChatRows(*v, selectedChatKey(*v)); + return 0; + } + if (id == ChatLayouts && HIWORD(wp) == LBN_SELCHANGE) + { + editChatLanguages(*v); + return 0; + } + if (id == ChatRemoveProfile && HIWORD(wp) == BN_CLICKED) + { + if (v->chatSelection >= 0) + { + v->draft.chatCycles.erase(v->chatKeys[v->chatSelection]); + fillChatLanguages(*v); + } + return 0; + } if (id == 230) { collectLayout(v); @@ -3985,8 +3934,7 @@ void showSettings(App &app, bool visible) hotkeyEdit(app, pane, 231, 454, 234, 230); label(pane, L"Backspace / Delete clears it", 454, 270, 230); button(pane, L"Re&fresh layouts", 253, 454, 322, 230); - button(pane, L"Languages for a &chat...", 259, 24, 378, 230); - button(pane, L"Languages for &applications...", 263, 272, 378, 300); + button(pane, L"Languages for &applications...", 263, 24, 378, 300); page(); settingsGroupLabel(pane, L"Keyboard shortcuts", 24, 68); @@ -4111,6 +4059,9 @@ void showSettings(App &app, bool visible) createOcrSettings(pane); page(); + createChatLanguages(pane); + page(); + v->splitter = control(w, L"STATIC", L"Resize navigation pane", SS_NOTIFY | WS_TABSTOP, SettingsSplitter, 0, 0, 0, 0); SetWindowSubclass(v->splitter, settingsSplitterProc, 1, reinterpret_cast(v)); diff --git a/tests/chat_profiles.cpp b/tests/chat_profiles.cpp index a86acad..050e8cf 100644 --- a/tests/chat_profiles.cpp +++ b/tests/chat_profiles.cpp @@ -854,13 +854,16 @@ int main(int argc,char **argv) SendMessageW(GetDlgItem(correction, 414), BM_CLICK, 0, 0); require(!saveEnabled(), "reverting an inline correction edit disables Save"); HWND navigation = settingsNavigation(parent); - constexpr int sections = 20; + constexpr int chatLanguagesPage = 20; + constexpr int sections = 21; require(navigation && TreeView_GetCount(navigation) == sections && TreeView_GetParent(navigation, settingsSection(navigation, 10)) == settingsSection(navigation, 7) && TreeView_GetParent(navigation, settingsSection(navigation, 11)) == settingsSection(navigation, 0), "correction and computer settings are nested under their sections"); require(TreeView_GetParent(navigation, settingsSection(navigation, 19)) == settingsSection(navigation, 3), "image text recognition is nested under Clipboard"); + require(TreeView_GetParent(navigation, settingsSection(navigation, chatLanguagesPage)) == + settingsSection(navigation, 1), "chat profiles appear under Languages"); for (int section = 12; section <= 16; ++section) require(TreeView_GetParent(navigation, settingsSection(navigation, section)) == settingsSection(navigation, 11), "each correction subsection belongs to the correction branch"); @@ -1124,44 +1127,51 @@ int main(int argc,char **argv) "search reveals the embedded OpenBao page"); SetWindowTextW(search, L""); selectSettingsPage(parent, 1); - require(!saveEnabled(),"changing sections leaves Settings clean"); - SendMessageW(parent, WM_COMMAND, 259, 0); - HWND dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr); - require(dialog && !IsWindowEnabled(parent), "chat dialog opens with disabled parent"); - auto findFixtureChat = [&](HWND chatDialog) { - SetDlgItemTextW(chatDialog, 714, L"! fIXTURE CHAT"); - HWND list = GetDlgItem(chatDialog, 710); + require(!saveEnabled() && !GetDlgItem(pane, 259), "Languages uses the tree to open chat profiles"); + selectSettingsPage(parent, chatLanguagesPage); + constexpr int contactsId = 710, layoutsId = 711, removeProfileId = 713, searchContactsId = 714; + require(IsWindowVisible(GetDlgItem(pane, contactsId)) && IsWindowEnabled(parent) && + !findTestWindow(L"KSwitcher.ChatLanguages", nullptr), "chat profiles open within Settings"); + auto findFixtureChat = [&] { + const auto chatPage = settingsViewport(parent); + SetDlgItemTextW(chatPage, searchContactsId, L"! fIXTURE CHAT"); + const auto list = GetDlgItem(chatPage, contactsId); require(ListView_GetItemCount(list) == 1, "case-insensitive contact search finds saved chat"); wchar_t appName[32]{}; ListView_GetItemText(list, 0, 1, appName, std::size(appName)); require(std::wstring(appName) == L"Telegram", "chat list shows the source app separately"); }; - SetDlgItemTextW(dialog, 714, L"No matching fixture 8031"); - require(ListView_GetItemCount(GetDlgItem(dialog, 710)) == 0 && - !IsWindowEnabled(GetDlgItem(dialog, IDOK)), "empty search results disable profile actions"); - findFixtureChat(dialog); - require(SendDlgItemMessageW(dialog, 711, LB_GETSELCOUNT, 0, 0) == 1, "saved single language selected"); - RedrawWindow(dialog, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN); - RECT rect{}; GetClientRect(dialog, &rect); - HDC dc = GetDC(dialog); + auto selectChatLayouts = [&](bool select) { + const auto chatPage = settingsViewport(parent); + SendDlgItemMessageW(chatPage, layoutsId, LB_SETSEL, select, -1); + SendMessageW(chatPage, WM_COMMAND, MAKEWPARAM(layoutsId, LBN_SELCHANGE), 0); + }; + SetDlgItemTextW(pane, searchContactsId, L"No matching fixture 8031"); + require(ListView_GetItemCount(GetDlgItem(pane, contactsId)) == 0 && + !IsWindowEnabled(GetDlgItem(pane, layoutsId)) && + !IsWindowEnabled(GetDlgItem(pane, removeProfileId)), "empty search disables profile editing"); + findFixtureChat(); + require(SendDlgItemMessageW(pane, layoutsId, LB_GETSELCOUNT, 0, 0) == 1, "saved single language selected"); + selectChatLayouts(false); + require(SendDlgItemMessageW(pane, layoutsId, LB_GETSELCOUNT, 0, 0) == 1 && !saveEnabled(), + "deselecting the last layout keeps the profile"); + findFixtureChat(); + RedrawWindow(parent, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN); + RECT rect{}; + GetClientRect(parent, &rect); + HDC dc = GetDC(parent); auto clip = ks::screenshotClip(dc, rect.right, rect.bottom, {}); - ReleaseDC(dialog, dc); + ReleaseDC(parent, dc); ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"chat-languages.png", ks::encodePng(ks::decodeImage(clip))); - SendDlgItemMessageW(dialog, 711, LB_SETSEL, TRUE, -1); - SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(711, LBN_SELCHANGE), 0); - SendMessageW(dialog, WM_COMMAND, IDCANCEL, 0); - require(!IsWindow(dialog) && IsWindowEnabled(parent), "cancel closes dialog"); - require(!saveEnabled(),"cancelled chat edits do not enable Save"); - SendMessageW(parent, WM_COMMAND, 259, 0); - dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr); - findFixtureChat(dialog); - require(SendDlgItemMessageW(dialog, 711, LB_GETSELCOUNT, 0, 0) == 1, "cancel discards language edits"); - SendDlgItemMessageW(dialog, 711, LB_SETSEL, TRUE, -1); - SendMessageW(dialog, WM_COMMAND, MAKEWPARAM(711, LBN_SELCHANGE), 0); - SendMessageW(dialog, WM_COMMAND, IDOK, 0); - require(!IsWindow(dialog) && IsWindowEnabled(parent), "profile applies to settings draft"); - require(saveEnabled() == (app.layouts.size()>1),"accepted chat edits refresh Save immediately"); + selectChatLayouts(true); + require(saveEnabled() == (app.layouts.size() > 1) && saveEnabled() == applyEnabled(), + "editing a profile immediately refreshes Apply and Save"); + require(app.settings.chatCycles.at(key).size() == 1, "inline editing leaves saved settings untouched"); + selectSettingsPage(parent, 1); + selectSettingsPage(parent, chatLanguagesPage); + require(SendDlgItemMessageW(pane, layoutsId, LB_GETSELCOUNT, 0, 0) == static_cast(app.layouts.size()), + "profile edits survive navigating away and returning"); selectSettingsPage(parent, 16); SetDlgItemTextW(correction, 412, L"Релізик\r\nрелізик, словечко"); SetDlgItemTextW(correction, 416, L" HeLo = Hello\r\n"); @@ -1174,26 +1184,33 @@ int main(int argc,char **argv) ks::showSettings(app); parent = app.settingsWindow; require(!saveEnabled(),"reopened saved Settings is clean"); - SendMessageW(parent, WM_COMMAND, 259, 0); - dialog = findTestWindow(L"KSwitcher.ChatLanguages", nullptr); - findFixtureChat(dialog); - SendMessageW(dialog, WM_COMMAND, 713, 0); - require(IsWindow(dialog), "chat reset keeps dialog open"); - SendMessageW(dialog, WM_COMMAND, IDOK, 0); - require(saveEnabled() && status().find(L"Unsaved settings")==0,"removing child profile immediately marks parent dirty"); - RedrawWindow(parent,nullptr,nullptr,RDW_INVALIDATE|RDW_UPDATENOW|RDW_ALLCHILDREN); - GetClientRect(parent,&rect); dc=GetDC(parent); - clip=ks::screenshotClip(dc,rect.right,rect.bottom,{}); ReleaseDC(parent,dc); - ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path()/L"settings-unsaved.png", + selectSettingsPage(parent, chatLanguagesPage); + findFixtureChat(); + const auto chatPage = settingsViewport(parent); + require(SendDlgItemMessageW(chatPage, layoutsId, LB_GETSELCOUNT, 0, 0) == + static_cast(app.layouts.size()), "reopening shows the saved profile"); + SendMessageW(GetDlgItem(chatPage, removeProfileId), BM_CLICK, 0, 0); + require(saveEnabled() && applyEnabled() && status().starts_with(L"Unsaved settings"), + "removing a profile immediately marks Settings dirty"); + RedrawWindow(parent, nullptr, nullptr, RDW_INVALIDATE | RDW_UPDATENOW | RDW_ALLCHILDREN); + GetClientRect(parent, &rect); + dc = GetDC(parent); + clip = ks::screenshotClip(dc, rect.right, rect.bottom, {}); + ReleaseDC(parent, dc); + ks::atomicWrite(std::filesystem::path(ks::executable()).parent_path() / L"settings-unsaved.png", ks::encodePng(ks::decodeImage(clip))); - SendMessageW(parent, WM_COMMAND, IDOK, 0); - require(!app.settings.chatCycles.contains(key), "remove profile restores default"); + SendMessageW(parent, WM_COMMAND, SettingsApply, 0); + require(IsWindow(parent) && !saveEnabled() && !applyEnabled() && + !app.settings.chatCycles.contains(key) && + !ks::loadSettings(root / L"settings.json", app.layouts).chatCycles.contains(key), + "Apply restores the default, saves the removal and keeps Settings open"); + SendMessageW(parent, WM_COMMAND, IDCANCEL, 0); // Existing shared sets become independent application drafts on edit. app.settings.appLanguageSets[L"Legacy shared"] = {{app.layouts[0].id}, {L"Codex.exe", L"notepad"}}; ks::showSettings(app); parent = app.settingsWindow; SendMessageW(parent, WM_COMMAND, 263, 0); - dialog = findTestWindow(L"KSwitcher.AppLanguages", nullptr); + HWND dialog = findTestWindow(L"KSwitcher.AppLanguages", nullptr); require(dialog && !IsWindowEnabled(parent), "application language editor opens"); auto selectApp = [&](const wchar_t *name) { int index = (int)SendDlgItemMessageW(dialog, 720, LB_FINDSTRINGEXACT, -1, (LPARAM)name); From 85cdce1b01f95d844f0ecda001604a5adfabd03f Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Fri, 27 Nov 2026 09:57:45 +0200 Subject: [PATCH 60/61] Allow trusted LAN clients to resolve transfer conflicts Refs #122 --- LAN-PREVIEW.md | 12 ++++++++++-- src/lan_client_files.cpp | 30 +++++++++++++++++++++++++----- tests/lan_clients.cpp | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 71 insertions(+), 7 deletions(-) diff --git a/LAN-PREVIEW.md b/LAN-PREVIEW.md index 872d51f..c15d5f1 100644 --- a/LAN-PREVIEW.md +++ b/LAN-PREVIEW.md @@ -35,7 +35,8 @@ retain their original reply formats. - `capabilities` optionally takes a `peer`. It returns the broker `protocol` (2), `hostRevision`, and boolean `write`, `delete`, `move`, - `revisionRead`, `onHostTransfer`, and `localEndpoint` fields. With no peer, + `revisionRead`, `onHostTransfer`, `localEndpoint`, and optional + `conflictPrompt` fields. With no peer, the fields describe the local broker and its grants. With a peer, the flags also account for its supported protocol. A peer with revision 0 still supports legacy browsing and downloading. @@ -57,7 +58,8 @@ retain their original reply formats. The recycle bin is subject to Windows availability on the paired host. - `transfer` takes `source` and `target` objects with a `peer` and `path` each, optional `move` (default false), and a `conflict` policy of `fail` - (default), `skip`, or `replace`. Replace merges directories and replaces + (default), `skip`, `replace`, or `ask` when `conflictPrompt` is available. + Replace merges directories and replaces regular files after validating the destination revision. The broker allows at most one local endpoint, represented by `"peer": null`. For a local endpoint the client must open the pipe with Windows impersonation @@ -69,6 +71,12 @@ retain their original reply formats. final frame has `type: "complete"` and counts, or an error. Transfers on one paired computer use its own file service even across drives. The local pipe exchanges only control and status for transfers. +- Ask merges directories and reports individual collisions in a JSON frame + with `type: "conflict"`, target `path`, `incoming` and `existing` metadata + (as in `stat`), and boolean `replaceable`. Respond with a JSON frame + containing `decision: "replace"`, `"skip"`, or `"cancel"`. Send + `decision: "wait"` at least once every five seconds while a prompt is open. + Access is checked again after each reply and before publishing the file. - For a move, the copy phase finishes before source deletion begins. Skipped items remain at the source. Cancellation or failure can leave previously completed destination items. Failure during source cleanup diff --git a/src/lan_client_files.cpp b/src/lan_client_files.cpp index 41d5c46..a486da6 100644 --- a/src/lan_client_files.cpp +++ b/src/lan_client_files.cpp @@ -48,7 +48,8 @@ Json capabilities(bool write, bool erase, unsigned host) { return {{"protocol", 2}, {"hostRevision", host}, {"write", write && host}, {"delete", erase && host}, {"move", write && erase && host}, - {"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0}}; + {"revisionRead", host != 0}, {"onHostTransfer", host != 0}, {"localEndpoint", host != 0}, + {"conflictPrompt", host != 0}}; } fs::path itemPath(const Json &value) { @@ -128,6 +129,27 @@ class ClientTransfer if (!result.at("continue").get()) throw std::system_error(ERROR_CANCELLED, std::system_category()); guard(); } + bool resolveConflict(const fs::path &path, const Json &incoming, const Json &existing) + { + if (conflict == "skip") return false; + const bool replaceable = directory(incoming) == directory(existing) && !reparse(existing); + if (conflict == "replace" && replaceable) return true; + if (conflict != "ask") throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category()); + if (replaceable && directory(existing)) return true; + + sendJson(send, {{"type", "conflict"}, {"path", utf8(path.native())}, + {"incoming", incoming}, {"existing", existing}, {"replaceable", replaceable}}); + for (;;) + { + const auto answer = Json::parse(receive(256)).at("decision").get(); + guard(); + if (answer == "wait") continue; + if (answer == "skip") return false; + if (answer == "replace" && replaceable) return true; + if (answer == "cancel") throw std::system_error(ERROR_CANCELLED, std::system_category()); + throw std::runtime_error("Invalid transfer conflict decision."); + } + } bool copy(const fs::path &from, const fs::path &to, unsigned depth) { if (depth > 256) throw std::runtime_error("The file tree is too deep."); @@ -139,9 +161,7 @@ class ClientTransfer if (found) { checkFileReply(existing); - if (conflict == "skip") { ++skipped; return false; } - if (conflict != "replace" || directory(original) != directory(existing)) - throw std::system_error(ERROR_ALREADY_EXISTS, std::system_category()); + if (!resolveConflict(to, original, existing)) { ++skipped; return false; } requireRegular(existing); } @@ -199,7 +219,7 @@ public: void run(const fs::path &from, const fs::path &to) { - if (conflict != "fail" && conflict != "skip" && conflict != "replace") + if (conflict != "fail" && conflict != "skip" && conflict != "replace" && conflict != "ask") throw std::runtime_error("Unknown conflict policy."); if (sameHost) { diff --git a/tests/lan_clients.cpp b/tests/lan_clients.cpp index 429735f..a999fb1 100644 --- a/tests/lan_clients.cpp +++ b/tests/lan_clients.cpp @@ -228,6 +228,42 @@ void verifyFiles(LanClients &clients, const Json &trusted, const std::wstring &p require(runTransfer(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "replace")).at("type") == "complete" && read(to / L"content.txt") == content, "replace conflict policy failed"); + const auto ask = [&](const char *decision, bool replaceable) { + Pipe client(pipe, transfer(endpoint(a, src), endpoint(b, to), false, "ask")); + unsigned prompts = 0; + for (;;) + { + auto result = client.reply(); + const auto type = result.value("type", ""); + if (type == "progress") client.sendJson({{"continue", true}}); + else if (type == "conflict") + { + ++prompts; + require(result.at("path") == utf8((to / L"content.txt").native()) && + result.at("replaceable") == replaceable && + result.at("incoming").at("size") == content.size(), "incorrect conflict prompt"); + client.sendJson({{"decision", "wait"}}); + client.sendJson({{"decision", decision}}); + } + else + { + client.ack(); + require(prompts == 1, "ask did not report the nested collision exactly once"); + return result; + } + } + }; + save(to / L"content.txt", "keep me"); + require(ask("skip", true).at("skipped") == 1 && read(to / L"content.txt") == "keep me", + "skipping a prompted collision changed its destination"); + require(ask("replace", true).at("type") == "complete" && read(to / L"content.txt") == content, + "confirming a prompted collision did not replace its destination"); + fs::remove(to / L"content.txt"); + fs::create_directory(to / L"content.txt"); + require(ask("replace", false).contains("error") && fs::is_directory(to / L"content.txt"), + "a prompted type mismatch allowed replacement"); + fs::remove(to / L"content.txt"); + const auto localCopy = root / L"local.txt"; const auto fromLocal = transfer(endpoint(nullptr, file), endpoint(b, dst / L"from-local.txt"), false); require(runTransfer(pipe, fromLocal).contains("error"), "identification-only pipe accessed local files"); From 47e10477e185cab81379f8bf1d5ad70aca8ec8cc Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Fri, 27 Nov 2026 10:53:35 +0200 Subject: [PATCH 61/61] Prepare KSwitcher v0.8.4 for stable delivery Refs #204 Refs #122 Refs #196 --- CMakeLists.txt | 2 +- Release/README.md | 10 +++++ Release/SHA256SUMS.txt | 2 +- Release/release-files.json | 84 +++++++++++++++++++------------------- resources/app.rc | 6 +-- src/update.h | 2 +- tests/input.cpp | 2 +- tests/input_pause.cpp | 7 ++-- 8 files changed, 63 insertions(+), 52 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2d84959..490def2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.24) -project(KSwitcher VERSION 0.8.3 LANGUAGES C CXX RC) +project(KSwitcher VERSION 0.8.4 LANGUAGES C CXX RC) if(NOT WIN32) message(FATAL_ERROR "KSwitcher uses native Windows APIs") endif() diff --git a/Release/README.md b/Release/README.md index 41d5f90..616fed5 100644 --- a/Release/README.md +++ b/Release/README.md @@ -1,5 +1,15 @@ # Latest Windows release +## v0.8.4 — 2026-11-27 + +- **Settings.** Open **Languages → Languages for a chat** in the Settings tree to search for a chat and choose its keyboard layouts. Save changes with **Apply** or **Save**. +- **Trusted LAN clients.** Clients such as Dirlume can ask how to handle individual file conflicts during copy or move. When supported, choose to replace, skip or cancel. + +**Українською.** + +- **Налаштування.** Відкрийте **Languages → Languages for a chat** у дереві Settings, щоб знайти чат і вибрати його розкладки. Застосуйте зміни кнопкою **Apply** або **Save**. +- **Довірені клієнти LAN.** Клієнти на кшталт Dirlume можуть запитувати, як обробити окремі конфлікти файлів під час копіювання або переміщення. Якщо клієнт підтримує цю можливість, виберіть заміну, пропуск або скасування. + ## v0.8.3 — 2026-11-26 - **Files.** Lavender now shows compact path segments with chevrons above both panes. The current folder has a rounded highlight. Click an ancestor to open it, the current folder to edit the path, or an ellipsis to reveal hidden folders. diff --git a/Release/SHA256SUMS.txt b/Release/SHA256SUMS.txt index 280a319..ee78403 100644 --- a/Release/SHA256SUMS.txt +++ b/Release/SHA256SUMS.txt @@ -1 +1 @@ -0726c819b43cd1508c4fa22b717ab13b0da826f5a48bbc3a4b0f10e6418d207a KSwitcher-win-x64.zip +9035578c4aa96533a78dd1830966cf0b2f8d9de623f51ec2d111e62249d1c65d KSwitcher-win-x64.zip diff --git a/Release/release-files.json b/Release/release-files.json index b91d925..1fc972c 100644 --- a/Release/release-files.json +++ b/Release/release-files.json @@ -1,181 +1,181 @@ { - "version": "0.8.3", "schema": 1, "files": [ { - "sha256": "134aff7d86cdba13eecf9e32a0556e0267c0900800bd6dc1e9b005729190eb7a", "path": "KSwitcher.exe", - "size": 3247616 + "sha256": "a7ad4db3cb46825c65b851c7e4cbd214f779eb5325a91ca7cdb96a3fe944d8a4", + "size": 3251712 }, { - "sha256": "7f90f6af18c9ac7f9e0f8255bfd339c49c9ea28e2da88d6b6e3443f6a867a1dd", "path": "KSwitcher.Config.exe", - "size": 2849792 + "sha256": "c9d2dddc6e2a5e14be02680c1177e4813515e207bada399f255fcbf4aef5e884", + "size": 2850304 }, { - "sha256": "f010f82aba8ace45abf0b90db991804964c1ec18f783a4169add56f478c96344", "path": "KSwitcher.Screenshot.exe", + "sha256": "1112fd25921d49ef20b3f71b0b8234eea3e9df47b1c1d207bfa22a9f7da34028", "size": 3193344 }, { - "sha256": "caa66e3d8cddd094f1de317fb1a6410d4413f30034cdb61f130d7fcee21004bb", "path": "KSwitcher.Files.exe", - "size": 6000640 + "sha256": "b2843967c9b70839e45ec3b8b48bffde41ff8994ea345317beb1bda28e6d6dff", + "size": 6002688 }, { - "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6", "path": "WebView2Loader.dll", + "sha256": "d3fce90bdeecb08596e377dea6a316354dd8949e32ff09b89d51be00c14e21b6", "size": 194912 }, { - "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f", "path": "terminal/addon-fit-LICENSE.txt", + "sha256": "e256f01188af527e4d06d21d06fbf785ae9c50d4b328bf03cbe0ba7f0aa4228f", "size": 1103 }, { - "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527", "path": "terminal/addon-fit.js", + "sha256": "ba3ea256ce0620a0992a197d6c9baea64823fc93d8da07a9e366ca9943c18527", "size": 1521 }, { - "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef", "path": "terminal/index.html", + "sha256": "084d97a727b778fb10d31adcd557ee7840a38377ed60e0ef0f3ece93b349b1ef", "size": 527 }, { - "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473", "path": "terminal/markdown-it-LICENSE.txt", + "sha256": "792c48c5a849a15fdf9e37e8bcf9e6d1dd13b32b46c642a748a0a46a9919d473", "size": 1073 }, { - "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e", "path": "terminal/markdown-it.js", + "sha256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e", "size": 100786 }, { - "sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2", "path": "terminal/markdown.html", + "sha256": "98984c8f76bd231dab00ef54034bfc2f29b365ee0b31c05edb16ad5216bd5bc2", "size": 3800 }, { - "sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96", "path": "terminal/markdown.js", + "sha256": "8b5429a035ce8ce11f77a222b5ee946844fd1e2999e1bb5c8f7c030ddbb1ff96", "size": 18721 }, { - "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80", "path": "terminal/mermaid-LICENSE.txt", + "sha256": "ec9fb67dcb25eccc416ed56e1aab819222c805a2a4bfe4cb19e7556bf2ffde80", "size": 1089 }, { - "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3", "path": "terminal/mermaid.js", + "sha256": "336df803d87a38b70a01e736e666c8f7601d2ce42f5e47c8fafe5d721074b9a3", "size": 5537838 }, { - "sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7", "path": "terminal/terminal.js", + "sha256": "838707e2813f7d007f7f60670a78ae4a4a6c97ca9a235d623cb85e16dc50e0c7", "size": 6627 }, { - "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd", "path": "terminal/xterm-LICENSE.txt", + "sha256": "b569f629d00f2626a8100df2a1798210535621e42164dfd426a6fe5aac7b0ccd", "size": 1261 }, { - "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6", "path": "terminal/xterm.css", + "sha256": "854a7c0fb70e8b1a083c16797ab827299fb18744f5ad34f227b48337e33293c6", "size": 7112 }, { - "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972", "path": "terminal/xterm.js", + "sha256": "14903579ff54664cd72f8e8699e6961a6272c21863ec1c3b118cdc8af5d4a972", "size": 488663 }, { - "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c", "path": "LICENSE", + "sha256": "d3c81140cce01c26bf6cbf52aa40e0825e1fa35b9a91d1387170a65d2597082c", "size": 4401 }, { - "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831", "path": "json-LICENSE.txt", + "sha256": "61e08da79c44061654015ce6b0c4061c23ee1dd18237fbf09e9bfda3c0ea2831", "size": 1096 }, { - "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625", "path": "files-text-license.txt", + "sha256": "185c5a37521316e940ead89cbf0b1ba5862d810c7c966e6c6a14a4a515b23625", "size": 883 }, { - "sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d", "path": "files-archive-license.txt", + "sha256": "57d6d9b1f85ac93b3bc73f6f7bdf4346e896c4644d6fa461c380ae29070c029d", "size": 4990 }, { - "sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4", "path": "files-image-license.txt", + "sha256": "7997c62a2f766674ceb99976485a6cf5c772309e79101a400c421d526b82f6e4", "size": 3044 }, { - "sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594", "path": "files-sftp-license.txt", + "sha256": "19c254c71ee49aefbd8854ac55b05d719c5f1e4f8ef9a982324b898501b39594", "size": 2064 }, { - "sha256": "be1b3fca2a291284ab550e9e77042fb27ecf927861d2d8fb8ec4907258477f01", "path": "README.md", - "size": 105515 + "sha256": "7f179b561fab6125f167203a6ae180a7050d876b056c39f62f3be36cf4bad733", + "size": 105904 }, { - "sha256": "917c2f41b3943647fdfafa911d93f72b8c6fb0d08592016ce1a698d256e038bb", "path": "LAN-PREVIEW.md", - "size": 16722 + "sha256": "4eac1f410e6b544aa45756e24f4fdfe9193c6f732410656160be54ab27a0d7e4", + "size": 17245 }, { - "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9", "path": "dictionaries/en.txt", + "sha256": "d0c022b27b9fbc2ff7b6b8bec723cc1adc4eef517202f9ff77eed5d8bea3acb9", "size": 732485 }, { - "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5", "path": "dictionaries/LICENSE-CC-BY-SA-4.0.txt", + "sha256": "0bdfb0201d1803634f268cdff0993b8349d2c70e956a06dbb667c8dd65254ec5", "size": 20566 }, { - "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311", "path": "dictionaries/README.md", + "sha256": "3017bf44d3be9d9dfab21bd6778aa52b7947e61acf9ce2bc86b41d6e949ac311", "size": 2265 }, { - "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849", "path": "dictionaries/ru.txt", + "sha256": "80e6b6a27815973535f7facb636c597eb845dfee45cfabfc4e9b3341b9332849", "size": 1109134 }, { - "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408", "path": "dictionaries/sources.json", + "sha256": "98e5b3fe7304e37705c9e5ff48b0b399ccb16e806736d21f09921b99e5f2a408", "size": 1280 }, { - "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf", "path": "dictionaries/uk.txt", + "sha256": "d30e990d6ec2983c04f3644a3c61c6c668e8c542323f5931916fdd55b916eebf", "size": 940799 }, { - "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a", "path": "tools/README.txt", + "sha256": "a34b5161a8315af037e1ec71d816bfc688f7c364141d4ee2347cf0515ef0c82a", "size": 993 }, { - "sha256": "b6a36bcdc26fc6bb55083e023e2fafb60236e541e9b1b7e598c66816a3089175", "path": "tools/StayHere.exe", + "sha256": "1530796fac99f1542b992e4254fc30c16c24ee7e6c6dc7b6ba41d241e3ea6417", "size": 133120 }, { - "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413", "path": "tools/StayHere-README.md", + "sha256": "ba214e2aca7405e698b3ab21ceb1f41ce088edd996b3e30e4a9d58ff496f9413", "size": 2796 } - ] + ], + "version": "0.8.4" } diff --git a/resources/app.rc b/resources/app.rc index 53356b4..a07061d 100644 --- a/resources/app.rc +++ b/resources/app.rc @@ -14,8 +14,8 @@ IDC_SCREENSHOT_PENCIL CURSOR "icons/lucide/pencil.cur" 1 RT_MANIFEST "app.manifest" 201 RCDATA "update.ps1" 1 VERSIONINFO - FILEVERSION 0,8,3,0 - PRODUCTVERSION 0,8,3,0 + FILEVERSION 0,8,4,0 + PRODUCTVERSION 0,8,4,0 FILEOS VOS_NT_WINDOWS32 FILETYPE VFT_APP BEGIN @@ -25,7 +25,7 @@ BEGIN BEGIN VALUE "FileDescription", "KSwitcher — native keyboard and clipboard utility" VALUE "ProductName", "KSwitcher" - VALUE "FileVersion", "0.8.3" + VALUE "FileVersion", "0.8.4" END END BLOCK "VarFileInfo" diff --git a/src/update.h b/src/update.h index 66a40aa..f1835a9 100644 --- a/src/update.h +++ b/src/update.h @@ -2,7 +2,7 @@ #include "platform.h" namespace ks { -inline constexpr wchar_t AppVersion[] = L"0.8.3"; +inline constexpr wchar_t AppVersion[] = L"0.8.4"; inline constexpr UINT UpdateMessage = WM_APP + 7; inline constexpr UINT UpdateCheckIntervalMs = 6 * 60 * 60 * 1000; inline constexpr UINT UpdateNotificationRetryMs = 5 * 60 * 1000; diff --git a/tests/input.cpp b/tests/input.cpp index f3eeda6..8f3963f 100644 --- a/tests/input.cpp +++ b/tests/input.cpp @@ -1138,7 +1138,7 @@ int main(int argc, char **argv) { auto events = GetDlgItem(pane, 733); auto visible = [&](int id) { return (GetWindowLongPtrW(GetDlgItem(pane, id), GWL_STYLE) & WS_VISIBLE) != 0; }; auto selectPage = [&](int index) { selectSettingsPage(settings, index); }; - require(TreeView_GetCount(navigation) == 20, "all Settings sections are listed"); + require(TreeView_GetCount(navigation) == 21, "all Settings sections are listed"); selectPage(3); require(visible(243) && !visible(501), "Clipboard lists excluded apps separately from OCR"); require(TreeView_GetParent(navigation, settingsSection(navigation, 19)) == settingsSection(navigation, 3), diff --git a/tests/input_pause.cpp b/tests/input_pause.cpp index 4578268..ec434c8 100644 --- a/tests/input_pause.cpp +++ b/tests/input_pause.cpp @@ -67,9 +67,10 @@ void chooseInputAction(HWND resident, DWORD pid, const wchar_t *expected) } } require(donationSeparated && donation.hbmpItem, "tray donation item has an icon and both separators"); - require(help && GetMenuItemCount(help) == 2 && menuTitle(help, 0) == L"&User guide" && - menuTitle(help, 1) == L"&About KSwitcher", - "tray Help submenu contains User guide and About KSwitcher"); + require(help && GetMenuItemCount(help) == 3 && menuTitle(help, 0) == L"&User guide" && + menuTitle(help, 1) == ks::whatsNewTitle(GetThreadUILanguage()) && + menuTitle(help, 2) == L"&About KSwitcher", + "tray Help submenu contains User guide, release notes and About KSwitcher"); require(PostMessageW(popup, WM_CHAR, L'i', 0), "cannot select input menu item"); until([&] { return !IsWindow(popup); }, "tray action did not close menu"); query(resident, WM_NULL);