diff --git a/src/app.rs b/src/app.rs new file mode 100644 index 0000000..2c46f69 --- /dev/null +++ b/src/app.rs @@ -0,0 +1,1597 @@ +//! Application state, page rendering, window creation and the event loop. + +use crate::config::{ + confirm_discard_unsaved, load_theme_choice, load_zoom, save_theme_choice, save_window_geom, + save_zoom, show_warning_dialog, ThemeChoice, +}; +use crate::escape::{escape_js, html_escape_attr, html_escape_text}; +use crate::files::{ + forget_recent_file, install_file_watcher, is_supported_document, local_document_path_from_url, + normalize_new_markdown_path, remember_recent_file, resolve_document_link, reveal_in_explorer, + save_active_file, self_write_still_matches_disk, should_protect_external_change, + SelfWriteRecord, MAX_RECENT_FILES, +}; +use crate::markdown::md_to_html_with_base; +use crate::page::build_page; +use crate::session::{self, DocumentSession}; +use std::collections::HashMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; +use tao::dpi::{PhysicalPosition, PhysicalSize}; +use tao::event::{Event as TaoEvent, WindowEvent}; +use tao::event_loop::{ControlFlow, EventLoop, EventLoopProxy, EventLoopWindowTarget}; +use tao::window::{Window, WindowBuilder, WindowId}; +use wry::{WebContext, WebView, WebViewBuilder}; + +const ICON_BYTES: &[u8] = include_bytes!("../assets/icon.ico"); + +/// The page drives these over IPC today; the menu-style variants are kept for +/// keyboard paths that are not wired up on Windows yet (Ctrl+W/E/F, Quit). +#[allow(dead_code)] +#[derive(Debug)] +pub(crate) enum UserEvent { + NewFile(WindowId), + NewTab(WindowId), + OpenFile(WindowId), + OpenPaths(Option, Vec, bool), + 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 + ExternalChangeResolved(WindowId, bool), + FileSaved(WindowId, PathBuf), // our own save: refresh preview only, leave textarea cursor alone + SaveFailed(WindowId, PathBuf, String), + DirtyChanged(WindowId, bool), + ToggleEdit, + ShowFind, + Print(WindowId), // route print through wry's native API (WKWebView ignores window.print()) + SetTheme(ThemeChoice), + Quit, + RecentChanged, + Ready(WindowId), // first paint landed: inject hljs now; if bench mode, also exit +} + +pub(crate) struct WindowState { + pub(crate) webview: WebView, + pub(crate) window: Window, + pub(crate) session: Arc>, + pub(crate) last_self_write: Arc>>, + pub(crate) watcher: Arc>>, + pub(crate) enhance_flags: Arc>, + pub(crate) loaded_enhancers: EnhanceFlags, + pub(crate) page_ready: bool, + pub(crate) pending_launches: Vec<(Vec, bool)>, + pub(crate) pending_close: bool, + pub(crate) warned_external_change: Option, + pub(crate) pending_external_change: Option, + pub(crate) dirty: bool, + pub(crate) is_primary: bool, +} + +impl WindowState { + fn render_active( + &mut self, + recent_files: &Arc>>, + strings: &Strings, + ) -> bool { + let session = Arc::clone(&self.session); + let mut session = session.lock().unwrap(); + let dirty = render_active_document( + &self.webview, + &self.window, + &mut session, + recent_files, + &self.enhance_flags, + &mut self.loaded_enhancers, + strings, + ); + self.dirty = dirty; + dirty + } +} + +pub(crate) struct AppState { + pub(crate) windows: HashMap, + pub(crate) active_window: WindowId, + pub(crate) recent_files: Arc>>, + pub(crate) strings: Strings, + pub(crate) web_context: WebContext, +} + +impl AppState { + fn active_mut(&mut self) -> Option<&mut WindowState> { + let id = self.active_window; + self.windows.get_mut(&id) + } +} + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct EnhanceFlags { + pub(crate) math: bool, + pub(crate) mermaid: bool, +} + +impl EnhanceFlags { + fn any(self) -> bool { + self.math || self.mermaid + } +} + +#[derive(Clone)] +pub(crate) struct Strings { + pub(crate) drop_hint: &'static str, + pub(crate) cannot_read: &'static str, + pub(crate) open_file: &'static str, + pub(crate) new_file: &'static str, + pub(crate) new_tab: &'static str, + pub(crate) home_tab: &'static str, + pub(crate) recent_title: &'static str, + pub(crate) missing_title: &'static str, + pub(crate) missing_body: &'static str, + pub(crate) locate_file: &'static str, + pub(crate) close_tab: &'static str, + pub(crate) cannot_save: &'static str, + pub(crate) btn_edit: &'static str, + pub(crate) btn_preview: &'static str, + pub(crate) btn_new: &'static str, + pub(crate) btn_new_window: &'static str, + pub(crate) btn_open_location: &'static str, + pub(crate) new_filename: &'static str, + pub(crate) fold_toggle: &'static str, + pub(crate) btn_zoom: &'static str, + pub(crate) btn_zoom_out: &'static str, + pub(crate) btn_zoom_reset: &'static str, + pub(crate) btn_zoom_in: &'static str, + pub(crate) search_placeholder: &'static str, + pub(crate) stat_words: &'static str, + pub(crate) stat_chars: &'static str, +} + +impl Strings { + /// The app ships a single English UI. There is deliberately no locale + /// detection, so the interface never mixes Chinese and English labels. + pub(crate) fn english() -> Self { + Strings { + drop_hint: "Drop a .md file here or press Cmd/Ctrl+O to open", + cannot_read: "Cannot read file", + open_file: "Open File", + new_file: "New File", + new_tab: "New Tab", + home_tab: "New Tab", + recent_title: "Recent", + missing_title: "File Moved or Deleted", + missing_body: "This tab is kept. Locate the file again or close the tab.", + locate_file: "Locate File", + close_tab: "Close Tab", + cannot_save: "This file could not be saved (read-only or locked). Continue and discard the unsaved changes?", + btn_edit: "Edit (Cmd/Ctrl+E)", + 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", + btn_zoom_out: "Zoom out (Cmd/Ctrl+-)", + btn_zoom_reset: "Reset zoom (Cmd/Ctrl+0)", + btn_zoom_in: "Zoom in (Cmd/Ctrl++)", + search_placeholder: "Find", + stat_words: "non-space", + stat_chars: "chars", + } + } +} + +// Embedded highlight.js + themes (offline) +pub(crate) const HLJS_JS: &str = include_str!("../assets/hljs/highlight.min.js"); +// Always-dark code blocks; app chrome still follows the system theme. +// Extra language pack(s) not in the `common` bundle. Each file +// ends with `hljs.registerLanguage(...)` and only works if evaluated +// in the same scope as the main bundle — we concat them into hljs-src. +pub(crate) const HLJS_EXTRA_LANGS: &str = concat!( + // Delphi / Pascal (aliases: dpr, dfm, pas, pascal) — user requested + include_str!("../assets/hljs/delphi.min.js"), +); +const KATEX_JS: &str = include_str!("../assets/katex/katex.min.js"); +const KATEX_CSS: &str = include_str!("../assets/katex/katex.inline.css"); +const MERMAID_JS: &str = include_str!("../assets/mermaid/mermaid.min.js"); +pub(crate) fn tabs_json(session: &DocumentSession) -> String { + let tabs = session + .tabs + .iter() + .map(|tab| { + // The page owns the New Tab label; rust only flags the kind. + let name = tab + .file_path() + .and_then(|path| path.file_name()) + .map(|name| name.to_string_lossy().to_string()) + .unwrap_or_default(); + let path = tab + .file_path() + .map(|path| path.to_string_lossy().to_string()) + .unwrap_or_default(); + serde_json::json!({ + "id": tab.id, + "name": name, + "path": path, + "home": tab.is_home(), + "active": session.active_id == Some(tab.id), + "missing": tab.missing, + "dirty": tab.dirty, + }) + }) + .collect::>(); + serde_json::to_string(&tabs).expect("tab state is serializable") +} + +fn missing_preview_html(tab_id: u64, path: &Path, s: &Strings) -> String { + format!( + r#"
!

{}

{}

