Compare commits

...
9 changed files with 693 additions and 65 deletions

No files matched your search

+14 -2
View File
@@ -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.
@@ -397,6 +400,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 потоково записують нову копію в
+24
View File
@@ -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"
+4 -2
View File
@@ -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);
+56
View File
@@ -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<TextLineLocation> 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<count;++index)
{
checkLineScan(stop);
const auto contents=readPage(index);
end=contents.size();
for(size_t offset=0;offset<end;++offset)
{
const auto value=contents[offset];
if(counter.line==line && !(counter.afterCr && value=='\n'))
return TextLineLocation{index,offset};
counter.consume(value);
}
}
return counter.line==line?std::optional(TextLineLocation{count-1,end}):std::nullopt;
}
std::string formatHexAddress(uint64_t offset)
{
constexpr char digits[]="0123456789ABCDEF";
+10
View File
@@ -4,6 +4,8 @@
#include <cstdint>
#include <filesystem>
#include <map>
#include <optional>
#include <stop_token>
#include <string>
#include <string_view>
@@ -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<TextLineLocation> 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(); }
+306 -61
View File
@@ -25,6 +25,7 @@
#include "../vendor/json.hpp"
#include <algorithm>
#include <array>
#include <cerrno>
#include <chrono>
#include <cstring>
#include <cwchar>
@@ -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)
@@ -663,6 +666,19 @@ struct RemoteTextFile
}
};
std::future<std::unique_ptr<RemoteTextFile>> fetchRemoteText(const RemoteTextSource &source,
const std::filesystem::path &path,const std::shared_ptr<std::atomic<bool>> &canceled)
{
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task([source,path,canceled] {
auto file=std::make_unique<RemoteTextFile>(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<HWND,std::shared_ptr<TextWindow>> textWindows;
std::vector<HWND> textWindowOrder;
@@ -744,6 +760,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)
{
@@ -769,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);
}
@@ -776,6 +794,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,12 +805,24 @@ private:
bool edit{}, loading{}, stagedDirty{}, closeAfterSave{}, insertRejected{};
bool draft{}, embedded{};
bool hex{};
uint64_t initialBookmark{};
bool showBookmarkSource{};
struct ViewerPosition
{
uint64_t page{};
LRESULT anchor{}, caret{}, firstLine{}, horizontal{};
};
std::optional<ViewerPosition> beforeHex;
struct SuspendedEditor
{
std::unique_ptr<TextDocument> document;
ViewerPosition position;
bool uploadPending{};
};
std::optional<SuspendedEditor> suspendedEditor;
std::unique_ptr<RemoteTextFile> savedViewerFile;
std::future<std::unique_ptr<RemoteTextFile>> savedViewerLoad;
std::shared_ptr<std::atomic<bool>> cancelSavedViewer;
TextSaveFormat newFormat;
std::filesystem::path pendingSavePath;
HICON smallIcon{},largeIcon{};
@@ -814,7 +845,6 @@ private:
int pageEol = SC_EOL_CRLF;
size_t undoBytes{};
bool uploadPending{};
bool switchAfterSave{};
FilesTerminalView preview;
bool previewWanted{}, previewVisible{}, previewRetried{};
ULONGLONG previewDeadline{};
@@ -874,6 +904,18 @@ 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;
static constexpr UINT_PTR savedViewerTimer = 7;
struct BookmarkLocation
{
std::filesystem::path path;
uint64_t line{};
bool adding{};
std::optional<TextLineLocation> position;
std::unique_ptr<TextDocument> source;
};
std::future<BookmarkLocation> bookmarkTask;
std::stop_source bookmarkStop;
struct QuickDocument
{
std::unique_ptr<TextDocument> document;
@@ -933,6 +975,9 @@ private:
void installLexer();
void loadPage(uint64_t index,std::optional<std::string> 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);
@@ -940,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<RemoteTextFile> saved={});
void restoreEditor();
void finishSavedViewer();
void cancelSavedViewerLoad();
bool needsSave() const;
bool canPreview() const;
void updatePreview();
@@ -1015,6 +1067,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");
@@ -1380,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
@@ -1390,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();
@@ -1404,6 +1460,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<size_t>(std::max<LRESULT>(0,send(SCI_GETCURRENTPOS)));
const auto encoding=document->encoding();
std::packaged_task<BookmarkLocation()> task([path=original,currentPage,caret,encoding,line,token] {
auto source=std::make_unique<TextDocument>(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<LPARAM>(&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 +1592,7 @@ void TextWindow::initializeDocument(std::optional<std::string> firstPage)
installLexer();
loadPage(0,std::move(firstPage));
updatePreview();
if(initialBookmark) locateBookmark(std::exchange(initialBookmark,0));
}
std::string readMarkdownDocument(TextDocument &document)
@@ -1544,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);
@@ -1592,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);
@@ -1610,7 +1756,6 @@ void TextWindow::finishSave()
return;
}
if (closeAfterSave) { DestroyWindow(window); return; }
if (change) { changeMode(); return; }
if(created)
{
initializeDocument();
@@ -1631,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);
@@ -1643,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<RemoteTextFile>(remote->source,original);
refreshed->download(false,{});
auto replacement = std::make_unique<TextDocument>(refreshed->cache,false);
document.reset();
remote = std::move(refreshed);
document = std::move(replacement);
uploadPending = false;
auto cancel=std::make_shared<std::atomic<bool>>(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<LRESULT>(position.anchor,0,length),std::clamp<LRESULT>(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<TextDocument>(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();
@@ -1699,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<TextDocument>(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<RemoteTextFile> saved)
{
const auto position=currentPosition();
const auto path=draft?std::filesystem::path{}:saved?saved->cache:remote?remote->cache:original;
auto replacement=std::make_unique<TextDocument>(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 — ") +
@@ -1739,7 +1959,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 +2001,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);
@@ -1859,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;
@@ -1909,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);
@@ -2099,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+1<navigationHistory.size()}}.dump()));
preview.post(wide(nlohmann::json{{"action","history"},{"back",!suspendedEditor && navigationIndex>0},
{"forward",!suspendedEditor && navigationIndex+1<navigationHistory.size()}}.dump()));
}
void TextWindow::navigatePreview(PreviewLink request)
{
if(edit || busy() || pendingTask || navigation.valid() || navigationHistory.empty()) return;
if(suspendedEditor)
{
if(request.direction) return;
if(request.target.path!=original) request.newWindow=true;
}
if(request.newWindow)
{
if(remote)
@@ -2126,19 +2357,11 @@ void TextWindow::navigatePreview(PreviewLink request)
else destination=std::move(request.target);
if(destination.path==original || !remote) { showLocation(nullptr); return; }
auto cancel=std::make_shared<std::atomic<bool>>(false);
std::packaged_task<std::unique_ptr<RemoteTextFile>()> task(
[backend=remote->source,path=destination.path,cancel] {
auto file=std::make_unique<RemoteTextFile>(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; }
@@ -2354,17 +2577,20 @@ 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)
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":
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" :
@@ -2428,6 +2654,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 +2800,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 +2966,8 @@ 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();
if (wparam == savedViewerTimer) self->finishSavedViewer();
return 0;
case trimUndo:
if (self->undoBytes >= 32 * TextDocument::pageBytes)
@@ -2747,6 +2979,8 @@ 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);
self->stopPreview(false);
@@ -3004,7 +3238,7 @@ void openImageWindow(HWND owner,std::vector<std::filesystem::path> 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 +3249,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 +3291,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());}
}
}
+2
View File
@@ -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<std::filesystem::path> 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,
+251
View File
@@ -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<ViewerBookmark> 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<ViewerBookmark> 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<std::string>());
const auto line=item["line"].get<uint64_t>();
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<std::string>());
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.line<right.line;
});
bookmarks.erase(std::unique(bookmarks.begin(),bookmarks.end(),sameViewerBookmark),bookmarks.end());
return bookmarks;
}
std::filesystem::path viewerBookmarksFile()
{
return dataDirectory()/L"files-viewer-bookmarks.json";
}
enum class BookmarkChange { upsert, rename, remove };
void changeViewerBookmark(const ViewerBookmark &bookmark,BookmarkChange change)
{
struct Lock
{
HANDLE handle=CreateMutexW(nullptr,FALSE,L"Local\\KSwitcher.Files.ViewerBookmarks");
bool owned{};
~Lock()
{
if(owned) ReleaseMutex(handle);
if(handle) CloseHandle(handle);
}
} lock;
if(!lock.handle) throw std::runtime_error("Could not open Viewer bookmark storage.");
const auto wait=WaitForSingleObject(lock.handle,100);
lock.owned=wait==WAIT_OBJECT_0 || wait==WAIT_ABANDONED;
if(!lock.owned) throw std::runtime_error("Viewer bookmark storage is busy.");
const auto file=viewerBookmarksFile();
auto bookmarks=readViewerBookmarks(file);
const auto existing=std::find_if(bookmarks.begin(),bookmarks.end(),[&](const auto &item) {
return sameViewerBookmark(item,bookmark);
});
if(existing==bookmarks.end())
{
if(change!=BookmarkChange::upsert) throw std::runtime_error("This bookmark has already been removed.");
bookmarks.push_back(bookmark);
}
else if(change==BookmarkChange::remove) bookmarks.erase(existing);
else existing->name=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<BookmarkPrompt *>(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<BookmarkPrompt *>(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<int>(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'0' || 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<int>(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<ViewerBookmark> bookmarks;
std::optional<ViewerBookmark> 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<size_t>(row)<state.bookmarks.size()?
state.bookmarks[row].path.c_str():L"No bookmarks");
}
void renderBookmarkList(HWND dialog,ViewerBookmarkList &state,LRESULT oldSelection)
{
state.bookmarks=readViewerBookmarks(viewerBookmarksFile());
if(!state.filter.empty()) std::erase_if(state.bookmarks,[&](const auto &item) {
return compareBookmarkPaths(state.filter,item.path)!=0;
});
const auto list=GetDlgItem(dialog,bookmarkList);
SendMessageW(list,LB_RESETCONTENT,0,0);
const auto dc=GetDC(list);
HGDIOBJ oldFont{};
if(dc)
if(const auto font=SendMessageW(list,WM_GETFONT,0,0))
oldFont=SelectObject(dc,reinterpret_cast<HFONT>(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<LPARAM>(label.c_str()));
SIZE dimensions{};
if(dc && GetTextExtentPoint32W(dc,label.c_str(),static_cast<int>(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<LRESULT>(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<ViewerBookmarkList *>(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<ViewerBookmarkList *>(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<size_t>(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<LPARAM>(&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<ViewerBookmark> 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<LPARAM>(&state))==IDOK) return std::move(state.opening);
return {};
}
+26
View File
@@ -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";
}