Add Quick View for local text and Markdown

Refs #89
This commit is contained in:
agrynco committed 2026-11-25 13:33:15 +02:00
1 parent edb259e6bb
commit 3dd4edeb2c
8 files changed
+408 -60

No files matched your search

+199 -46
View File
@@ -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<RemoteTextFile>(*backend,original);
else document=std::make_unique<TextDocument>(draft?std::filesystem::path{}:original,edit,options.encoding);
else if(!embedded) document=std::make_unique<TextDocument>(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<TextDocument> 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<TextDocument> document;
std::string firstPage;
std::optional<std::string> markdown;
};
std::future<QuickDocument> quickLoading;
std::filesystem::path quickPath;
uint64_t quickRequest{}, quickReading{};
ULONGLONG quickReadyAt{};
std::wstring quickError;
std::optional<std::string> 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<std::string> 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<std::string> 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<std::string> 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<std::string> 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<document.pages();++index) text+=document.readPage(index);
return text;
}
void TextWindow::previewFile(const std::filesystem::path &path)
{
if(path==quickPath) return;
quickPath=path;
++quickRequest;
quickReadyAt=GetTickCount64()+80;
stopPreview(false,true);
document.reset();
quickMarkdown.reset();
quickError.clear();
layout();
SetTimer(window,quickViewTimer,30,nullptr);
}
void TextWindow::pollQuickView()
{
if(quickLoading.valid())
{
if(quickLoading.wait_for(std::chrono::seconds(0))!=std::future_status::ready) return;
const bool current=quickRequest==quickReading;
try
{
auto loaded=quickLoading.get();
if(current)
{
original=quickPath;
filename=original.filename().wstring();
document=std::move(loaded.document);
quickMarkdown=std::move(loaded.markdown);
initializeDocument(std::move(loaded.firstPage));
}
}
catch(const std::exception &error)
{
if(current)
{
quickError=wide(error.what());
document.reset();
layout();
}
}
if(current)
{
KillTimer(window,quickViewTimer);
return;
}
}
if(quickPath.empty())
{
KillTimer(window,quickViewTimer);
return;
}
if(GetTickCount64()<quickReadyAt) return;
quickReading=quickRequest;
std::packaged_task<QuickDocument()> task([path=quickPath] {
auto source=std::make_unique<TextDocument>(path,false);
auto first=source->readPage(0);
if(first.find('\0')!=std::string::npos)
throw std::runtime_error("Binary preview is unavailable.");
std::optional<std::string> 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;index<document->pages();++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()<nextFileCheck) return;
if(embedded || remote || !previewVisible || navigation.valid() || busy() || pendingTask || GetTickCount64()<nextFileCheck) return;
nextFileCheck=GetTickCount64()+350;
const auto stamp=previewFileStamp();
if(!stamp || stamp==previewStamp) return;
@@ -1862,14 +1961,17 @@ void TextWindow::previewMessage(const std::wstring &value)
PostMessageW(window,cycleWindow,message.value("reverse",false),0);
return;
}
if(embedded && action!="image" && action!="rendered" && action!="failed") return;
const auto revision=message.value("revision",previewRevision);
if(embedded && revision!=previewRevision) return;
if(action=="failed")
{
PostMessageW(window,previewFailed,0,0);
PostMessageW(window,previewFailed,static_cast<WPARAM>(revision),0);
return;
}
if(action=="rendered")
{
PostMessageW(window,previewRendered,0,0);
PostMessageW(window,previewRendered,static_cast<WPARAM>(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<LONG>(2*row,area.bottom-row)},previewWanted);
const int top=embedded?row:2*row;
const LONG bottom=std::max<LONG>(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<HBRUSH>(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<LONG>(2*row,client.bottom-row)};
FillRect(dc, &body, brush);
SetDCBrushColor(dc, color(TextColor::chromebg));
@@ -2339,6 +2461,7 @@ void TextWindow::notify(const SCNotification &notice)
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<const std::shared_ptr<TextWindow> *>(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<TextWindow>(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<HMENU>(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<TextWindow>(original,edit,dialogs,backend,fragment,options);
const auto title=std::wstring(edit?L"Editor — ":L"Viewer — ")+
(backend?backend->name+L" · ":std::wstring{})+path.wstring();