{}
"#, + html_escape_text(s.missing_title), + html_escape_text(s.missing_body), + html_escape_text(&path.to_string_lossy()), + html_escape_text(s.locate_file), + html_escape_text(s.close_tab), + ) +} + +pub(crate) fn base_href_for_file(path: &Path) -> Option { + let dir = path.parent()?; + url::Url::from_directory_path(dir) + .ok() + .map(|url| url.to_string()) +} + +fn starts_mermaid_fence(line: &str) -> bool { + let trimmed = line.trim_start(); + let rest = trimmed + .strip_prefix("```") + .or_else(|| trimmed.strip_prefix("~~~")); + let Some(info) = rest else { + return false; + }; + let info = info.trim_start(); + info == "mermaid" + || info + .strip_prefix("mermaid") + .and_then(|s| s.chars().next()) + .map(|c| c.is_whitespace() || c == '{') + .unwrap_or(false) +} + +fn has_unescaped_at(s: &str, index: usize, needle: &str) -> bool { + if !s[index..].starts_with(needle) { + return false; + } + let mut backslashes = 0; + for b in s[..index].bytes().rev() { + if b == b'\\' { + backslashes += 1; + } else { + break; + } + } + backslashes % 2 == 0 +} + +fn has_unescaped_pair(s: &str, open: &str, close: &str) -> bool { + let mut pos = 0; + while let Some(rel) = s[pos..].find(open) { + let start = pos + rel; + if !has_unescaped_at(s, start, open) { + pos = start + open.len(); + continue; + } + let body_start = start + open.len(); + let mut search = body_start; + while let Some(close_rel) = s[search..].find(close) { + let close_at = search + close_rel; + if has_unescaped_at(s, close_at, close) { + return true; + } + search = close_at + close.len(); + } + pos = body_start; + } + false +} + +fn has_inline_dollar_math(s: &str) -> bool { + let bytes = s.as_bytes(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] != b'$' || !has_unescaped_at(s, i, "$") { + i += 1; + continue; + } + if bytes.get(i + 1).copied() == Some(b'$') + || bytes + .get(i + 1) + .map(|b| b.is_ascii_whitespace()) + .unwrap_or(true) + { + i += 1; + continue; + } + let mut j = i + 1; + while j < bytes.len() { + if bytes[j] == b'$' + && has_unescaped_at(s, j, "$") + && bytes + .get(j.wrapping_sub(1)) + .map(|b| !b.is_ascii_whitespace()) + .unwrap_or(false) + { + return true; + } + j += 1; + } + i += 1; + } + false +} + +fn enhance_flags_for(md: &str) -> EnhanceFlags { + EnhanceFlags { + math: has_unescaped_pair(md, "$$", "$$") + || has_unescaped_pair(md, "\\[", "\\]") + || has_unescaped_pair(md, "\\(", "\\)") + || has_inline_dollar_math(md), + mermaid: md.lines().any(starts_mermaid_fence), + } +} + +fn build_enhancer_bootstrap(flags: EnhanceFlags, loaded: EnhanceFlags) -> Vec { + if !flags.any() { + return Vec::new(); + } + + let mut scripts = Vec::new(); + if flags.math && !loaded.math { + let mut js = String::from("(function(){\nif(!window.katex){\n"); + js.push_str(KATEX_JS); + js.push_str("\n;try{window.katex=katex;}catch(e){}\n}\n"); + js.push_str("if(window.__setKatexCss)window.__setKatexCss('"); + js.push_str(&escape_js(KATEX_CSS)); + js.push_str("');\n})();"); + scripts.push(js); + } + if flags.mermaid && !loaded.mermaid { + // Mermaid's standalone bundle expects global script scope. Keep it + // out of the function wrapper that is safe for KaTeX/highlight.js. + let mut js = String::with_capacity(MERMAID_JS.len() + 80); + js.push_str(MERMAID_JS); + js.push_str("\n;try{window.mermaid=mermaid;}catch(e){}\n"); + scripts.push(js); + } + scripts.push("if(window.__enhancePreview)window.__enhancePreview();".to_string()); + scripts +} + +pub(crate) fn home_preview_html(s: &Strings, recent_files: &[PathBuf]) -> String { + let empty_class = if recent_files.is_empty() { + "empty" + } else { + "empty has-recent" + }; + let mut html = format!( + r#"
#
{}
"#, + html_escape_text(s.drop_hint), + html_escape_text(s.open_file), + html_escape_attr(s.btn_new), + html_escape_text(s.new_file) + ); + + if !recent_files.is_empty() { + html.push_str(&format!( + r#"
{}
"#, + html_escape_text(s.recent_title) + )); + for (index, path) in recent_files.iter().take(MAX_RECENT_FILES).enumerate() { + let name = path + .file_name() + .map(|n| n.to_string_lossy()) + .unwrap_or_else(|| path.to_string_lossy()); + let parent = path + .parent() + .map(|p| p.to_string_lossy()) + .unwrap_or_default(); + html.push_str(&format!( + r#""#, + html_escape_text(&name), + html_escape_text(&parent) + )); + } + html.push_str("
"); + } + + html.push_str("
"); + html +} + +/// Decode embedded icon.ico to an RGBA tao Icon for the window chrome. +pub(crate) fn load_window_icon() -> Option { + let img = image::load_from_memory_with_format(ICON_BYTES, image::ImageFormat::Ico).ok()?; + let rgba = img.to_rgba8(); + let (w, h) = rgba.dimensions(); + tao::window::Icon::from_rgba(rgba.into_raw(), w, h).ok() +} + +fn find_open_path(app: &AppState, path: &Path) -> Option<(WindowId, u64)> { + let normalized = session::normalize_path(path.to_path_buf()); + for (window_id, ws) in &app.windows { + let session = ws.session.lock().unwrap(); + if let Some(tab) = session + .tabs + .iter() + .find(|tab| tab.path.as_deref() == Some(normalized.as_path())) + { + return Some((*window_id, tab.id)); + } + } + None +} + +fn focus_open_tab( + app: &mut AppState, + window_id: WindowId, + tab_id: u64, + recent_files: &Arc>>, + strings: &Strings, + proxy: &EventLoopProxy, +) -> bool { + let Some(ws) = app.windows.get_mut(&window_id) else { + return false; + }; + let mut session = ws.session.lock().unwrap(); + let target_active = session.active_id == Some(tab_id); + let active_dirty = session.active().map(|tab| tab.dirty).unwrap_or(false); + let target_dirty = session + .tabs + .iter() + .find(|tab| tab.id == tab_id) + .map(|tab| tab.dirty) + .unwrap_or(false); + if !target_active && (active_dirty || target_dirty) { + // Never switch away from or reload an unsaved tab just to focus it. + return false; + } + if !session.activate(tab_id) { + return false; + } + app.active_window = window_id; + ws.window.set_minimized(false); + ws.window.set_focus(); + if target_active { + update_tabs(&ws.webview, &session); + return true; + } + drop(session); + ws.render_active(recent_files, strings); + let path = ws + .session + .lock() + .unwrap() + .active_path() + .map(Path::to_path_buf); + install_file_watcher(&ws.watcher, proxy, &ws.last_self_write, window_id, path); + true +} + +fn update_tabs(webview: &WebView, session: &DocumentSession) { + let state = tabs_json(session); + let _ = webview.evaluate_script(&format!("if(window.__setTabs)window.__setTabs({state});")); +} + +fn update_window_title(window: &Window, session: &DocumentSession) { + let title = match session.active() { + Some(tab) => match tab.file_path() { + Some(path) => { + let name = path + .file_name() + .map(|name| name.to_string_lossy().to_string()) + .unwrap_or_else(|| path.to_string_lossy().to_string()); + format!("{}{} — MD Preview", if tab.dirty { "• " } else { "" }, name) + } + None => "MD Preview".to_string(), + }, + None => "MD Preview".to_string(), + }; + window.set_title(&title); +} + +fn render_home( + webview: &WebView, + window: &Window, + session: &DocumentSession, + recent_files: &Arc>>, + strings: &Strings, +) { + let html = home_preview_html(strings, &recent_files.lock().unwrap()); + let _ = webview.evaluate_script(&format!( + "if(window.__setEmptyPreview)window.__setEmptyPreview('{}');", + escape_js(&html) + )); + update_tabs(webview, session); + update_window_title(window, session); +} + +/// Build the `__setContent` call. +/// +/// The argument list must match the `window.__setContent` signature in +/// `assets/page/page.js`. Nothing type-checks this boundary: when the two +/// drift apart the page reads a wrong value as HTML (it once rendered the tab +/// id, so a white window showed "1", "2", "3" as tabs were opened). +pub(crate) fn set_content_script( + html: &str, + raw: &str, + base_href: &str, + flags: EnhanceFlags, + editing: bool, + scroll_ratio: f32, +) -> String { + format!( + "if(window.__setContent)window.__setContent('{}', '{}', '{}', {}, {}, {}, {});", + escape_js(html), + escape_js(raw), + escape_js(base_href), + flags.math, + flags.mermaid, + editing, + scroll_ratio + ) +} + +fn render_active_document( + webview: &WebView, + window: &Window, + session: &mut DocumentSession, + recent_files: &Arc>>, + enhance_flags: &Arc>, + loaded_enhancers: &mut EnhanceFlags, + strings: &Strings, +) -> bool { + let Some(active) = session.active().cloned() else { + render_home(webview, window, session, recent_files, strings); + return false; + }; + // Home tabs carry no file; they render the new-tab page. + let Some(path) = active.file_path().map(Path::to_path_buf) else { + render_home(webview, window, session, recent_files, strings); + return false; + }; + + match fs::read_to_string(&path) { + Ok(raw) => { + if let Some(tab) = session.get_mut(active.id) { + tab.missing = false; + } + remember_recent_file(recent_files, &path); + let html = md_to_html_with_base(&raw, path.parent()); + let base_href = base_href_for_file(&path).unwrap_or_default(); + let flags = enhance_flags_for(&raw); + *enhance_flags.lock().unwrap() = flags; + let _ = webview.evaluate_script(&set_content_script( + &html, + &raw, + &base_href, + flags, + active.editing, + active.scroll_ratio, + )); + for script in build_enhancer_bootstrap(flags, *loaded_enhancers) { + let _ = webview.evaluate_script(&script); + } + loaded_enhancers.math |= flags.math; + loaded_enhancers.mermaid |= flags.mermaid; + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + if let Some(tab) = session.get_mut(active.id) { + tab.missing = true; + } + if active.dirty { + show_warning_dialog( + strings.missing_title, + "The file disappeared while it still has unsaved edits. The editor content has been kept.", + ); + } else { + let html = missing_preview_html(active.id, &path, strings); + let _ = webview.evaluate_script(&format!( + "if(window.__setMissing)window.__setMissing('{}');", + escape_js(&html) + )); + } + } + Err(error) => { + if active.dirty { + show_warning_dialog(strings.cannot_read, &error.to_string()); + } else { + // A bad restored path must leave the window usable, without a + // modal dialog during startup or stale content from another tab. + let html = format!( + r#"

{}

{}

{}
"#, + html_escape_text(strings.cannot_read), + html_escape_text(&error.to_string()), + html_escape_text(&path.to_string_lossy()), + html_escape_text(strings.open_file), + active.id, + html_escape_text(strings.close_tab), + ); + let _ = webview.evaluate_script(&format!( + "if(window.__setMissing)window.__setMissing('{}');", + escape_js(&html) + )); + } + } + } + + let dirty = session.active().map(|tab| tab.dirty).unwrap_or(false); + update_tabs(webview, session); + update_window_title(window, session); + dirty +} + +// WebView2 NavigateToString has a 2 MiB limit. Never include document or +// persisted path data in this page; load the active tab after the ready IPC. +pub(crate) fn build_startup_page(strings: &Strings) -> String { + build_page( + &home_preview_html(strings, &[]), + "", + None, + EnhanceFlags::default(), + strings, + true, + ) +} + +#[allow(clippy::too_many_arguments)] // shared window plumbing; split with the webview module +pub(crate) fn build_webview( + window: &Window, + web_context: &mut WebContext, + window_id: WindowId, + session: Arc>, + last_self_write: Arc>>, + recent_files: Arc>>, + proxy: EventLoopProxy, + initial_page: String, +) -> Result { + let proxy_for_ipc = proxy.clone(); + let proxy_for_navigation = proxy.clone(); + let proxy_for_drag = proxy.clone(); + let builder = WebViewBuilder::with_web_context(web_context) + .with_html(&initial_page) + .with_navigation_handler(move |url: String| { + // Let wry load the initial in-memory document; route any real URL click + // to the app's tab model or the system default handler. + if url.starts_with("http://") + || url.starts_with("https://") + || url.starts_with("mailto:") + { + let _ = open::that(&url); + false + } else if let Some(path) = local_document_path_from_url(&url) { + let _ = proxy_for_navigation.send_event(UserEvent::OpenPaths( + Some(window_id), + vec![path], + false, + )); + false + } else { + !url.starts_with("file:") + } + }) + .with_ipc_handler(move |msg| { + let body = msg.body(); + if body == "new-file" { + let _ = proxy_for_ipc.send_event(UserEvent::NewFile(window_id)); + } else if body == "open" { + let _ = proxy_for_ipc.send_event(UserEvent::OpenFile(window_id)); + } else if let Some(index) = body.strip_prefix("open-recent:") { + if let Ok(index) = index.parse::() { + let path = recent_files.lock().unwrap().get(index).cloned(); + if let Some(path) = path { + if path.exists() { + let _ = proxy_for_ipc.send_event(UserEvent::OpenPaths( + Some(window_id), + vec![path], + false, + )); + } else if forget_recent_file(&recent_files, &path) { + let _ = proxy_for_ipc.send_event(UserEvent::RecentChanged); + } + } + } + } else if let Some(url) = body.strip_prefix("open-local-link:") { + let active_path = session.lock().unwrap().active_path().map(Path::to_path_buf); + if let Some(path) = resolve_document_link(url, active_path.as_deref()) { + let _ = proxy_for_ipc.send_event(UserEvent::OpenPaths( + Some(window_id), + vec![path], + false, + )); + } + } else if let Some(rest) = body.strip_prefix("tab-action:") { + let (header, pending_content) = rest + .split_once('\n') + .map(|(header, content)| (header, Some(content))) + .unwrap_or((rest, None)); + let mut parts = header.splitn(3, ':'); + let action = parts.next().unwrap_or(""); + let id = parts.next().and_then(|value| value.parse::().ok()); + // The page reports where the tab it is leaving was scrolled to. + let scroll_ratio = parts.next().and_then(|value| value.parse::().ok()); + let Some(id) = id else { + return; + }; + if let Some(ratio) = scroll_ratio { + session.lock().unwrap().set_active_scroll_ratio(ratio); + } + if let Some(content) = pending_content { + // A tab action is only safe once the pending edit is written. + if !save_active_file( + &session, + &last_self_write, + &proxy_for_ipc, + window_id, + content, + ) { + return; + } + } + match action { + "activate" => { + let _ = proxy_for_ipc.send_event(UserEvent::ActivateTab(window_id, id)); + } + "close" => { + let _ = proxy_for_ipc.send_event(UserEvent::CloseTab(window_id, id)); + } + "detach" => { + let _ = proxy_for_ipc.send_event(UserEvent::DetachTab(window_id, id)); + } + "new-tab" => { + let _ = proxy_for_ipc.send_event(UserEvent::NewTab(window_id)); + } + _ => {} + } + } else if let Some(id) = body.strip_prefix("locate-tab:") { + 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" { + let _ = proxy_for_ipc.send_event(UserEvent::DirtyChanged(window_id, false)); + } else if body == "external-change:dirty" { + let _ = + proxy_for_ipc.send_event(UserEvent::ExternalChangeResolved(window_id, true)); + } else if body == "external-change:clean" { + let _ = + proxy_for_ipc.send_event(UserEvent::ExternalChangeResolved(window_id, false)); + } else if body == "print" { + let _ = proxy_for_ipc.send_event(UserEvent::Print(window_id)); + } else if body == "ready" { + let _ = proxy_for_ipc.send_event(UserEvent::Ready(window_id)); + } else if let Some(percent) = body.strip_prefix("zoom:") { + if let Ok(percent) = percent.parse::() { + save_zoom(percent); + } + } else if body == "refresh" { + if let Some(path) = session.lock().unwrap().active_path().map(Path::to_path_buf) { + let _ = proxy_for_ipc.send_event(UserEvent::FileChanged(window_id, path)); + } + } else if let Some(content) = body.strip_prefix("save:") { + save_active_file( + &session, + &last_self_write, + &proxy_for_ipc, + window_id, + content, + ); + } else if let Some(rest) = body.strip_prefix("scroll:") { + if let Some((id, ratio)) = rest.split_once(':') { + if let (Ok(id), Ok(ratio)) = (id.parse::(), ratio.parse::()) { + session.lock().unwrap().set_tab_scroll_ratio(id, ratio); + } + } + } else if let Some(rest) = body.strip_prefix("edit-mode:") { + if let Some((id, mode)) = rest.split_once(':') { + if let Ok(id) = id.parse::() { + session.lock().unwrap().set_tab_editing(id, mode == "1"); + } + } + } + }) + .with_drag_drop_handler(move |event| { + if let wry::DragDropEvent::Drop { paths, .. } = event { + let paths = paths + .into_iter() + .filter(|path| is_supported_document(path)) + .collect::>(); + if !paths.is_empty() { + let _ = proxy_for_drag.send_event(UserEvent::OpenPaths( + Some(window_id), + paths, + false, + )); + } + } + true + }); + + // Wry supplies its own browser options, which can mask WebView2's + // environment override. Honor explicit diagnostic arguments only when set. + let builder = { + use wry::WebViewBuilderExtWindows; + match std::env::var("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS") { + Ok(arguments) => builder.with_additional_browser_args(&arguments), + Err(_) => builder, + } + }; + + let webview = builder.build(window); + + webview.map_err(|error| error.to_string()) +} + +const MAX_WINDOWS: usize = 16; + +pub(crate) 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.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 + 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( + target: &EventLoopWindowTarget, + app: &mut AppState, + proxy: &EventLoopProxy, + initial_session: DocumentSession, + source_window_id: WindowId, +) -> Result { + if app.windows.len() >= MAX_WINDOWS { + return Err(format!( + "At most {MAX_WINDOWS} windows can be open at once." + )); + } + let source = app + .windows + .get(&source_window_id) + .or_else(|| app.windows.get(&app.active_window)) + .ok_or_else(|| "No active window.".to_string())?; + let (position, size) = secondary_geom(source); + let theme = load_theme_choice(); + let mut builder = WindowBuilder::new() + .with_title("MD Preview") + .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)); + } + let window = builder.build(target).map_err(|error| error.to_string())?; + let window_id = window.id(); + let page = build_startup_page(&app.strings); + let mut initial_session = initial_session; + if initial_session.tabs.is_empty() { + initial_session.open_home(); + } + let session = Arc::new(Mutex::new(initial_session)); + let last_self_write = Arc::new(Mutex::new(None)); + let recent_files = Arc::clone(&app.recent_files); + let webview = build_webview( + &window, + &mut app.web_context, + window_id, + Arc::clone(&session), + Arc::clone(&last_self_write), + recent_files, + proxy.clone(), + page, + )?; + let enhance_flags = Arc::new(Mutex::new(EnhanceFlags::default())); + let watcher = Arc::new(Mutex::new(None)); + app.windows.insert( + window_id, + WindowState { + webview, + window, + session, + last_self_write, + watcher, + enhance_flags, + loaded_enhancers: EnhanceFlags::default(), + page_ready: false, + pending_launches: Vec::new(), + pending_close: false, + warned_external_change: None, + pending_external_change: None, + dirty: false, + is_primary: false, + }, + ); + app.active_window = window_id; + if let Some(ws) = app.windows.get(&window_id) { + ws.window.set_focus(); + } + Ok(window_id) +} + +fn close_window(app: &mut AppState, window_id: WindowId, control_flow: &mut ControlFlow) { + let was_primary = app + .windows + .get(&window_id) + .map(|ws| ws.is_primary) + .unwrap_or(false); + if was_primary { + if let Some(ws) = app.windows.get(&window_id) { + save_window_geom(&ws.window); + } + } + app.windows.remove(&window_id); + if app.windows.is_empty() { + *control_flow = ControlFlow::Exit; + return; + } + if was_primary { + if let Some((_, ws)) = app.windows.iter_mut().next() { + ws.is_primary = true; + } + } + if app.active_window == window_id { + if let Some(next) = app.windows.keys().next().copied() { + app.active_window = next; + if let Some(ws) = app.windows.get(&next) { + ws.window.set_focus(); + } + } + } +} + +/// Hand the event loop to the app state. Called last from `main`. +pub(crate) fn run_event_loop( + event_loop: EventLoop, + mut app: AppState, + proxy: EventLoopProxy, + hljs_bootstrap: String, + bench: bool, + t0: Instant, +) { + event_loop.run(move |event, target, control_flow| { + *control_flow = ControlFlow::Wait; + let strings = app.strings.clone(); + let recent_files = Arc::clone(&app.recent_files); + + match event { + TaoEvent::UserEvent(UserEvent::NewFile(window_id)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + let active_dirty = ws + .session + .lock() + .unwrap() + .active() + .map(|tab| tab.dirty) + .unwrap_or(false); + if active_dirty { + let _ = ws.webview.evaluate_script( + "if(window.__mdPreviewNewFile)window.__mdPreviewNewFile();", + ); + return; + } + let current_dir = ws + .session + .lock() + .unwrap() + .active() + .and_then(|tab| tab.file_path()) + .and_then(|path| path.parent().map(Path::to_path_buf)); + let mut dialog = rfd::FileDialog::new() + .add_filter("Markdown", &["md", "markdown", "mdown", "mkd"]) + .set_file_name(strings.new_filename); + if let Some(current_dir) = current_dir { + dialog = dialog.set_directory(current_dir); + } + if let Some(path) = dialog.save_file() { + let path = normalize_new_markdown_path(path); + match fs::write(&path, "") { + Ok(()) => { + let _ = proxy.send_event(UserEvent::OpenPaths( + Some(window_id), + vec![path], + true, + )); + } + Err(error) => { + show_warning_dialog("Could Not Create File", &error.to_string()); + } + } + } + } + TaoEvent::UserEvent(UserEvent::OpenFile(window_id)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + let active_dirty = ws + .session + .lock() + .unwrap() + .active() + .map(|tab| tab.dirty) + .unwrap_or(false); + if active_dirty { + let _ = ws.webview.evaluate_script( + "if(window.__mdPreviewOpenFile)window.__mdPreviewOpenFile();", + ); + return; + } + if let Some(paths) = rfd::FileDialog::new() + .add_filter("Markdown", &["md", "markdown", "mdown", "mkd"]) + .pick_files() + { + let _ = proxy.send_event(UserEvent::OpenPaths( + Some(window_id), + paths, + false, + )); + } + } + TaoEvent::UserEvent(UserEvent::NewTab(window_id)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + let mut session = ws.session.lock().unwrap(); + session.open_home(); + drop(session); + ws.render_active(&recent_files, &strings); + install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, None); + } + TaoEvent::UserEvent(UserEvent::OpenPaths(target, paths, edit_on_open)) => { + let target_window = target.unwrap_or(app.active_window); + let Some(ws) = app.windows.get_mut(&target_window) else { + return; + }; + if !ws.page_ready { + ws.pending_launches.push((paths, edit_on_open)); + return; + } + + let paths = paths + .into_iter() + .filter(|path| is_supported_document(path)) + .collect::>(); + if paths.is_empty() { + return; + } + for path in paths { + if let Some((window_id, tab_id)) = find_open_path(&app, &path) { + if !focus_open_tab( + &mut app, + window_id, + tab_id, + &recent_files, + &strings, + &proxy, + ) { + show_warning_dialog( + "Unsaved Changes", + "That file is open in another window with unsaved changes.", + ); + } + continue; + } + let Some(ws) = app.windows.get_mut(&target_window) else { + return; + }; + if !ws.page_ready { + 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); + if !preserve_active && session.active_is_home() { + session.open_reusing_home(path, edit_on_open); + } else { + session.open(path, edit_on_open); + } + if preserve_active { + if let Some(id) = previous_active { + session.activate(id); + } + } + if preserve_active { + update_tabs(&ws.webview, &session); + } else { + drop(session); + ws.render_active(&recent_files, &strings); + } + let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); + install_file_watcher( + &ws.watcher, + &proxy, + &ws.last_self_write, + target_window, + path, + ); + } + } + TaoEvent::UserEvent(UserEvent::ActivateTab(window_id, id)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + let mut session = ws.session.lock().unwrap(); + if session.activate(id) { + drop(session); + ws.render_active(&recent_files, &strings); + let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); + install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path); + } + } + TaoEvent::UserEvent(UserEvent::CloseTab(window_id, id)) => { + let multiple_windows = app.windows.len() > 1; + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + let mut session = ws.session.lock().unwrap(); + let Some(target) = session.tabs.iter().find(|tab| tab.id == id) else { + return; + }; + let was_active = session.active_id == Some(id); + let sole_tab = session.tabs.len() == 1; + let closing_home = target.is_home(); + if sole_tab { + if multiple_windows { + drop(session); + close_window(&mut app, window_id, control_flow); + return; + } + if closing_home { + // The last window always keeps one Home tab. + return; + } + // Closing the last file tab returns to the Home tab. + session.close_with_home_fallback(id); + drop(session); + ws.render_active(&recent_files, &strings); + install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, None); + return; + } + if session.close(id) { + if was_active { + drop(session); + ws.render_active(&recent_files, &strings); + let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); + install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path); + } else { + update_tabs(&ws.webview, &session); + } + } + } + TaoEvent::UserEvent(UserEvent::DetachTab(window_id, tab_id)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + let session = ws.session.lock().unwrap(); + let Some(tab) = session.tabs.iter().find(|tab| tab.id == tab_id).cloned() else { + return; + }; + if tab.is_home() { + return; + } + let target_active = session.active_id == Some(tab_id); + if !target_active && tab.dirty { + drop(session); + show_warning_dialog( + "Could Not Move Tab", + "Save this file before moving it to a new window.", + ); + return; + } + drop(session); + + let mut moved = tab; + moved.dirty = false; + moved.missing = false; + let new_session = DocumentSession::with_tab(moved); + let new_window_id = match create_window_with_session( + target, + &mut app, + &proxy, + new_session, + window_id, + ) { + Ok(id) => id, + Err(error) => { + show_warning_dialog("Could Not Open New Window", &error); + return; + } + }; + + let close_source; + { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + let mut session = ws.session.lock().unwrap(); + if session.detach(tab_id).is_none() { + drop(session); + close_window(&mut app, new_window_id, control_flow); + show_warning_dialog("Could Not Move Tab", "The tab is no longer available."); + return; + } + close_source = session.tabs.is_empty(); + if !close_source { + drop(session); + ws.render_active(&recent_files, &strings); + let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); + install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path); + } + } + if close_source { + 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) + .and_then(|tab| tab.file_path()) + .map(Path::to_path_buf) + }); + 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; + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + if ws.session.lock().unwrap().active_id.is_some() { + let _ = ws.webview.evaluate_script( + "if(window.__mdPreviewCloseActiveTab)window.__mdPreviewCloseActiveTab();", + ); + } else if multiple_windows { + close_window(&mut app, window_id, control_flow); + } + } + TaoEvent::UserEvent(UserEvent::LocateTab(window_id, id)) => { + if let Some(path) = rfd::FileDialog::new() + .add_filter("Markdown", &["md", "markdown", "mdown", "mkd"]) + .pick_file() + { + if let Some((other_id, other_tab)) = find_open_path(&app, &path) { + if !focus_open_tab( + &mut app, + other_id, + other_tab, + &recent_files, + &strings, + &proxy, + ) { + show_warning_dialog( + "Unsaved Changes", + "That file is open in another window with unsaved changes.", + ); + } + return; + } + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + let mut session = ws.session.lock().unwrap(); + if session.relocate(id, path) && session.activate(id) { + drop(session); + ws.render_active(&recent_files, &strings); + let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); + install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path); + } else { + show_warning_dialog("Already Open", "That file is already open in another tab."); + } + } + } + TaoEvent::UserEvent(UserEvent::FileChanged(window_id, path)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + if ws.session.lock().unwrap().active_path() == Some(path.as_path()) { + ws.pending_external_change = Some(path); + let _ = ws.webview.evaluate_script( + "if(window.__mdPreviewResolveExternalChange)window.__mdPreviewResolveExternalChange();", + ); + } + } + TaoEvent::UserEvent(UserEvent::ExternalChangeResolved(window_id, webview_dirty)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + let Some(path) = ws.pending_external_change.take() else { + return; + }; + if self_write_still_matches_disk(ws.last_self_write.lock().unwrap().as_ref(), &path) { + return; + } + let mut session = ws.session.lock().unwrap(); + if session.active_path() == Some(path.as_path()) { + let session_dirty = session.active().map(|tab| tab.dirty).unwrap_or(false); + if should_protect_external_change(webview_dirty, session_dirty) { + if let Some(tab) = session.active_mut() { + tab.dirty = true; + } + ws.dirty = true; + let _ = ws.webview.evaluate_script( + "if(window.__mdPreviewPauseAutosave)window.__mdPreviewPauseAutosave();", + ); + drop(session); + if ws.warned_external_change.as_ref() != Some(&path) { + show_warning_dialog( + "File Changed on Disk", + "Automatic saving is paused and your edits are still in the editor. Press Cmd/Ctrl+S to replace the disk version, or reopen the file to keep the external version.", + ); + ws.warned_external_change = Some(path); + } + return; + } + drop(session); + ws.render_active(&recent_files, &strings); + } + } + TaoEvent::UserEvent(UserEvent::FileSaved(window_id, path)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + if ws.warned_external_change.as_ref() == Some(&path) { + ws.warned_external_change = None; + } + let mut session = ws.session.lock().unwrap(); + let active_matches = session.active_path() == Some(path.as_path()); + if let Some(tab) = session + .tabs + .iter_mut() + .find(|tab| tab.path.as_deref() == Some(path.as_path())) + { + tab.dirty = false; + tab.missing = false; + } + if active_matches { + if let Ok(raw) = fs::read_to_string(&path) { + let html = md_to_html_with_base(&raw, path.parent()); + let flags = enhance_flags_for(&raw); + *ws.enhance_flags.lock().unwrap() = flags; + let _ = ws.webview.evaluate_script(&format!( + "if(window.__setPreview)window.__setPreview('{}', {}, {});if(window.__markSaved)window.__markSaved('{}');", + escape_js(&html), + flags.math, + flags.mermaid, + escape_js(&raw) + )); + for script in build_enhancer_bootstrap(flags, ws.loaded_enhancers) { + let _ = ws.webview.evaluate_script(&script); + } + ws.loaded_enhancers.math |= flags.math; + ws.loaded_enhancers.mermaid |= flags.mermaid; + } + } + ws.dirty = session.active().map(|tab| tab.dirty).unwrap_or(false); + update_tabs(&ws.webview, &session); + update_window_title(&ws.window, &session); + let pending_close = ws.pending_close; + drop(session); + if pending_close { + close_window(&mut app, window_id, control_flow); + } + } + TaoEvent::UserEvent(UserEvent::SaveFailed(window_id, _path, error)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + let _ = ws.webview.evaluate_script( + "if(window.__markSaveBlocked)window.__markSaveBlocked();", + ); + if ws.pending_close { + ws.pending_close = false; + if confirm_discard_unsaved(&error) { + close_window(&mut app, window_id, control_flow); + } + } else { + show_warning_dialog( + "Could Not Save", + &format!( + "{error}\n\nAutosave is paused for this file. Close the window to discard the unsaved changes." + ), + ); + } + } + TaoEvent::UserEvent(UserEvent::DirtyChanged(window_id, dirty)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + ws.dirty = dirty; + let mut session = ws.session.lock().unwrap(); + if let Some(tab) = session.active_mut() { + tab.dirty = dirty; + } + update_tabs(&ws.webview, &session); + update_window_title(&ws.window, &session); + } + TaoEvent::UserEvent(UserEvent::ToggleEdit) => { + let Some(ws) = app.active_mut() else { + return; + }; + let _ = ws.webview.evaluate_script( + "if(window.__mdPreviewToggleEdit)window.__mdPreviewToggleEdit();", + ); + } + TaoEvent::UserEvent(UserEvent::ShowFind) => { + let Some(ws) = app.active_mut() else { + return; + }; + let _ = ws + .webview + .evaluate_script("if(window.__mdPreviewShowFind)window.__mdPreviewShowFind();"); + } + TaoEvent::UserEvent(UserEvent::RecentChanged) => { + let html = home_preview_html(&strings, &recent_files.lock().unwrap()); + let js = format!( + "if(window.__setEmptyPreview)window.__setEmptyPreview('{}');", + escape_js(&html) + ); + for ws in app.windows.values() { + if ws.session.lock().unwrap().active_is_home() { + let _ = ws.webview.evaluate_script(&js); + } + } + } + TaoEvent::UserEvent(UserEvent::Print(window_id)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + let _ = ws.webview.print(); + } + TaoEvent::UserEvent(UserEvent::Quit) => { + let window_id = app.active_window; + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + if ws.dirty && !ws.pending_close { + ws.pending_close = true; + let _ = ws.webview.evaluate_script( + "if(window.__mdPreviewSave)window.__mdPreviewSave();", + ); + } else if !ws.pending_close { + if ws.is_primary { + save_window_geom(&ws.window); + } + *control_flow = ControlFlow::Exit; + } + } + TaoEvent::UserEvent(UserEvent::SetTheme(choice)) => { + save_theme_choice(choice); + for ws in app.windows.values() { + ws.window.set_theme(choice.tao_theme()); + } + } + TaoEvent::UserEvent(UserEvent::Ready(window_id)) => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + // First paint is on the screen; now push hljs into the page + // (kept out of first-paint HTML to keep it slim). Always do + // this, even in bench mode, so subsequent panes would still + // highlight — bench just exits right after measuring. + let _ = ws.webview.evaluate_script(&hljs_bootstrap); + let zoom = load_zoom(); + if zoom != 100 { + let _ = ws.webview.evaluate_script(&format!( + "window.__mdPreviewSetZoom && window.__mdPreviewSetZoom({zoom});" + )); + } + if !ws.page_ready { + ws.page_ready = true; + ws.render_active(&recent_files, &strings); + let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); + install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path); + } + for (paths, edit) in ws.pending_launches.drain(..) { + let _ = proxy.send_event(UserEvent::OpenPaths(Some(window_id), paths, edit)); + } + if bench { + eprintln!("[bench] +{}ms ready", t0.elapsed().as_millis()); + *control_flow = ControlFlow::Exit; + } + } + TaoEvent::WindowEvent { + event: WindowEvent::Focused(true), + window_id, + .. + } => { + if app.windows.contains_key(&window_id) { + app.active_window = window_id; + } + } + TaoEvent::WindowEvent { + event: WindowEvent::CloseRequested, + window_id, + .. + } => { + let Some(ws) = app.windows.get_mut(&window_id) else { + return; + }; + if ws.dirty && !ws.pending_close { + ws.pending_close = true; + let _ = ws.webview.evaluate_script( + "if(window.__mdPreviewSave)window.__mdPreviewSave();", + ); + } else if !ws.pending_close { + close_window(&mut app, window_id, control_flow); + } + } + TaoEvent::WindowEvent { + event: WindowEvent::Destroyed, + window_id, + .. + } => { + // The window may already be gone (closed by CloseRequested). + if !app.windows.contains_key(&window_id) { + return; + } + close_window(&mut app, window_id, control_flow); + } + _ => {} + } + }); +} diff --git a/src/main.rs b/src/main.rs index b2b8198..d482ed2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] +mod app; mod config; mod escape; mod files; @@ -11,136 +12,30 @@ mod session; #[cfg(test)] mod testutil; -#[cfg(test)] -use config::clamp_zoom; +use app::{ + build_startup_page, build_webview, load_window_icon, run_event_loop, AppState, EnhanceFlags, + Strings, UserEvent, WindowState, HLJS_EXTRA_LANGS, HLJS_JS, +}; use config::{ - centered_geom, config_dir, confirm_discard_unsaved, geom_visible, load_theme_choice, - load_window_geom, load_zoom, save_theme_choice, save_window_geom, save_zoom, - show_warning_dialog, ThemeChoice, -}; -use escape::{escape_js, html_escape_attr, html_escape_text}; -use files::{ - forget_recent_file, install_file_watcher, is_supported_document, load_recent_files, - local_document_path_from_url, normalize_new_markdown_path, remember_recent_file, - resolve_document_link, reveal_in_explorer, save_active_file, self_write_still_matches_disk, - should_protect_external_change, SelfWriteRecord, MAX_RECENT_FILES, + centered_geom, config_dir, geom_visible, load_theme_choice, load_window_geom, + show_warning_dialog, }; +use files::{is_supported_document, load_recent_files, SelfWriteRecord}; use session::DocumentSession; use std::collections::HashMap; use std::fs; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::Instant; -use tao::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}; -use tao::event::{Event as TaoEvent, WindowEvent}; -use tao::event_loop::{ - ControlFlow, EventLoop, EventLoopBuilder, EventLoopProxy, EventLoopWindowTarget, -}; -use tao::window::{Window, WindowBuilder, WindowId}; -use wry::{WebContext, WebView, WebViewBuilder}; +use tao::dpi::{LogicalPosition, LogicalSize}; +use tao::event_loop::{EventLoop, EventLoopBuilder}; +use tao::window::WindowBuilder; #[cfg(test)] use markdown::md_to_html; -use markdown::md_to_html_with_base; +#[cfg(test)] use page::build_page; -const ICON_BYTES: &[u8] = include_bytes!("../assets/icon.ico"); - -/// The page drives these over IPC today; the menu-style variants are kept for -/// keyboard paths that are not wired up on Windows yet (Ctrl+W/E/F, Quit). -#[allow(dead_code)] -#[derive(Debug)] -enum UserEvent { - NewFile(WindowId), - NewTab(WindowId), - OpenFile(WindowId), - OpenPaths(Option, Vec, bool), - 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 - ExternalChangeResolved(WindowId, bool), - FileSaved(WindowId, PathBuf), // our own save: refresh preview only, leave textarea cursor alone - SaveFailed(WindowId, PathBuf, String), - DirtyChanged(WindowId, bool), - ToggleEdit, - ShowFind, - Print(WindowId), // route print through wry's native API (WKWebView ignores window.print()) - SetTheme(ThemeChoice), - Quit, - RecentChanged, - Ready(WindowId), // first paint landed: inject hljs now; if bench mode, also exit -} - -struct WindowState { - webview: WebView, - window: Window, - session: Arc>, - last_self_write: Arc>>, - watcher: Arc>>, - enhance_flags: Arc>, - loaded_enhancers: EnhanceFlags, - page_ready: bool, - pending_launches: Vec<(Vec, bool)>, - pending_close: bool, - warned_external_change: Option, - pending_external_change: Option, - dirty: bool, - is_primary: bool, -} - -impl WindowState { - fn render_active( - &mut self, - recent_files: &Arc>>, - strings: &Strings, - ) -> bool { - let session = Arc::clone(&self.session); - let mut session = session.lock().unwrap(); - let dirty = render_active_document( - &self.webview, - &self.window, - &mut session, - recent_files, - &self.enhance_flags, - &mut self.loaded_enhancers, - strings, - ); - self.dirty = dirty; - dirty - } -} - -struct AppState { - windows: HashMap, - active_window: WindowId, - recent_files: Arc>>, - strings: Strings, - web_context: WebContext, -} - -impl AppState { - fn active_mut(&mut self) -> Option<&mut WindowState> { - let id = self.active_window; - self.windows.get_mut(&id) - } -} - -#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] -struct EnhanceFlags { - math: bool, - mermaid: bool, -} - -impl EnhanceFlags { - fn any(self) -> bool { - self.math || self.mermaid - } -} - fn is_help_arg(arg: &str) -> bool { arg == "-h" || arg == "--help" } @@ -152,873 +47,6 @@ fn print_help() { ); } -#[derive(Clone)] -struct Strings { - drop_hint: &'static str, - cannot_read: &'static str, - open_file: &'static str, - new_file: &'static str, - new_tab: &'static str, - home_tab: &'static str, - recent_title: &'static str, - missing_title: &'static str, - missing_body: &'static str, - locate_file: &'static str, - close_tab: &'static str, - cannot_save: &'static str, - btn_edit: &'static str, - 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, - btn_zoom_out: &'static str, - btn_zoom_reset: &'static str, - btn_zoom_in: &'static str, - search_placeholder: &'static str, - stat_words: &'static str, - stat_chars: &'static str, -} - -impl Strings { - /// The app ships a single English UI. There is deliberately no locale - /// detection, so the interface never mixes Chinese and English labels. - fn english() -> Self { - Strings { - drop_hint: "Drop a .md file here or press Cmd/Ctrl+O to open", - cannot_read: "Cannot read file", - open_file: "Open File", - new_file: "New File", - new_tab: "New Tab", - home_tab: "New Tab", - recent_title: "Recent", - missing_title: "File Moved or Deleted", - missing_body: "This tab is kept. Locate the file again or close the tab.", - locate_file: "Locate File", - close_tab: "Close Tab", - cannot_save: "This file could not be saved (read-only or locked). Continue and discard the unsaved changes?", - btn_edit: "Edit (Cmd/Ctrl+E)", - 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", - btn_zoom_out: "Zoom out (Cmd/Ctrl+-)", - btn_zoom_reset: "Reset zoom (Cmd/Ctrl+0)", - btn_zoom_in: "Zoom in (Cmd/Ctrl++)", - search_placeholder: "Find", - stat_words: "non-space", - stat_chars: "chars", - } - } -} - -// Embedded highlight.js + themes (offline) -const HLJS_JS: &str = include_str!("../assets/hljs/highlight.min.js"); -// Always-dark code blocks; app chrome still follows the system theme. -// Extra language pack(s) not in the `common` bundle. Each file -// ends with `hljs.registerLanguage(...)` and only works if evaluated -// in the same scope as the main bundle — we concat them into hljs-src. -const HLJS_EXTRA_LANGS: &str = concat!( - // Delphi / Pascal (aliases: dpr, dfm, pas, pascal) — user requested - include_str!("../assets/hljs/delphi.min.js"), -); -const KATEX_JS: &str = include_str!("../assets/katex/katex.min.js"); -const KATEX_CSS: &str = include_str!("../assets/katex/katex.inline.css"); -const MERMAID_JS: &str = include_str!("../assets/mermaid/mermaid.min.js"); -fn tabs_json(session: &DocumentSession) -> String { - let tabs = session - .tabs - .iter() - .map(|tab| { - // The page owns the New Tab label; rust only flags the kind. - let name = tab - .file_path() - .and_then(|path| path.file_name()) - .map(|name| name.to_string_lossy().to_string()) - .unwrap_or_default(); - let path = tab - .file_path() - .map(|path| path.to_string_lossy().to_string()) - .unwrap_or_default(); - serde_json::json!({ - "id": tab.id, - "name": name, - "path": path, - "home": tab.is_home(), - "active": session.active_id == Some(tab.id), - "missing": tab.missing, - "dirty": tab.dirty, - }) - }) - .collect::>(); - serde_json::to_string(&tabs).expect("tab state is serializable") -} - -fn missing_preview_html(tab_id: u64, path: &Path, s: &Strings) -> String { - format!( - r#"
!

{}

{}

{}
"#, - html_escape_text(s.missing_title), - html_escape_text(s.missing_body), - html_escape_text(&path.to_string_lossy()), - html_escape_text(s.locate_file), - html_escape_text(s.close_tab), - ) -} - -fn base_href_for_file(path: &Path) -> Option { - let dir = path.parent()?; - url::Url::from_directory_path(dir) - .ok() - .map(|url| url.to_string()) -} - -fn starts_mermaid_fence(line: &str) -> bool { - let trimmed = line.trim_start(); - let rest = trimmed - .strip_prefix("```") - .or_else(|| trimmed.strip_prefix("~~~")); - let Some(info) = rest else { - return false; - }; - let info = info.trim_start(); - info == "mermaid" - || info - .strip_prefix("mermaid") - .and_then(|s| s.chars().next()) - .map(|c| c.is_whitespace() || c == '{') - .unwrap_or(false) -} - -fn has_unescaped_at(s: &str, index: usize, needle: &str) -> bool { - if !s[index..].starts_with(needle) { - return false; - } - let mut backslashes = 0; - for b in s[..index].bytes().rev() { - if b == b'\\' { - backslashes += 1; - } else { - break; - } - } - backslashes % 2 == 0 -} - -fn has_unescaped_pair(s: &str, open: &str, close: &str) -> bool { - let mut pos = 0; - while let Some(rel) = s[pos..].find(open) { - let start = pos + rel; - if !has_unescaped_at(s, start, open) { - pos = start + open.len(); - continue; - } - let body_start = start + open.len(); - let mut search = body_start; - while let Some(close_rel) = s[search..].find(close) { - let close_at = search + close_rel; - if has_unescaped_at(s, close_at, close) { - return true; - } - search = close_at + close.len(); - } - pos = body_start; - } - false -} - -fn has_inline_dollar_math(s: &str) -> bool { - let bytes = s.as_bytes(); - let mut i = 0; - while i < bytes.len() { - if bytes[i] != b'$' || !has_unescaped_at(s, i, "$") { - i += 1; - continue; - } - if bytes.get(i + 1).copied() == Some(b'$') - || bytes - .get(i + 1) - .map(|b| b.is_ascii_whitespace()) - .unwrap_or(true) - { - i += 1; - continue; - } - let mut j = i + 1; - while j < bytes.len() { - if bytes[j] == b'$' - && has_unescaped_at(s, j, "$") - && bytes - .get(j.wrapping_sub(1)) - .map(|b| !b.is_ascii_whitespace()) - .unwrap_or(false) - { - return true; - } - j += 1; - } - i += 1; - } - false -} - -fn enhance_flags_for(md: &str) -> EnhanceFlags { - EnhanceFlags { - math: has_unescaped_pair(md, "$$", "$$") - || has_unescaped_pair(md, "\\[", "\\]") - || has_unescaped_pair(md, "\\(", "\\)") - || has_inline_dollar_math(md), - mermaid: md.lines().any(starts_mermaid_fence), - } -} - -fn build_enhancer_bootstrap(flags: EnhanceFlags, loaded: EnhanceFlags) -> Vec { - if !flags.any() { - return Vec::new(); - } - - let mut scripts = Vec::new(); - if flags.math && !loaded.math { - let mut js = String::from("(function(){\nif(!window.katex){\n"); - js.push_str(KATEX_JS); - js.push_str("\n;try{window.katex=katex;}catch(e){}\n}\n"); - js.push_str("if(window.__setKatexCss)window.__setKatexCss('"); - js.push_str(&escape_js(KATEX_CSS)); - js.push_str("');\n})();"); - scripts.push(js); - } - if flags.mermaid && !loaded.mermaid { - // Mermaid's standalone bundle expects global script scope. Keep it - // out of the function wrapper that is safe for KaTeX/highlight.js. - let mut js = String::with_capacity(MERMAID_JS.len() + 80); - js.push_str(MERMAID_JS); - js.push_str("\n;try{window.mermaid=mermaid;}catch(e){}\n"); - scripts.push(js); - } - scripts.push("if(window.__enhancePreview)window.__enhancePreview();".to_string()); - scripts -} - -fn home_preview_html(s: &Strings, recent_files: &[PathBuf]) -> String { - let empty_class = if recent_files.is_empty() { - "empty" - } else { - "empty has-recent" - }; - let mut html = format!( - r#"
#
{}
"#, - html_escape_text(s.drop_hint), - html_escape_text(s.open_file), - html_escape_attr(s.btn_new), - html_escape_text(s.new_file) - ); - - if !recent_files.is_empty() { - html.push_str(&format!( - r#"
{}
"#, - html_escape_text(s.recent_title) - )); - for (index, path) in recent_files.iter().take(MAX_RECENT_FILES).enumerate() { - let name = path - .file_name() - .map(|n| n.to_string_lossy()) - .unwrap_or_else(|| path.to_string_lossy()); - let parent = path - .parent() - .map(|p| p.to_string_lossy()) - .unwrap_or_default(); - html.push_str(&format!( - r#""#, - html_escape_text(&name), - html_escape_text(&parent) - )); - } - html.push_str("
"); - } - - html.push_str("
"); - html -} - -/// Decode embedded icon.ico to an RGBA tao Icon for the window chrome. -fn load_window_icon() -> Option { - let img = image::load_from_memory_with_format(ICON_BYTES, image::ImageFormat::Ico).ok()?; - let rgba = img.to_rgba8(); - let (w, h) = rgba.dimensions(); - tao::window::Icon::from_rgba(rgba.into_raw(), w, h).ok() -} - -fn find_open_path(app: &AppState, path: &Path) -> Option<(WindowId, u64)> { - let normalized = session::normalize_path(path.to_path_buf()); - for (window_id, ws) in &app.windows { - let session = ws.session.lock().unwrap(); - if let Some(tab) = session - .tabs - .iter() - .find(|tab| tab.path.as_deref() == Some(normalized.as_path())) - { - return Some((*window_id, tab.id)); - } - } - None -} - -fn focus_open_tab( - app: &mut AppState, - window_id: WindowId, - tab_id: u64, - recent_files: &Arc>>, - strings: &Strings, - proxy: &EventLoopProxy, -) -> bool { - let Some(ws) = app.windows.get_mut(&window_id) else { - return false; - }; - let mut session = ws.session.lock().unwrap(); - let target_active = session.active_id == Some(tab_id); - let active_dirty = session.active().map(|tab| tab.dirty).unwrap_or(false); - let target_dirty = session - .tabs - .iter() - .find(|tab| tab.id == tab_id) - .map(|tab| tab.dirty) - .unwrap_or(false); - if !target_active && (active_dirty || target_dirty) { - // Never switch away from or reload an unsaved tab just to focus it. - return false; - } - if !session.activate(tab_id) { - return false; - } - app.active_window = window_id; - ws.window.set_minimized(false); - ws.window.set_focus(); - if target_active { - update_tabs(&ws.webview, &session); - return true; - } - drop(session); - ws.render_active(recent_files, strings); - let path = ws - .session - .lock() - .unwrap() - .active_path() - .map(Path::to_path_buf); - install_file_watcher(&ws.watcher, proxy, &ws.last_self_write, window_id, path); - true -} - -fn update_tabs(webview: &WebView, session: &DocumentSession) { - let state = tabs_json(session); - let _ = webview.evaluate_script(&format!("if(window.__setTabs)window.__setTabs({state});")); -} - -fn update_window_title(window: &Window, session: &DocumentSession) { - let title = match session.active() { - Some(tab) => match tab.file_path() { - Some(path) => { - let name = path - .file_name() - .map(|name| name.to_string_lossy().to_string()) - .unwrap_or_else(|| path.to_string_lossy().to_string()); - format!("{}{} — MD Preview", if tab.dirty { "• " } else { "" }, name) - } - None => "MD Preview".to_string(), - }, - None => "MD Preview".to_string(), - }; - window.set_title(&title); -} - -fn render_home( - webview: &WebView, - window: &Window, - session: &DocumentSession, - recent_files: &Arc>>, - strings: &Strings, -) { - let html = home_preview_html(strings, &recent_files.lock().unwrap()); - let _ = webview.evaluate_script(&format!( - "if(window.__setEmptyPreview)window.__setEmptyPreview('{}');", - escape_js(&html) - )); - update_tabs(webview, session); - update_window_title(window, session); -} - -/// Build the `__setContent` call. -/// -/// The argument list must match the `window.__setContent` signature in -/// `assets/page/page.js`. Nothing type-checks this boundary: when the two -/// drift apart the page reads a wrong value as HTML (it once rendered the tab -/// id, so a white window showed "1", "2", "3" as tabs were opened). -fn set_content_script( - html: &str, - raw: &str, - base_href: &str, - flags: EnhanceFlags, - editing: bool, - scroll_ratio: f32, -) -> String { - format!( - "if(window.__setContent)window.__setContent('{}', '{}', '{}', {}, {}, {}, {});", - escape_js(html), - escape_js(raw), - escape_js(base_href), - flags.math, - flags.mermaid, - editing, - scroll_ratio - ) -} - -fn render_active_document( - webview: &WebView, - window: &Window, - session: &mut DocumentSession, - recent_files: &Arc>>, - enhance_flags: &Arc>, - loaded_enhancers: &mut EnhanceFlags, - strings: &Strings, -) -> bool { - let Some(active) = session.active().cloned() else { - render_home(webview, window, session, recent_files, strings); - return false; - }; - // Home tabs carry no file; they render the new-tab page. - let Some(path) = active.file_path().map(Path::to_path_buf) else { - render_home(webview, window, session, recent_files, strings); - return false; - }; - - match fs::read_to_string(&path) { - Ok(raw) => { - if let Some(tab) = session.get_mut(active.id) { - tab.missing = false; - } - remember_recent_file(recent_files, &path); - let html = md_to_html_with_base(&raw, path.parent()); - let base_href = base_href_for_file(&path).unwrap_or_default(); - let flags = enhance_flags_for(&raw); - *enhance_flags.lock().unwrap() = flags; - let _ = webview.evaluate_script(&set_content_script( - &html, - &raw, - &base_href, - flags, - active.editing, - active.scroll_ratio, - )); - for script in build_enhancer_bootstrap(flags, *loaded_enhancers) { - let _ = webview.evaluate_script(&script); - } - loaded_enhancers.math |= flags.math; - loaded_enhancers.mermaid |= flags.mermaid; - } - Err(error) if error.kind() == std::io::ErrorKind::NotFound => { - if let Some(tab) = session.get_mut(active.id) { - tab.missing = true; - } - if active.dirty { - show_warning_dialog( - strings.missing_title, - "The file disappeared while it still has unsaved edits. The editor content has been kept.", - ); - } else { - let html = missing_preview_html(active.id, &path, strings); - let _ = webview.evaluate_script(&format!( - "if(window.__setMissing)window.__setMissing('{}');", - escape_js(&html) - )); - } - } - Err(error) => { - if active.dirty { - show_warning_dialog(strings.cannot_read, &error.to_string()); - } else { - // A bad restored path must leave the window usable, without a - // modal dialog during startup or stale content from another tab. - let html = format!( - r#"

