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) + } +}