From 9ae2c134adeae1661d24f6f36540f528ea3b2a49 Mon Sep 17 00:00:00 2001 From: Richard Wu Date: Wed, 28 Oct 2026 17:02:43 +0800 Subject: [PATCH] fix: keep detached windows on source monitor and refine tab actions --- src/main.rs | 235 ++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 208 insertions(+), 27 deletions(-) diff --git a/src/main.rs b/src/main.rs index a241feb..7c53c60 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,7 @@ use std::path::Component; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::Instant; -use tao::dpi::{LogicalPosition, LogicalSize}; +use tao::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}; use tao::event::{Event as TaoEvent, WindowEvent}; use tao::event_loop::{ ControlFlow, EventLoop, EventLoopBuilder, EventLoopProxy, EventLoopWindowTarget, @@ -41,6 +41,7 @@ enum UserEvent { ActivateTab(WindowId, u64), CloseTab(WindowId, u64), DetachTab(WindowId, u64), + RevealTab(WindowId, u64), CloseActiveTab, LocateTab(WindowId, u64), FileChanged(WindowId, PathBuf), // external change: refresh preview AND textarea @@ -201,6 +202,7 @@ struct Strings { btn_preview: &'static str, btn_new: &'static str, btn_new_window: &'static str, + btn_open_location: &'static str, new_filename: &'static str, fold_toggle: &'static str, btn_zoom: &'static str, @@ -229,6 +231,7 @@ impl Strings { btn_preview: "预览 (Cmd/Ctrl+E)", btn_new: "新建 Markdown (Cmd/Ctrl+N)", btn_new_window: "在新窗口打开", + btn_open_location: "打开文件所在位置", new_filename: "新建.md", fold_toggle: "折叠/展开", btn_zoom: "正文缩放", @@ -253,6 +256,7 @@ impl Strings { btn_preview: "Preview (Cmd/Ctrl+E)", btn_new: "New Markdown (Cmd/Ctrl+N)", btn_new_window: "Open in New Window", + btn_open_location: "Show in Explorer", new_filename: "Untitled.md", fold_toggle: "Collapse / Expand", btn_zoom: "Content zoom", @@ -1311,6 +1315,7 @@ body.has-tabs {{ --chrome-top: 50px; }} font-size: 13px; }} .tab:hover {{ background: rgba(0,0,0,0.045); }} + .tab.dragging {{ opacity: .55; cursor: grabbing; }} .tab.active {{ color: #202020; background: #fff; border-color: #ddd; box-shadow: 0 1px 2px rgba(0,0,0,.04); }} .tab.missing {{ color: #a15c00; }} .tab-status {{ width: 7px; height: 7px; flex: 0 0 auto; border-radius: 50%; background: transparent; }} @@ -1324,13 +1329,18 @@ body.has-tabs {{ --chrome-top: 50px; }} }} .tab-close:hover {{ opacity: 1; background: rgba(0,0,0,.08); }} .tab-menu {{ - position: fixed; z-index: 200; min-width: 184px; padding: 5px; + position: fixed; z-index: 200; min-width: 188px; padding: 4px; background: #fff; border: 1px solid #ddd; border-radius: 8px; box-shadow: 0 8px 24px rgba(0,0,0,.16); }} .tab-menu[hidden] {{ display: none; }} + .tab-menu-path {{ + max-width: 280px; padding: 3px 8px 5px; overflow: hidden; + color: #8a8a8a; font-size: 11px; line-height: 1.3; + white-space: nowrap; text-overflow: ellipsis; + }} .tab-menu button {{ - display: block; width: 100%; padding: 7px 10px; border: 0; border-radius: 5px; + display: block; width: 100%; padding: 5px 8px; border: 0; border-radius: 5px; background: transparent; color: #222; text-align: left; font: inherit; font-size: 13px; cursor: pointer; }} @@ -1461,6 +1471,7 @@ body.empty .toolbar {{ display: none !important; }} .tab.missing {{ color: #e3a04b; }} .tab-close:hover, .tab-open:hover {{ background: rgba(255,255,255,.1); color: #fff; }} .tab-menu {{ background: #2a2a2a; border-color: #444; box-shadow: 0 8px 24px rgba(0,0,0,.45); }} + .tab-menu-path {{ color: #999; }} .tab-menu button {{ color: #ddd; }} .tab-menu button:hover {{ background: rgba(255,255,255,.08); }} .tab-menu button:disabled:hover {{ background: transparent; }} @@ -1500,7 +1511,7 @@ body.editing #app {{ max-width: none; padding: 0; }} }}
- +
@@ -1550,8 +1561,12 @@ body.editing #app {{ max-width: none; padding: 0; }} var docStats = document.getElementById('doc-stats'); var tabOpen = document.getElementById('tab-open'); var tabMenu = document.getElementById('tab-menu'); + var tabMenuPath = document.getElementById('tab-menu-path'); + var tabMenuReveal = document.getElementById('tab-menu-reveal'); var tabMenuNewWindow = document.getElementById('tab-menu-new-window'); var tabMenuTargetId = 0; + var tabDrag = null; + var suppressTabClickUntil = 0; var ta = document.getElementById('editor'); var dirty = false; var activeTabId = 0; @@ -1637,16 +1652,46 @@ body.editing #app {{ max-width: none; padding: 0; }} applyZoom(100, false); window.__mdPreviewSetZoom = function(percent) {{ applyZoom(percent, false); }}; updateDocumentStats(ta.value); + function shortenPath(path, max) {{ + if (!path || path.length <= max) return path || ''; + var head = Math.ceil((max - 3) / 2); + var tail = Math.floor((max - 3) / 2); + return path.slice(0, head) + '...' + path.slice(-tail); + }} + function suppressTabTooltips() {{ + Array.prototype.forEach.call(tabsEl.querySelectorAll('.tab[title]'), function(tab) {{ + tab.setAttribute('data-saved-title', tab.getAttribute('title')); + tab.removeAttribute('title'); + }}); + }} + function restoreTabTooltips() {{ + Array.prototype.forEach.call(tabsEl.querySelectorAll('.tab[data-saved-title]'), function(tab) {{ + var title = tab.getAttribute('data-saved-title'); + tab.removeAttribute('data-saved-title'); + if (title) tab.setAttribute('title', title); + }}); + }} function hideTabMenu() {{ if (!tabMenu || tabMenu.hidden) return; tabMenu.hidden = true; tabMenuTargetId = 0; + restoreTabTooltips(); }} function showTabMenu(id, x, y) {{ if (!tabMenu) return; + if (!tabMenu.hidden) hideTabMenu(); + suppressTabTooltips(); tabMenuTargetId = id; + var tabEl = tabsEl.querySelector('.tab[data-tab-id="' + id + '"]'); + var path = tabEl ? (tabEl.getAttribute('data-tab-path') || '') : ''; + if (tabMenuPath) {{ + tabMenuPath.textContent = shortenPath(path, 42); + if (path) tabMenuPath.setAttribute('title', path); + else tabMenuPath.removeAttribute('title'); + }} tabMenu.hidden = false; if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1; + if (tabMenuReveal) tabMenuReveal.disabled = !path; tabMenu.style.left = '0px'; tabMenu.style.top = '0px'; var rect = tabMenu.getBoundingClientRect(); @@ -1902,10 +1947,61 @@ body.editing #app {{ max-width: none; padding: 0; }} if (id) detachTab(id); }}); }} + if (tabMenuReveal) {{ + tabMenuReveal.addEventListener('click', function(e) {{ + e.preventDefault(); + e.stopPropagation(); + var id = tabMenuTargetId; + hideTabMenu(); + if (id) window.ipc.postMessage('reveal-tab:' + id); + }}); + }} + tabsEl.addEventListener('pointerdown', function(e) {{ + if (e.button !== 0 || tabCount <= 1) return; + var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null; + if (!tab || (e.target.closest && e.target.closest('.tab-close'))) return; + hideTabMenu(); + tabDrag = {{ id: tab.getAttribute('data-tab-id'), startY: e.clientY, element: tab, pointerId: e.pointerId, dragged: false }}; + try {{ tab.setPointerCapture(e.pointerId); }} catch (err) {{}} + }}); + tabsEl.addEventListener('pointermove', function(e) {{ + if (!tabDrag || e.pointerId !== tabDrag.pointerId) return; + if (!tabDrag.dragged && Math.abs(e.clientY - tabDrag.startY) >= 24) {{ + tabDrag.dragged = true; + tabDrag.element.classList.add('dragging'); + }} + }}); + tabsEl.addEventListener('pointerup', function(e) {{ + if (!tabDrag || e.pointerId !== tabDrag.pointerId) return; + var drag = tabDrag; + tabDrag = null; + drag.element.classList.remove('dragging'); + try {{ + if (drag.element.hasPointerCapture(e.pointerId)) drag.element.releasePointerCapture(e.pointerId); + }} catch (err) {{}} + if (!drag.dragged) return; + suppressTabClickUntil = Date.now() + 350; + if (tabCount > 1) detachTab(drag.id); + }}); + tabsEl.addEventListener('pointercancel', function(e) {{ + if (!tabDrag || e.pointerId !== tabDrag.pointerId) return; + var drag = tabDrag; + tabDrag = null; + drag.element.classList.remove('dragging'); + }}); window.addEventListener('resize', hideTabMenu); window.addEventListener('scroll', hideTabMenu, true); window.addEventListener('blur', hideTabMenu); document.addEventListener('click', function(e) {{ + if (Date.now() < suppressTabClickUntil) {{ + var suppressedTab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null; + if (suppressedTab) {{ + suppressTabClickUntil = 0; + e.preventDefault(); + e.stopPropagation(); + return; + }} + }} if (tabMenu && !tabMenu.hidden) hideTabMenu(); var closeTab = e.target && e.target.closest ? e.target.closest('[data-close-tab]') : null; if (closeTab) {{ @@ -2101,6 +2197,7 @@ body.editing #app {{ max-width: none; padding: 0; }} var item = document.createElement('div'); item.className = 'tab' + (tab.active ? ' active' : '') + (tab.missing ? ' missing' : '') + (tab.dirty ? ' dirty' : ''); item.setAttribute('data-tab-id', tab.id); + item.setAttribute('data-tab-path', tab.path); item.setAttribute('role', 'button'); item.setAttribute('tabindex', '0'); item.title = tab.path; @@ -2205,6 +2302,7 @@ if(window.__enhancePreview)window.__enhancePreview(); raw_md_escaped = html_escape_ta(raw_md), btn_new = s.btn_new, btn_new_window = s.btn_new_window, + btn_open_location = s.btn_open_location, btn_edit = s.btn_edit, btn_preview = s.btn_preview, fold_toggle = s.fold_toggle, @@ -2589,6 +2687,23 @@ mod tests { assert!(!is_help_arg("--edit")); } + #[test] + fn secondary_window_stays_on_source_monitor() { + assert_eq!( + clamp_secondary_position(2028, 128, 800, 600, Some((1920, 0, 1920, 1080))), + (2028, 128) + ); + assert_eq!( + clamp_secondary_position(3400, 1200, 800, 600, Some((1920, 0, 1920, 1080))), + (3040, 480) + ); + assert_eq!( + clamp_secondary_position(-100, -100, 800, 600, Some((0, 0, 1920, 1080))), + (0, 0) + ); + assert_eq!(clamp_secondary_position(10, 10, 800, 600, None), (10, 10)); + } + #[test] fn zoom_percent_is_clamped_to_supported_range() { assert_eq!(clamp_zoom(10), 50); @@ -2690,6 +2805,12 @@ mod tests { assert!(page.contains("(e.key === 'n' || e.key === 'N')")); assert!(page.contains("id=\"doc-stats\"")); assert!(page.contains("id=\"tab-menu\"")); + assert!(page.contains("id=\"tab-menu-path\"")); + assert!(page.contains("id=\"tab-menu-reveal\"")); + assert!(page.contains("data-tab-path")); + assert!(page.contains("function shortenPath")); + assert!(page.contains("tabsEl.addEventListener('pointerdown'")); + assert!(page.contains("suppressTabClickUntil")); assert!(page.contains("tabCount = tabs.length")); assert!(page.contains("tabMenuNewWindow.disabled = tabCount <= 1")); assert!(page.contains("updateDocumentStats")); @@ -3475,6 +3596,29 @@ fn is_supported_document(path: &Path) -> bool { .unwrap_or(false) } +#[cfg(windows)] +fn reveal_in_explorer(path: &Path) -> bool { + let mut command = std::process::Command::new("explorer.exe"); + if path.is_file() { + command.arg("/select,").arg(path); + } else if let Some(parent) = path.parent().filter(|parent| parent.is_dir()) { + command.arg(parent); + } else { + return false; + } + command.spawn().is_ok() +} + +#[cfg(not(windows))] +fn reveal_in_explorer(path: &Path) -> bool { + let target = if path.exists() { + path + } else { + path.parent().unwrap_or(path) + }; + open::that(target).is_ok() +} + fn resolve_document_link(value: &str, active: Option<&Path>) -> Option { let url = match url::Url::parse(value) { Ok(url) => url, @@ -4018,6 +4162,10 @@ fn build_webview( if let Ok(id) = id.parse::() { let _ = proxy_for_ipc.send_event(UserEvent::LocateTab(window_id, id)); } + } else if let Some(id) = body.strip_prefix("reveal-tab:") { + if let Ok(id) = id.parse::() { + let _ = proxy_for_ipc.send_event(UserEvent::RevealTab(window_id, id)); + } } else if body == "dirty:1" { let _ = proxy_for_ipc.send_event(UserEvent::DirtyChanged(window_id, true)); } else if body == "dirty:0" { @@ -4108,28 +4256,43 @@ fn build_webview( const MAX_WINDOWS: usize = 16; -fn secondary_geom(source: &WindowState, target: &EventLoopWindowTarget) -> WindowGeom { +fn clamp_secondary_position( + x: i32, + y: i32, + w: u32, + h: u32, + monitor: Option<(i32, i32, u32, u32)>, +) -> (i32, i32) { + let Some((mx, my, mw, mh)) = monitor else { + return (x, y); + }; + let max_x = mx + mw as i32 - w as i32; + let max_y = my + mh as i32 - h as i32; + (x.clamp(mx, max_x.max(mx)), y.clamp(my, max_y.max(my))) +} + +fn secondary_geom(source: &WindowState) -> (PhysicalPosition, PhysicalSize) { let scale = source.window.scale_factor(); let size = source.window.inner_size(); - let w = (size.width as f64 / scale).max(400.0); - let h = (size.height as f64 / scale).max(300.0); - let (mut x, mut y) = source + let w = size.width.max(400); + let h = size.height.max(300); + let offset = (28.0 * scale).round() as i32; + let (x, y) = source .window .outer_position() - .map(|pos| (pos.x as f64 / scale + 28.0, pos.y as f64 / scale + 28.0)) - .unwrap_or((140.0, 140.0)); - if let Some(monitor) = target.available_monitors().next() { - let ms = monitor.scale_factor(); - let mp = monitor.position(); - let msize = monitor.size(); - let mx = mp.x as f64 / ms; - let my = mp.y as f64 / ms; - let mw = msize.width as f64 / ms; - let mh = msize.height as f64 / ms; - x = x.clamp(mx, (mx + mw - w).max(mx)); - y = y.clamp(my, (my + mh - h).max(my)); - } - WindowGeom { x, y, w, h } + .map(|pos| (pos.x + offset, pos.y + offset)) + .unwrap_or((140, 140)); + let monitor = source + .window + .current_monitor() + .or_else(|| source.window.primary_monitor()) + .map(|monitor| { + let pos = monitor.position(); + let size = monitor.size(); + (pos.x, pos.y, size.width, size.height) + }); + let (x, y) = clamp_secondary_position(x, y, w, h, monitor); + (PhysicalPosition::new(x, y), PhysicalSize::new(w, h)) } fn create_window_with_session( @@ -4149,12 +4312,12 @@ fn create_window_with_session( .get(&source_window_id) .or_else(|| app.windows.get(&app.active_window)) .ok_or_else(|| "No active window.".to_string())?; - let geom = secondary_geom(source, target); + let (position, size) = secondary_geom(source); let theme = load_theme_choice(); let mut builder = WindowBuilder::new() .with_title("MD Preview") - .with_inner_size(LogicalSize::new(geom.w, geom.h)) - .with_position(LogicalPosition::new(geom.x, geom.y)) + .with_inner_size(size) + .with_position(position) .with_theme(theme.tao_theme()); if let Some(icon) = load_window_icon() { builder = builder.with_window_icon(Some(icon)); @@ -4520,8 +4683,6 @@ fn main() { return; } - ws.window.set_minimized(false); - ws.window.set_focus(); let paths = paths .into_iter() .filter(|path| is_supported_document(path)) @@ -4553,6 +4714,8 @@ fn main() { ws.pending_launches.push((vec![path], edit_on_open)); continue; } + ws.window.set_minimized(false); + ws.window.set_focus(); let mut session = ws.session.lock().unwrap(); let previous_active = session.active_id; let preserve_active = session.active().map(|tab| tab.dirty).unwrap_or(false); @@ -4678,6 +4841,24 @@ fn main() { close_window(&mut app, window_id, control_flow); } } + TaoEvent::UserEvent(UserEvent::RevealTab(window_id, tab_id)) => { + let path = app.windows.get(&window_id).and_then(|ws| { + let session = ws.session.lock().unwrap(); + session + .tabs + .iter() + .find(|tab| tab.id == tab_id) + .map(|tab| tab.path.clone()) + }); + if let Some(path) = path { + if !reveal_in_explorer(&path) { + show_warning_dialog( + "Could Not Open File Location", + &path.to_string_lossy(), + ); + } + } + } TaoEvent::UserEvent(UserEvent::CloseActiveTab) => { let window_id = app.active_window; let multiple_windows = app.windows.len() > 1;