diff --git a/Cargo.lock b/Cargo.lock index 0ca0f4e..a122cd0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1676,9 +1676,6 @@ version = "1.4.2" dependencies = [ "image", "notify", - "objc2", - "objc2-app-kit", - "objc2-foundation", "open", "pulldown-cmark", "rfd", diff --git a/Cargo.toml b/Cargo.toml index df1ee90..8570286 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,11 +19,6 @@ url = "2" [target.'cfg(windows)'.dependencies] winreg = "0.52" -[target.'cfg(target_os = "macos")'.dependencies] -objc2 = "0.6.4" -objc2-app-kit = { version = "0.3.2", default-features = false, features = ["NSAlert", "NSApplication", "NSButton", "NSCell", "NSControl", "NSEvent", "NSImage", "NSMenu", "NSMenuItem", "NSResponder", "NSView"] } -objc2-foundation = { version = "0.3.2", default-features = false, features = ["objc2-core-foundation", "NSString"] } - [target.'cfg(windows)'.build-dependencies] winresource = "0.1" diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..9b67c30 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,212 @@ +//! User data paths, persisted window/zoom/theme state, and the blocking dialogs. + +use std::fs; +use std::path::PathBuf; +use tao::event_loop::EventLoop; +use tao::window::{Theme, Window}; + +// Window defaults, in logical pixels. +pub const DEFAULT_W: f64 = 900.0; +pub const DEFAULT_H: f64 = 700.0; + +use crate::UserEvent; + +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum ThemeChoice { + #[default] + System, + Light, + Dark, +} + +impl ThemeChoice { + pub fn as_str(self) -> &'static str { + match self { + ThemeChoice::System => "system", + ThemeChoice::Light => "light", + ThemeChoice::Dark => "dark", + } + } + + pub fn from_str(value: &str) -> Self { + match value.trim().to_ascii_lowercase().as_str() { + "light" => ThemeChoice::Light, + "dark" => ThemeChoice::Dark, + _ => ThemeChoice::System, + } + } + + pub fn tao_theme(self) -> Option { + match self { + ThemeChoice::System => None, + ThemeChoice::Light => Some(Theme::Light), + ThemeChoice::Dark => Some(Theme::Dark), + } + } +} + +pub fn config_dir() -> PathBuf { + if let Some(path) = std::env::var_os("MD_PREVIEW_CONFIG_DIR") { + return PathBuf::from(path); + } + std::env::var_os("LOCALAPPDATA") + .or_else(|| std::env::var_os("APPDATA")) + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from(".")) + .join("md-preview") +} + +#[derive(Copy, Clone)] +pub struct WindowGeom { + pub x: f64, + pub y: f64, + pub w: f64, + pub h: f64, +} + +pub fn geom_path() -> PathBuf { + config_dir().join("window.geom") +} + +pub fn theme_path() -> PathBuf { + config_dir().join("theme.txt") +} + +pub fn load_theme_choice() -> ThemeChoice { + fs::read_to_string(theme_path()) + .map(|raw| ThemeChoice::from_str(&raw)) + .unwrap_or_default() +} + +pub fn save_theme_choice(choice: ThemeChoice) { + let dir = config_dir(); + let _ = fs::create_dir_all(&dir); + let _ = fs::write(dir.join("theme.txt"), choice.as_str()); +} + +const ZOOM_MIN: u32 = 50; +const ZOOM_MAX: u32 = 300; + +pub fn zoom_path() -> PathBuf { + config_dir().join("zoom.txt") +} + +pub fn clamp_zoom(percent: u32) -> u32 { + percent.clamp(ZOOM_MIN, ZOOM_MAX) +} + +pub fn load_zoom() -> u32 { + fs::read_to_string(zoom_path()) + .ok() + .and_then(|raw| raw.trim().parse::().ok()) + .map(clamp_zoom) + .unwrap_or(100) +} + +pub fn save_zoom(percent: u32) { + let dir = config_dir(); + let _ = fs::create_dir_all(&dir); + let _ = fs::write(zoom_path(), clamp_zoom(percent).to_string()); +} + +pub fn show_warning_dialog(title: &str, description: &str) { + let _ = rfd::MessageDialog::new() + .set_level(rfd::MessageLevel::Warning) + .set_title(title) + .set_description(description) + .show(); +} + +pub fn confirm_discard_unsaved(error: &str) -> bool { + matches!( + rfd::MessageDialog::new() + .set_level(rfd::MessageLevel::Warning) + .set_title("Could Not Save") + .set_description(format!( + "{error}\n\nThe file may be read-only or locked by another program. Close the window and discard the unsaved changes?" + )) + .set_buttons(rfd::MessageButtons::OkCancel) + .show(), + rfd::MessageDialogResult::Ok + ) +} + +pub fn load_window_geom() -> Option { + let txt = fs::read_to_string(geom_path()).ok()?; + let parts: Vec<&str> = txt.trim().split(',').collect(); + if parts.len() != 4 { + return None; + } + Some(WindowGeom { + x: parts[0].parse().ok()?, + y: parts[1].parse().ok()?, + w: parts[2].parse().ok()?, + h: parts[3].parse().ok()?, + }) +} + +pub fn save_window_geom(window: &Window) { + let Ok(pos) = window.outer_position() else { + return; + }; + let scale = window.scale_factor(); + let size = window.inner_size(); + let geom = WindowGeom { + x: pos.x as f64 / scale, + y: pos.y as f64 / scale, + w: size.width as f64 / scale, + h: size.height as f64 / scale, + }; + if geom.w < 200.0 || geom.h < 150.0 { + return; + } + let dir = config_dir(); + let _ = fs::create_dir_all(&dir); + let _ = fs::write( + dir.join("window.geom"), + format!("{},{},{},{}", geom.x, geom.y, geom.w, geom.h), + ); +} + +/// Return the saved geometry only when its center still falls inside +/// some connected monitor — prevents the window from landing off-screen +/// after a display swap. +pub fn geom_visible(geom: &WindowGeom, event_loop: &EventLoop) -> bool { + let cx = geom.x + geom.w / 2.0; + let cy = geom.y + geom.h / 2.0; + event_loop.available_monitors().any(|mon| { + let scale = mon.scale_factor(); + let mp = mon.position(); + let ms = mon.size(); + let mx = mp.x as f64 / scale; + let my = mp.y as f64 / scale; + let mw = ms.width as f64 / scale; + let mh = ms.height as f64 / scale; + cx >= mx && cx <= mx + mw && cy >= my && cy <= my + mh + }) +} + +pub fn centered_geom(event_loop: &EventLoop) -> WindowGeom { + if let Some(mon) = event_loop.primary_monitor() { + let scale = mon.scale_factor(); + let mp = mon.position(); + let ms = mon.size(); + let mx = mp.x as f64 / scale; + let my = mp.y as f64 / scale; + let mw = ms.width as f64 / scale; + let mh = ms.height as f64 / scale; + WindowGeom { + x: mx + (mw - DEFAULT_W) / 2.0, + y: my + (mh - DEFAULT_H) / 2.0, + w: DEFAULT_W, + h: DEFAULT_H, + } + } else { + WindowGeom { + x: 100.0, + y: 100.0, + w: DEFAULT_W, + h: DEFAULT_H, + } + } +} diff --git a/src/main.rs b/src/main.rs index 251856e..d63faa3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,14 +1,19 @@ -#![cfg_attr( - all(target_os = "windows", not(debug_assertions)), - windows_subsystem = "windows" -)] +#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] +mod config; mod escape; mod instance; mod markdown; mod page; mod session; +#[cfg(test)] +use config::clamp_zoom; +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 notify::{Event, RecursiveMode, Watcher}; use session::DocumentSession; @@ -22,7 +27,7 @@ use tao::event::{Event as TaoEvent, WindowEvent}; use tao::event_loop::{ ControlFlow, EventLoop, EventLoopBuilder, EventLoopProxy, EventLoopWindowTarget, }; -use tao::window::{Theme, Window, WindowBuilder, WindowId}; +use tao::window::{Window, WindowBuilder, WindowId}; use wry::{WebContext, WebView, WebViewBuilder}; #[cfg(test)] @@ -31,8 +36,6 @@ use markdown::md_to_html_with_base; use page::build_page; const ICON_BYTES: &[u8] = include_bytes!("../assets/icon.ico"); -const DEFAULT_W: f64 = 900.0; -const DEFAULT_H: f64 = 700.0; #[derive(Debug)] struct SelfWriteRecord { @@ -40,9 +43,9 @@ struct SelfWriteRecord { content: String, } -/// Menu-only events exist for macOS; on Windows the page drives the same -/// actions over IPC, so those variants are never constructed here. -#[cfg_attr(not(target_os = "macos"), allow(dead_code))] +/// 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), @@ -123,40 +126,6 @@ impl AppState { } } -#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] -enum ThemeChoice { - #[default] - System, - Light, - Dark, -} - -impl ThemeChoice { - fn as_str(self) -> &'static str { - match self { - ThemeChoice::System => "system", - ThemeChoice::Light => "light", - ThemeChoice::Dark => "dark", - } - } - - fn from_str(value: &str) -> Self { - match value.trim().to_ascii_lowercase().as_str() { - "light" => ThemeChoice::Light, - "dark" => ThemeChoice::Dark, - _ => ThemeChoice::System, - } - } - - fn tao_theme(self) -> Option { - match self { - ThemeChoice::System => None, - ThemeChoice::Light => Some(Theme::Light), - ThemeChoice::Dark => Some(Theme::Dark), - } - } -} - #[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] struct EnhanceFlags { math: bool, @@ -245,182 +214,6 @@ impl Strings { } } -fn config_dir() -> PathBuf { - if let Some(path) = std::env::var_os("MD_PREVIEW_CONFIG_DIR") { - return PathBuf::from(path); - } - #[cfg(target_os = "windows")] - { - std::env::var_os("LOCALAPPDATA") - .or_else(|| std::env::var_os("APPDATA")) - .map(PathBuf::from) - .unwrap_or_else(|| PathBuf::from(".")) - .join("md-preview") - } - #[cfg(not(target_os = "windows"))] - { - std::env::var_os("HOME") - .map(PathBuf::from) - .unwrap_or_default() - .join(".config/md-preview") - } -} - -#[derive(Copy, Clone)] -struct WindowGeom { - x: f64, - y: f64, - w: f64, - h: f64, -} - -fn geom_path() -> PathBuf { - config_dir().join("window.geom") -} - -fn theme_path() -> PathBuf { - config_dir().join("theme.txt") -} - -fn load_theme_choice() -> ThemeChoice { - fs::read_to_string(theme_path()) - .map(|raw| ThemeChoice::from_str(&raw)) - .unwrap_or_default() -} - -fn save_theme_choice(choice: ThemeChoice) { - let dir = config_dir(); - let _ = fs::create_dir_all(&dir); - let _ = fs::write(dir.join("theme.txt"), choice.as_str()); -} - -const ZOOM_MIN: u32 = 50; -const ZOOM_MAX: u32 = 300; - -fn zoom_path() -> PathBuf { - config_dir().join("zoom.txt") -} - -fn clamp_zoom(percent: u32) -> u32 { - percent.clamp(ZOOM_MIN, ZOOM_MAX) -} - -fn load_zoom() -> u32 { - fs::read_to_string(zoom_path()) - .ok() - .and_then(|raw| raw.trim().parse::().ok()) - .map(clamp_zoom) - .unwrap_or(100) -} - -fn save_zoom(percent: u32) { - let dir = config_dir(); - let _ = fs::create_dir_all(&dir); - let _ = fs::write(zoom_path(), clamp_zoom(percent).to_string()); -} - -fn show_warning_dialog(title: &str, description: &str) { - let _ = rfd::MessageDialog::new() - .set_level(rfd::MessageLevel::Warning) - .set_title(title) - .set_description(description) - .show(); -} - -fn confirm_discard_unsaved(error: &str) -> bool { - matches!( - rfd::MessageDialog::new() - .set_level(rfd::MessageLevel::Warning) - .set_title("Could Not Save") - .set_description(format!( - "{error}\n\nThe file may be read-only or locked by another program. Close the window and discard the unsaved changes?" - )) - .set_buttons(rfd::MessageButtons::OkCancel) - .show(), - rfd::MessageDialogResult::Ok - ) -} - -fn load_window_geom() -> Option { - let txt = fs::read_to_string(geom_path()).ok()?; - let parts: Vec<&str> = txt.trim().split(',').collect(); - if parts.len() != 4 { - return None; - } - Some(WindowGeom { - x: parts[0].parse().ok()?, - y: parts[1].parse().ok()?, - w: parts[2].parse().ok()?, - h: parts[3].parse().ok()?, - }) -} - -fn save_window_geom(window: &Window) { - let Ok(pos) = window.outer_position() else { - return; - }; - let scale = window.scale_factor(); - let size = window.inner_size(); - let geom = WindowGeom { - x: pos.x as f64 / scale, - y: pos.y as f64 / scale, - w: size.width as f64 / scale, - h: size.height as f64 / scale, - }; - if geom.w < 200.0 || geom.h < 150.0 { - return; - } - let dir = config_dir(); - let _ = fs::create_dir_all(&dir); - let _ = fs::write( - dir.join("window.geom"), - format!("{},{},{},{}", geom.x, geom.y, geom.w, geom.h), - ); -} - -/// Return the saved geometry only when its center still falls inside -/// some connected monitor — prevents the window from landing off-screen -/// after a display swap. -fn geom_visible(geom: &WindowGeom, event_loop: &EventLoop) -> bool { - let cx = geom.x + geom.w / 2.0; - let cy = geom.y + geom.h / 2.0; - event_loop.available_monitors().any(|mon| { - let scale = mon.scale_factor(); - let mp = mon.position(); - let ms = mon.size(); - let mx = mp.x as f64 / scale; - let my = mp.y as f64 / scale; - let mw = ms.width as f64 / scale; - let mh = ms.height as f64 / scale; - cx >= mx && cx <= mx + mw && cy >= my && cy <= my + mh - }) -} - -fn centered_geom(event_loop: &EventLoop) -> WindowGeom { - if let Some(mon) = event_loop.primary_monitor() { - let scale = mon.scale_factor(); - let mp = mon.position(); - let ms = mon.size(); - let mx = mp.x as f64 / scale; - let my = mp.y as f64 / scale; - let mw = ms.width as f64 / scale; - let mh = ms.height as f64 / scale; - WindowGeom { - x: mx + (mw - DEFAULT_W) / 2.0, - y: my + (mh - DEFAULT_H) / 2.0, - w: DEFAULT_W, - h: DEFAULT_H, - } - } else { - WindowGeom { - x: 100.0, - y: 100.0, - w: DEFAULT_W, - h: DEFAULT_H, - } - } -} - // 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. @@ -733,764 +526,6 @@ fn event_should_reload_file(ev: &Event, target: &Path) -> bool { .any(|event_path| event_path_matches_file(event_path, target)) } -#[cfg(test)] -mod tests { - use super::*; - use notify::EventKind; - use std::time::{SystemTime, UNIX_EPOCH}; - - fn temp_test_dir(name: &str) -> PathBuf { - let unique = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_nanos(); - let dir = - std::env::temp_dir().join(format!("md-preview-{name}-{}-{unique}", std::process::id())); - fs::create_dir_all(&dir).unwrap(); - dir - } - - #[test] - fn large_document_startup_stays_below_webview2_html_limit() { - let dir = temp_test_dir("startup-large"); - let file = dir.join("中文 large.md"); - fs::write(&file, "x".repeat(3 * 1024 * 1024)).unwrap(); - let mut session = DocumentSession::default(); - session.open(file, true); - let page = build_startup_page(&Strings::english()); - assert!( - page.len() < 2 * 1024 * 1024, - "startup HTML has {} bytes", - page.len() - ); - assert!(session.active().unwrap().editing); - fs::remove_dir_all(dir).unwrap(); - } - - #[test] - fn dollar_math_is_protected_from_markdown_escapes() { - let html = md_to_html(r"$\{x\}$"); - - assert!(html.contains(r#"\{x\}"#)); - } - - #[test] - fn dollar_math_is_protected_from_markdown_emphasis() { - let html = md_to_html(r"$\bar{\mu}_{n}$ and $x_{n}$"); - - assert!(html.contains(r#"\bar{\mu}_{n}"#)); - assert!(html.contains(r#"x_{n}"#)); - assert!(!html.contains("")); - } - - #[test] - fn multiline_display_math_is_not_split_by_hard_breaks() { - let html = md_to_html("$$\na + b\n$$"); - - assert!(html.contains(r#"class="math math-display""#), "{html}"); - assert!(html.contains("a + b"), "{html}"); - assert!(!html.contains("
"), "{html}"); - } - - #[test] - fn github_alerts_render_as_markdown_alert_blockquotes() { - let html = md_to_html("> [!IMPORTANT]\n> This is an alert"); - - assert!(html.contains(r#"
"#)); - assert!(html.contains("

This is an alert

")); - assert!(!html.contains("[!IMPORTANT]")); - } - - #[test] - fn soft_breaks_render_as_hard_breaks_in_paragraphs() { - let html = md_to_html("2.1 默认只读讨论。\n2.2 默认工作流:先读代码。"); - - assert!( - html.contains("2.1 默认只读讨论。
\n2.2 默认工作流"), - "{html}" - ); - } - - #[test] - fn blank_lines_still_create_paragraphs() { - let html = md_to_html("first line\n\nsecond line"); - - assert_eq!(html.matches("

").count(), 2, "{html}"); - assert!(!html.contains("
"), "{html}"); - } - - #[test] - fn soft_breaks_inside_headings_stay_soft() { - let html = md_to_html("First heading line\nsecond heading line\n==="); - - assert!(html.contains(""), "{html}"); - } - - #[test] - fn soft_breaks_in_list_items_become_hard_breaks() { - let html = md_to_html("- first line\n second line"); - - assert!(html.contains("

  • first line
    "), "{html}"); - assert!(html.contains("second line
  • "), "{html}"); - } - - #[test] - fn code_blocks_keep_newlines_without_br() { - let html = md_to_html("~~~text\nline one\nline two\n~~~"); - - assert!(!html.contains("
    "), "{html}"); - assert!(html.contains("line one\nline two"), "{html}"); - } - - #[test] - fn gfm_footnotes_render_reference_and_definition() { - let html = md_to_html("Text with a note[^1].\n\n[^1]: The footnote body."); - - assert!(html.contains(r#"class="footnote-reference""#), "{html}"); - assert!(html.contains(r#"class="footnote-definition""#), "{html}"); - assert!(html.contains("The footnote body."), "{html}"); - } - - #[test] - fn definition_lists_render_as_dl_dt_dd() { - let html = md_to_html("Term\n: Definition"); - - assert!(html.contains("
    "), "{html}"); - assert!(html.contains("
    Term
    "), "{html}"); - assert!(html.contains("
    Definition
    "), "{html}"); - } - - #[test] - fn utf8_bom_is_ignored_before_heading_and_front_matter() { - let heading = md_to_html("\u{feff}# BOM heading"); - assert!( - heading.contains(r#"

    BOM heading

    "#), - "{heading}" - ); - - let front_matter = md_to_html("\u{feff}---\ntitle: BOM\n---\n# Body"); - assert!( - front_matter.contains(r#"class="front-matter""#), - "{front_matter}" - ); - assert!(front_matter.contains("title: BOM"), "{front_matter}"); - assert!( - front_matter.contains(r#"

    Body

    "#), - "{front_matter}" - ); - } - - #[test] - fn double_equals_highlight_renders_mark_without_touching_code() { - let html = md_to_html("Use ==highlight & tag== here and `==literal==` there."); - - assert!(html.contains(r#"Use highlight & tag here"#)); - assert!(html.contains("==literal==")); - } - - #[test] - fn fenced_code_blocks_keep_double_equals_literal() { - let html = md_to_html("```csharp\nif (m_Profile == null) {\n return a == b;\n}\n```"); - - assert!( - html.contains("m_Profile == null"), - "comparison must stay literal" - ); - assert!( - html.contains("a == b"), - "every comparison must be preserved" - ); - assert!( - !html.contains("mdp-mark"), - "code blocks must not get highlight markup" - ); - } - - #[test] - fn base_href_is_a_directory_file_url() { - let dir = temp_test_dir("base-href"); - let file = dir.join("note.md"); - fs::write(&file, "# x").unwrap(); - - let href = base_href_for_file(&file).unwrap(); - - assert!(href.starts_with("file:///"), "{href}"); - assert!(href.ends_with('/'), "{href}"); - assert!(!href.contains("%3F"), "{href}"); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn local_relative_images_are_embedded_from_markdown_directory() { - let dir = temp_test_dir("local-image"); - let assets = dir.join("assets"); - fs::create_dir_all(&assets).unwrap(); - fs::write(assets.join("pixel.png"), b"abc").unwrap(); - - let html = md_to_html_with_base("![pixel](assets/pixel.png)", Some(&dir)); - - assert!(html.contains(r#"pixel"#)); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn local_relative_images_keep_original_src_when_unreadable() { - let dir = temp_test_dir("missing-image"); - - let html = md_to_html_with_base("![missing](assets/missing.png)", Some(&dir)); - - assert!(html.contains(r#"missing"#)); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn local_relative_images_do_not_embed_parent_traversal() { - let dir = temp_test_dir("traversal-image"); - - let html = md_to_html_with_base("![secret](../secret.png)", Some(&dir)); - - assert!(html.contains(r#"secret"#)); - assert!(!html.contains("data:image/png")); - let _ = fs::remove_dir_all(dir); - } - - #[test] - fn yaml_front_matter_keeps_metadata_readable_without_blank_lines() { - let html = md_to_html( - "---\nname: skill-creator-lite\ndescription: Skill 创建封装工具。\n---\n# Body", - ); - - assert!(html.contains(r#"