From 50010c99bae16b02ffce72deb2a575f709995d96 Mon Sep 17 00:00:00 2001 From: Anatolii Hrynchuk Date: Wed, 25 Nov 2026 16:32:23 +0200 Subject: [PATCH] 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"; }