{}

{}

{}
"#, - html_escape_text(strings.cannot_read), - html_escape_text(&error.to_string()), - html_escape_text(&path.to_string_lossy()), - html_escape_text(strings.open_file), - active.id, - html_escape_text(strings.close_tab), - ); - let _ = webview.evaluate_script(&format!( - "if(window.__setMissing)window.__setMissing('{}');", - escape_js(&html) - )); - } - } - } - - let dirty = session.active().map(|tab| tab.dirty).unwrap_or(false); - update_tabs(webview, session); - update_window_title(window, session); - dirty -} - -// WebView2 NavigateToString has a 2 MiB limit. Never include document or -// persisted path data in this page; load the active tab after the ready IPC. -fn build_startup_page(strings: &Strings) -> String { - build_page( - &home_preview_html(strings, &[]), - "", - None, - EnhanceFlags::default(), - strings, - true, - ) -} - -#[allow(clippy::too_many_arguments)] // shared window plumbing; split with the webview module -fn build_webview( - window: &Window, - web_context: &mut WebContext, - window_id: WindowId, - session: Arc>, - last_self_write: Arc>>, - recent_files: Arc>>, - proxy: EventLoopProxy, - initial_page: String, -) -> Result { - let proxy_for_ipc = proxy.clone(); - let proxy_for_navigation = proxy.clone(); - let proxy_for_drag = proxy.clone(); - let builder = WebViewBuilder::with_web_context(web_context) - .with_html(&initial_page) - .with_navigation_handler(move |url: String| { - // Let wry load the initial in-memory document; route any real URL click - // to the app's tab model or the system default handler. - if url.starts_with("http://") - || url.starts_with("https://") - || url.starts_with("mailto:") - { - let _ = open::that(&url); - false - } else if let Some(path) = local_document_path_from_url(&url) { - let _ = proxy_for_navigation.send_event(UserEvent::OpenPaths( - Some(window_id), - vec![path], - false, - )); - false - } else { - !url.starts_with("file:") - } - }) - .with_ipc_handler(move |msg| { - let body = msg.body(); - if body == "new-file" { - let _ = proxy_for_ipc.send_event(UserEvent::NewFile(window_id)); - } else if body == "open" { - let _ = proxy_for_ipc.send_event(UserEvent::OpenFile(window_id)); - } else if let Some(index) = body.strip_prefix("open-recent:") { - if let Ok(index) = index.parse::() { - let path = recent_files.lock().unwrap().get(index).cloned(); - if let Some(path) = path { - if path.exists() { - let _ = proxy_for_ipc.send_event(UserEvent::OpenPaths( - Some(window_id), - vec![path], - false, - )); - } else if forget_recent_file(&recent_files, &path) { - let _ = proxy_for_ipc.send_event(UserEvent::RecentChanged); - } - } - } - } else if let Some(url) = body.strip_prefix("open-local-link:") { - let active_path = session.lock().unwrap().active_path().map(Path::to_path_buf); - if let Some(path) = resolve_document_link(url, active_path.as_deref()) { - let _ = proxy_for_ipc.send_event(UserEvent::OpenPaths( - Some(window_id), - vec![path], - false, - )); - } - } else if let Some(rest) = body.strip_prefix("tab-action:") { - let (header, pending_content) = rest - .split_once('\n') - .map(|(header, content)| (header, Some(content))) - .unwrap_or((rest, None)); - let mut parts = header.splitn(3, ':'); - let action = parts.next().unwrap_or(""); - let id = parts.next().and_then(|value| value.parse::().ok()); - // The page reports where the tab it is leaving was scrolled to. - let scroll_ratio = parts.next().and_then(|value| value.parse::().ok()); - let Some(id) = id else { - return; - }; - if let Some(ratio) = scroll_ratio { - session.lock().unwrap().set_active_scroll_ratio(ratio); - } - if let Some(content) = pending_content { - // A tab action is only safe once the pending edit is written. - if !save_active_file( - &session, - &last_self_write, - &proxy_for_ipc, - window_id, - content, - ) { - return; - } - } - match action { - "activate" => { - let _ = proxy_for_ipc.send_event(UserEvent::ActivateTab(window_id, id)); - } - "close" => { - let _ = proxy_for_ipc.send_event(UserEvent::CloseTab(window_id, id)); - } - "detach" => { - let _ = proxy_for_ipc.send_event(UserEvent::DetachTab(window_id, id)); - } - "new-tab" => { - let _ = proxy_for_ipc.send_event(UserEvent::NewTab(window_id)); - } - _ => {} - } - } else if let Some(id) = body.strip_prefix("locate-tab:") { - 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" { - let _ = proxy_for_ipc.send_event(UserEvent::DirtyChanged(window_id, false)); - } else if body == "external-change:dirty" { - let _ = - proxy_for_ipc.send_event(UserEvent::ExternalChangeResolved(window_id, true)); - } else if body == "external-change:clean" { - let _ = - proxy_for_ipc.send_event(UserEvent::ExternalChangeResolved(window_id, false)); - } else if body == "print" { - let _ = proxy_for_ipc.send_event(UserEvent::Print(window_id)); - } else if body == "ready" { - let _ = proxy_for_ipc.send_event(UserEvent::Ready(window_id)); - } else if let Some(percent) = body.strip_prefix("zoom:") { - if let Ok(percent) = percent.parse::() { - save_zoom(percent); - } - } else if body == "refresh" { - if let Some(path) = session.lock().unwrap().active_path().map(Path::to_path_buf) { - let _ = proxy_for_ipc.send_event(UserEvent::FileChanged(window_id, path)); - } - } else if let Some(content) = body.strip_prefix("save:") { - save_active_file( - &session, - &last_self_write, - &proxy_for_ipc, - window_id, - content, - ); - } else if let Some(rest) = body.strip_prefix("scroll:") { - if let Some((id, ratio)) = rest.split_once(':') { - if let (Ok(id), Ok(ratio)) = (id.parse::(), ratio.parse::()) { - session.lock().unwrap().set_tab_scroll_ratio(id, ratio); - } - } - } else if let Some(rest) = body.strip_prefix("edit-mode:") { - if let Some((id, mode)) = rest.split_once(':') { - if let Ok(id) = id.parse::() { - session.lock().unwrap().set_tab_editing(id, mode == "1"); - } - } - } - }) - .with_drag_drop_handler(move |event| { - if let wry::DragDropEvent::Drop { paths, .. } = event { - let paths = paths - .into_iter() - .filter(|path| is_supported_document(path)) - .collect::>(); - if !paths.is_empty() { - let _ = proxy_for_drag.send_event(UserEvent::OpenPaths( - Some(window_id), - paths, - false, - )); - } - } - true - }); - - // Wry supplies its own browser options, which can mask WebView2's - // environment override. Honor explicit diagnostic arguments only when set. - let builder = { - use wry::WebViewBuilderExtWindows; - match std::env::var("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS") { - Ok(arguments) => builder.with_additional_browser_args(&arguments), - Err(_) => builder, - } - }; - - let webview = builder.build(window); - - webview.map_err(|error| error.to_string()) -} - -const MAX_WINDOWS: usize = 16; - -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.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 + 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( - target: &EventLoopWindowTarget, - app: &mut AppState, - proxy: &EventLoopProxy, - initial_session: DocumentSession, - source_window_id: WindowId, -) -> Result { - if app.windows.len() >= MAX_WINDOWS { - return Err(format!( - "At most {MAX_WINDOWS} windows can be open at once." - )); - } - let source = app - .windows - .get(&source_window_id) - .or_else(|| app.windows.get(&app.active_window)) - .ok_or_else(|| "No active window.".to_string())?; - let (position, size) = secondary_geom(source); - let theme = load_theme_choice(); - let mut builder = WindowBuilder::new() - .with_title("MD Preview") - .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)); - } - let window = builder.build(target).map_err(|error| error.to_string())?; - let window_id = window.id(); - let page = build_startup_page(&app.strings); - let mut initial_session = initial_session; - if initial_session.tabs.is_empty() { - initial_session.open_home(); - } - let session = Arc::new(Mutex::new(initial_session)); - let last_self_write = Arc::new(Mutex::new(None)); - let recent_files = Arc::clone(&app.recent_files); - let webview = build_webview( - &window, - &mut app.web_context, - window_id, - Arc::clone(&session), - Arc::clone(&last_self_write), - recent_files, - proxy.clone(), - page, - )?; - let enhance_flags = Arc::new(Mutex::new(EnhanceFlags::default())); - let watcher = Arc::new(Mutex::new(None)); - app.windows.insert( - window_id, - WindowState { - webview, - window, - session, - last_self_write, - watcher, - enhance_flags, - loaded_enhancers: EnhanceFlags::default(), - page_ready: false, - pending_launches: Vec::new(), - pending_close: false, - warned_external_change: None, - pending_external_change: None, - dirty: false, - is_primary: false, - }, - ); - app.active_window = window_id; - if let Some(ws) = app.windows.get(&window_id) { - ws.window.set_focus(); - } - Ok(window_id) -} - -fn close_window(app: &mut AppState, window_id: WindowId, control_flow: &mut ControlFlow) { - let was_primary = app - .windows - .get(&window_id) - .map(|ws| ws.is_primary) - .unwrap_or(false); - if was_primary { - if let Some(ws) = app.windows.get(&window_id) { - save_window_geom(&ws.window); - } - } - app.windows.remove(&window_id); - if app.windows.is_empty() { - *control_flow = ControlFlow::Exit; - return; - } - if was_primary { - if let Some((_, ws)) = app.windows.iter_mut().next() { - ws.is_primary = true; - } - } - if app.active_window == window_id { - if let Some(next) = app.windows.keys().next().copied() { - app.active_window = next; - if let Some(ws) = app.windows.get(&next) { - ws.window.set_focus(); - } - } - } -} - fn main() { // Bench instrumentation: MD_PREVIEW_BENCH=1 makes the app print // cold-start timings to stderr and exit as soon as the first paint @@ -1181,7 +209,7 @@ fn main() { .active() .map(|tab| tab.dirty) .unwrap_or(false); - let mut app = AppState { + let app = AppState { windows: HashMap::from([( window_id, WindowState { @@ -1207,607 +235,18 @@ fn main() { web_context, }; - event_loop.run(move |event, target, control_flow| { - *control_flow = ControlFlow::Wait; - let strings = app.strings.clone(); - let recent_files = Arc::clone(&app.recent_files); - - match event { - TaoEvent::UserEvent(UserEvent::NewFile(window_id)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - let active_dirty = ws - .session - .lock() - .unwrap() - .active() - .map(|tab| tab.dirty) - .unwrap_or(false); - if active_dirty { - let _ = ws.webview.evaluate_script( - "if(window.__mdPreviewNewFile)window.__mdPreviewNewFile();", - ); - return; - } - let current_dir = ws - .session - .lock() - .unwrap() - .active() - .and_then(|tab| tab.file_path()) - .and_then(|path| path.parent().map(Path::to_path_buf)); - let mut dialog = rfd::FileDialog::new() - .add_filter("Markdown", &["md", "markdown", "mdown", "mkd"]) - .set_file_name(strings.new_filename); - if let Some(current_dir) = current_dir { - dialog = dialog.set_directory(current_dir); - } - if let Some(path) = dialog.save_file() { - let path = normalize_new_markdown_path(path); - match fs::write(&path, "") { - Ok(()) => { - let _ = proxy.send_event(UserEvent::OpenPaths( - Some(window_id), - vec![path], - true, - )); - } - Err(error) => { - show_warning_dialog("Could Not Create File", &error.to_string()); - } - } - } - } - TaoEvent::UserEvent(UserEvent::OpenFile(window_id)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - let active_dirty = ws - .session - .lock() - .unwrap() - .active() - .map(|tab| tab.dirty) - .unwrap_or(false); - if active_dirty { - let _ = ws.webview.evaluate_script( - "if(window.__mdPreviewOpenFile)window.__mdPreviewOpenFile();", - ); - return; - } - if let Some(paths) = rfd::FileDialog::new() - .add_filter("Markdown", &["md", "markdown", "mdown", "mkd"]) - .pick_files() - { - let _ = proxy.send_event(UserEvent::OpenPaths( - Some(window_id), - paths, - false, - )); - } - } - TaoEvent::UserEvent(UserEvent::NewTab(window_id)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - let mut session = ws.session.lock().unwrap(); - session.open_home(); - drop(session); - ws.render_active(&recent_files, &strings); - install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, None); - } - TaoEvent::UserEvent(UserEvent::OpenPaths(target, paths, edit_on_open)) => { - let target_window = target.unwrap_or(app.active_window); - let Some(ws) = app.windows.get_mut(&target_window) else { - return; - }; - if !ws.page_ready { - ws.pending_launches.push((paths, edit_on_open)); - return; - } - - let paths = paths - .into_iter() - .filter(|path| is_supported_document(path)) - .collect::>(); - if paths.is_empty() { - return; - } - for path in paths { - if let Some((window_id, tab_id)) = find_open_path(&app, &path) { - if !focus_open_tab( - &mut app, - window_id, - tab_id, - &recent_files, - &strings, - &proxy, - ) { - show_warning_dialog( - "Unsaved Changes", - "That file is open in another window with unsaved changes.", - ); - } - continue; - } - let Some(ws) = app.windows.get_mut(&target_window) else { - return; - }; - if !ws.page_ready { - 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); - if !preserve_active && session.active_is_home() { - session.open_reusing_home(path, edit_on_open); - } else { - session.open(path, edit_on_open); - } - if preserve_active { - if let Some(id) = previous_active { - session.activate(id); - } - } - if preserve_active { - update_tabs(&ws.webview, &session); - } else { - drop(session); - ws.render_active(&recent_files, &strings); - } - let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); - install_file_watcher( - &ws.watcher, - &proxy, - &ws.last_self_write, - target_window, - path, - ); - } - } - TaoEvent::UserEvent(UserEvent::ActivateTab(window_id, id)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - let mut session = ws.session.lock().unwrap(); - if session.activate(id) { - drop(session); - ws.render_active(&recent_files, &strings); - let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); - install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path); - } - } - TaoEvent::UserEvent(UserEvent::CloseTab(window_id, id)) => { - let multiple_windows = app.windows.len() > 1; - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - let mut session = ws.session.lock().unwrap(); - let Some(target) = session.tabs.iter().find(|tab| tab.id == id) else { - return; - }; - let was_active = session.active_id == Some(id); - let sole_tab = session.tabs.len() == 1; - let closing_home = target.is_home(); - if sole_tab { - if multiple_windows { - drop(session); - close_window(&mut app, window_id, control_flow); - return; - } - if closing_home { - // The last window always keeps one Home tab. - return; - } - // Closing the last file tab returns to the Home tab. - session.close_with_home_fallback(id); - drop(session); - ws.render_active(&recent_files, &strings); - install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, None); - return; - } - if session.close(id) { - if was_active { - drop(session); - ws.render_active(&recent_files, &strings); - let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); - install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path); - } else { - update_tabs(&ws.webview, &session); - } - } - } - TaoEvent::UserEvent(UserEvent::DetachTab(window_id, tab_id)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - let session = ws.session.lock().unwrap(); - let Some(tab) = session.tabs.iter().find(|tab| tab.id == tab_id).cloned() else { - return; - }; - if tab.is_home() { - return; - } - let target_active = session.active_id == Some(tab_id); - if !target_active && tab.dirty { - drop(session); - show_warning_dialog( - "Could Not Move Tab", - "Save this file before moving it to a new window.", - ); - return; - } - drop(session); - - let mut moved = tab; - moved.dirty = false; - moved.missing = false; - let new_session = DocumentSession::with_tab(moved); - let new_window_id = match create_window_with_session( - target, - &mut app, - &proxy, - new_session, - window_id, - ) { - Ok(id) => id, - Err(error) => { - show_warning_dialog("Could Not Open New Window", &error); - return; - } - }; - - let close_source; - { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - let mut session = ws.session.lock().unwrap(); - if session.detach(tab_id).is_none() { - drop(session); - close_window(&mut app, new_window_id, control_flow); - show_warning_dialog("Could Not Move Tab", "The tab is no longer available."); - return; - } - close_source = session.tabs.is_empty(); - if !close_source { - drop(session); - ws.render_active(&recent_files, &strings); - let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); - install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path); - } - } - if close_source { - 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) - .and_then(|tab| tab.file_path()) - .map(Path::to_path_buf) - }); - 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; - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - if ws.session.lock().unwrap().active_id.is_some() { - let _ = ws.webview.evaluate_script( - "if(window.__mdPreviewCloseActiveTab)window.__mdPreviewCloseActiveTab();", - ); - } else if multiple_windows { - close_window(&mut app, window_id, control_flow); - } - } - TaoEvent::UserEvent(UserEvent::LocateTab(window_id, id)) => { - if let Some(path) = rfd::FileDialog::new() - .add_filter("Markdown", &["md", "markdown", "mdown", "mkd"]) - .pick_file() - { - if let Some((other_id, other_tab)) = find_open_path(&app, &path) { - if !focus_open_tab( - &mut app, - other_id, - other_tab, - &recent_files, - &strings, - &proxy, - ) { - show_warning_dialog( - "Unsaved Changes", - "That file is open in another window with unsaved changes.", - ); - } - return; - } - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - let mut session = ws.session.lock().unwrap(); - if session.relocate(id, path) && session.activate(id) { - drop(session); - ws.render_active(&recent_files, &strings); - let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); - install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path); - } else { - show_warning_dialog("Already Open", "That file is already open in another tab."); - } - } - } - TaoEvent::UserEvent(UserEvent::FileChanged(window_id, path)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - if ws.session.lock().unwrap().active_path() == Some(path.as_path()) { - ws.pending_external_change = Some(path); - let _ = ws.webview.evaluate_script( - "if(window.__mdPreviewResolveExternalChange)window.__mdPreviewResolveExternalChange();", - ); - } - } - TaoEvent::UserEvent(UserEvent::ExternalChangeResolved(window_id, webview_dirty)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - let Some(path) = ws.pending_external_change.take() else { - return; - }; - if self_write_still_matches_disk(ws.last_self_write.lock().unwrap().as_ref(), &path) { - return; - } - let mut session = ws.session.lock().unwrap(); - if session.active_path() == Some(path.as_path()) { - let session_dirty = session.active().map(|tab| tab.dirty).unwrap_or(false); - if should_protect_external_change(webview_dirty, session_dirty) { - if let Some(tab) = session.active_mut() { - tab.dirty = true; - } - ws.dirty = true; - let _ = ws.webview.evaluate_script( - "if(window.__mdPreviewPauseAutosave)window.__mdPreviewPauseAutosave();", - ); - drop(session); - if ws.warned_external_change.as_ref() != Some(&path) { - show_warning_dialog( - "File Changed on Disk", - "Automatic saving is paused and your edits are still in the editor. Press Cmd/Ctrl+S to replace the disk version, or reopen the file to keep the external version.", - ); - ws.warned_external_change = Some(path); - } - return; - } - drop(session); - ws.render_active(&recent_files, &strings); - } - } - TaoEvent::UserEvent(UserEvent::FileSaved(window_id, path)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - if ws.warned_external_change.as_ref() == Some(&path) { - ws.warned_external_change = None; - } - let mut session = ws.session.lock().unwrap(); - let active_matches = session.active_path() == Some(path.as_path()); - if let Some(tab) = session - .tabs - .iter_mut() - .find(|tab| tab.path.as_deref() == Some(path.as_path())) - { - tab.dirty = false; - tab.missing = false; - } - if active_matches { - if let Ok(raw) = fs::read_to_string(&path) { - let html = md_to_html_with_base(&raw, path.parent()); - let flags = enhance_flags_for(&raw); - *ws.enhance_flags.lock().unwrap() = flags; - let _ = ws.webview.evaluate_script(&format!( - "if(window.__setPreview)window.__setPreview('{}', {}, {});if(window.__markSaved)window.__markSaved('{}');", - escape_js(&html), - flags.math, - flags.mermaid, - escape_js(&raw) - )); - for script in build_enhancer_bootstrap(flags, ws.loaded_enhancers) { - let _ = ws.webview.evaluate_script(&script); - } - ws.loaded_enhancers.math |= flags.math; - ws.loaded_enhancers.mermaid |= flags.mermaid; - } - } - ws.dirty = session.active().map(|tab| tab.dirty).unwrap_or(false); - update_tabs(&ws.webview, &session); - update_window_title(&ws.window, &session); - let pending_close = ws.pending_close; - drop(session); - if pending_close { - close_window(&mut app, window_id, control_flow); - } - } - TaoEvent::UserEvent(UserEvent::SaveFailed(window_id, _path, error)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - let _ = ws.webview.evaluate_script( - "if(window.__markSaveBlocked)window.__markSaveBlocked();", - ); - if ws.pending_close { - ws.pending_close = false; - if confirm_discard_unsaved(&error) { - close_window(&mut app, window_id, control_flow); - } - } else { - show_warning_dialog( - "Could Not Save", - &format!( - "{error}\n\nAutosave is paused for this file. Close the window to discard the unsaved changes." - ), - ); - } - } - TaoEvent::UserEvent(UserEvent::DirtyChanged(window_id, dirty)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - ws.dirty = dirty; - let mut session = ws.session.lock().unwrap(); - if let Some(tab) = session.active_mut() { - tab.dirty = dirty; - } - update_tabs(&ws.webview, &session); - update_window_title(&ws.window, &session); - } - TaoEvent::UserEvent(UserEvent::ToggleEdit) => { - let Some(ws) = app.active_mut() else { - return; - }; - let _ = ws.webview.evaluate_script( - "if(window.__mdPreviewToggleEdit)window.__mdPreviewToggleEdit();", - ); - } - TaoEvent::UserEvent(UserEvent::ShowFind) => { - let Some(ws) = app.active_mut() else { - return; - }; - let _ = ws - .webview - .evaluate_script("if(window.__mdPreviewShowFind)window.__mdPreviewShowFind();"); - } - TaoEvent::UserEvent(UserEvent::RecentChanged) => { - let html = home_preview_html(&strings, &recent_files.lock().unwrap()); - let js = format!( - "if(window.__setEmptyPreview)window.__setEmptyPreview('{}');", - escape_js(&html) - ); - for ws in app.windows.values() { - if ws.session.lock().unwrap().active_is_home() { - let _ = ws.webview.evaluate_script(&js); - } - } - } - TaoEvent::UserEvent(UserEvent::Print(window_id)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - let _ = ws.webview.print(); - } - TaoEvent::UserEvent(UserEvent::Quit) => { - let window_id = app.active_window; - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - if ws.dirty && !ws.pending_close { - ws.pending_close = true; - let _ = ws.webview.evaluate_script( - "if(window.__mdPreviewSave)window.__mdPreviewSave();", - ); - } else if !ws.pending_close { - if ws.is_primary { - save_window_geom(&ws.window); - } - *control_flow = ControlFlow::Exit; - } - } - TaoEvent::UserEvent(UserEvent::SetTheme(choice)) => { - save_theme_choice(choice); - for ws in app.windows.values() { - ws.window.set_theme(choice.tao_theme()); - } - } - TaoEvent::UserEvent(UserEvent::Ready(window_id)) => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - // First paint is on the screen; now push hljs into the page - // (kept out of first-paint HTML to keep it slim). Always do - // this, even in bench mode, so subsequent panes would still - // highlight — bench just exits right after measuring. - let _ = ws.webview.evaluate_script(&hljs_bootstrap); - let zoom = load_zoom(); - if zoom != 100 { - let _ = ws.webview.evaluate_script(&format!( - "window.__mdPreviewSetZoom && window.__mdPreviewSetZoom({zoom});" - )); - } - if !ws.page_ready { - ws.page_ready = true; - ws.render_active(&recent_files, &strings); - let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf); - install_file_watcher(&ws.watcher, &proxy, &ws.last_self_write, window_id, path); - } - for (paths, edit) in ws.pending_launches.drain(..) { - let _ = proxy.send_event(UserEvent::OpenPaths(Some(window_id), paths, edit)); - } - if bench { - eprintln!("[bench] +{}ms ready", t0.elapsed().as_millis()); - *control_flow = ControlFlow::Exit; - } - } - TaoEvent::WindowEvent { - event: WindowEvent::Focused(true), - window_id, - .. - } => { - if app.windows.contains_key(&window_id) { - app.active_window = window_id; - } - } - TaoEvent::WindowEvent { - event: WindowEvent::CloseRequested, - window_id, - .. - } => { - let Some(ws) = app.windows.get_mut(&window_id) else { - return; - }; - if ws.dirty && !ws.pending_close { - ws.pending_close = true; - let _ = ws.webview.evaluate_script( - "if(window.__mdPreviewSave)window.__mdPreviewSave();", - ); - } else if !ws.pending_close { - close_window(&mut app, window_id, control_flow); - } - } - TaoEvent::WindowEvent { - event: WindowEvent::Destroyed, - window_id, - .. - } => { - // The window may already be gone (closed by CloseRequested). - if !app.windows.contains_key(&window_id) { - return; - } - close_window(&mut app, window_id, control_flow); - } - _ => {} - } - }); + run_event_loop(event_loop, app, proxy, hljs_bootstrap, bench, t0); } #[cfg(test)] mod tests { use super::*; + use crate::app::{ + base_href_for_file, clamp_secondary_position, home_preview_html, set_content_script, + tabs_json, EnhanceFlags, Strings, + }; + use crate::config::{clamp_zoom, ThemeChoice}; + use crate::markdown::md_to_html_with_base; use crate::testutil::temp_dir as temp_test_dir; #[test]