- Remove locale detection and the Chinese Strings set - Label the new-tab page New Tab instead of Home - Use Untitled defaults for Finder-created files - Drop the sys-locale dependency
5287 lines
195 KiB
Rust
5287 lines
195 KiB
Rust
#![cfg_attr(
|
||
all(target_os = "windows", not(debug_assertions)),
|
||
windows_subsystem = "windows"
|
||
)]
|
||
|
||
mod instance;
|
||
mod session;
|
||
|
||
use notify::{Event, RecursiveMode, Watcher};
|
||
use pulldown_cmark::{html, CowStr, Event as MdEvent, Options, Parser, Tag, TagEnd};
|
||
use session::DocumentSession;
|
||
use std::collections::HashMap;
|
||
use std::fs;
|
||
use std::path::Component;
|
||
use std::path::{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::{Theme, Window, WindowBuilder, WindowId};
|
||
use wry::{WebContext, WebView, WebViewBuilder};
|
||
|
||
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 {
|
||
path: PathBuf,
|
||
content: String,
|
||
}
|
||
|
||
#[derive(Debug)]
|
||
enum UserEvent {
|
||
NewFile(WindowId),
|
||
NewTab(WindowId),
|
||
OpenFile(WindowId),
|
||
OpenPaths(Option<WindowId>, Vec<PathBuf>, 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<Mutex<DocumentSession>>,
|
||
last_self_write: Arc<Mutex<Option<SelfWriteRecord>>>,
|
||
watcher: Arc<Mutex<Option<notify::RecommendedWatcher>>>,
|
||
enhance_flags: Arc<Mutex<EnhanceFlags>>,
|
||
loaded_enhancers: EnhanceFlags,
|
||
page_ready: bool,
|
||
pending_launches: Vec<(Vec<PathBuf>, bool)>,
|
||
pending_close: bool,
|
||
warned_external_change: Option<PathBuf>,
|
||
pending_external_change: Option<PathBuf>,
|
||
dirty: bool,
|
||
is_primary: bool,
|
||
}
|
||
|
||
impl WindowState {
|
||
fn render_active(
|
||
&mut self,
|
||
recent_files: &Arc<Mutex<Vec<PathBuf>>>,
|
||
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<WindowId, WindowState>,
|
||
active_window: WindowId,
|
||
recent_files: Arc<Mutex<Vec<PathBuf>>>,
|
||
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)]
|
||
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<Theme> {
|
||
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,
|
||
mermaid: bool,
|
||
}
|
||
|
||
impl EnhanceFlags {
|
||
fn any(self) -> bool {
|
||
self.math || self.mermaid
|
||
}
|
||
}
|
||
|
||
fn is_help_arg(arg: &str) -> bool {
|
||
arg == "-h" || arg == "--help"
|
||
}
|
||
|
||
fn print_help() {
|
||
println!(
|
||
"MD Preview {}\n\nUsage:\n md-preview [file.md]\n\nOptions:\n -h, --help Show this help message",
|
||
env!("CARGO_PKG_VERSION")
|
||
);
|
||
}
|
||
|
||
#[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",
|
||
}
|
||
}
|
||
}
|
||
|
||
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::<u32>().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<WindowGeom> {
|
||
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<UserEvent>) -> 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<UserEvent>) -> 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,
|
||
}
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
fn md_to_html(md: &str) -> String {
|
||
md_to_html_with_base(md, None)
|
||
}
|
||
|
||
fn md_to_html_with_base(md: &str, base_dir: Option<&Path>) -> String {
|
||
// A UTF-8 BOM is legal in files but not part of Markdown syntax. Strip it
|
||
// before front-matter detection so both `---` metadata and a leading
|
||
// heading still parse.
|
||
let md = md.strip_prefix('\u{feff}').unwrap_or(md);
|
||
let (front_matter, markdown) = split_yaml_front_matter(md)
|
||
.map(|(metadata, body)| (Some(metadata), body))
|
||
.unwrap_or((None, md));
|
||
let opts = Options::ENABLE_TABLES
|
||
| Options::ENABLE_STRIKETHROUGH
|
||
| Options::ENABLE_TASKLISTS
|
||
| Options::ENABLE_HEADING_ATTRIBUTES
|
||
| Options::ENABLE_MATH
|
||
| Options::ENABLE_GFM
|
||
| Options::ENABLE_FOOTNOTES
|
||
| Options::ENABLE_DEFINITION_LIST;
|
||
let parser = Parser::new_ext(markdown, opts);
|
||
let events = render_softbreaks_as_hard(embed_local_images(
|
||
add_mark_highlights(add_heading_ids(parser.collect())),
|
||
base_dir,
|
||
));
|
||
let mut html_out = String::new();
|
||
if let Some(metadata) = front_matter {
|
||
html_out.push_str(r#"<aside class="front-matter"><pre>"#);
|
||
html_out.push_str(&html_escape_text(metadata.trim_end_matches(['\r', '\n'])));
|
||
html_out.push_str("</pre></aside>\n");
|
||
}
|
||
html::push_html(&mut html_out, events.into_iter());
|
||
html_out
|
||
}
|
||
|
||
/// AI-generated Markdown often uses a single newline as a visual line break.
|
||
/// Treat those soft breaks as hard breaks in normal prose, but keep headings
|
||
/// untouched: a multi-line setext heading should stay one visual line.
|
||
fn render_softbreaks_as_hard<'a>(events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
|
||
let mut heading_depth = 0usize;
|
||
let mut out = Vec::with_capacity(events.len());
|
||
for event in events {
|
||
match &event {
|
||
MdEvent::Start(Tag::Heading { .. }) => heading_depth += 1,
|
||
MdEvent::End(TagEnd::Heading(_)) => {
|
||
heading_depth = heading_depth.saturating_sub(1);
|
||
}
|
||
MdEvent::SoftBreak if heading_depth == 0 => {
|
||
out.push(MdEvent::HardBreak);
|
||
continue;
|
||
}
|
||
_ => {}
|
||
}
|
||
out.push(event);
|
||
}
|
||
out
|
||
}
|
||
|
||
fn split_yaml_front_matter(md: &str) -> Option<(&str, &str)> {
|
||
let mut lines = md.split_inclusive('\n');
|
||
let first = lines.next()?;
|
||
if first.trim_end_matches(['\r', '\n']) != "---" {
|
||
return None;
|
||
}
|
||
|
||
let metadata_start = first.len();
|
||
let mut offset = metadata_start;
|
||
for line in lines {
|
||
let value = line.trim_end_matches(['\r', '\n']);
|
||
if value == "---" || value == "..." {
|
||
let metadata = &md[metadata_start..offset];
|
||
let body = &md[offset + line.len()..];
|
||
return Some((metadata, body));
|
||
}
|
||
offset += line.len();
|
||
}
|
||
None
|
||
}
|
||
|
||
fn embed_local_images<'a>(events: Vec<MdEvent<'a>>, base_dir: Option<&Path>) -> Vec<MdEvent<'a>> {
|
||
let Some(base_dir) = base_dir else {
|
||
return events;
|
||
};
|
||
|
||
events
|
||
.into_iter()
|
||
.map(|event| match event {
|
||
MdEvent::Start(Tag::Image {
|
||
link_type,
|
||
dest_url,
|
||
title,
|
||
id,
|
||
}) => {
|
||
let embedded = local_image_data_url(base_dir, dest_url.as_ref());
|
||
MdEvent::Start(Tag::Image {
|
||
link_type,
|
||
dest_url: embedded.map(CowStr::from).unwrap_or(dest_url),
|
||
title,
|
||
id,
|
||
})
|
||
}
|
||
_ => event,
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
fn local_image_data_url(base_dir: &Path, url: &str) -> Option<String> {
|
||
let image_path = resolve_local_relative_image_path(base_dir, url)?;
|
||
let mime = image_mime_type(&image_path)?;
|
||
let bytes = fs::read(image_path).ok()?;
|
||
Some(format!("data:{mime};base64,{}", base64_encode(&bytes)))
|
||
}
|
||
|
||
fn resolve_local_relative_image_path(base_dir: &Path, url: &str) -> Option<PathBuf> {
|
||
let path_part = url.split(['#', '?']).next()?.trim();
|
||
if !is_local_relative_url(path_part) {
|
||
return None;
|
||
}
|
||
|
||
let mut candidate = base_dir.to_path_buf();
|
||
for segment in path_part.split('/') {
|
||
if segment.is_empty() || segment == "." {
|
||
continue;
|
||
}
|
||
let decoded = percent_decode_path_segment(segment)?;
|
||
let segment_path = Path::new(&decoded);
|
||
if segment_path
|
||
.components()
|
||
.any(|component| !matches!(component, Component::Normal(_)))
|
||
{
|
||
return None;
|
||
}
|
||
candidate.push(segment_path);
|
||
}
|
||
|
||
if candidate == base_dir {
|
||
return None;
|
||
}
|
||
Some(candidate)
|
||
}
|
||
|
||
fn is_local_relative_url(url: &str) -> bool {
|
||
!url.is_empty()
|
||
&& !url.starts_with('#')
|
||
&& !url.starts_with('/')
|
||
&& !url.starts_with('\\')
|
||
&& !url.starts_with("//")
|
||
&& !url.contains(':')
|
||
}
|
||
|
||
fn percent_decode_path_segment(segment: &str) -> Option<String> {
|
||
let bytes = segment.as_bytes();
|
||
let mut out = Vec::with_capacity(bytes.len());
|
||
let mut i = 0;
|
||
while i < bytes.len() {
|
||
if bytes[i] == b'%' {
|
||
let hi = bytes.get(i + 1).and_then(|b| hex_value(*b))?;
|
||
let lo = bytes.get(i + 2).and_then(|b| hex_value(*b))?;
|
||
out.push((hi << 4) | lo);
|
||
i += 3;
|
||
} else {
|
||
out.push(bytes[i]);
|
||
i += 1;
|
||
}
|
||
}
|
||
String::from_utf8(out).ok()
|
||
}
|
||
|
||
fn hex_value(byte: u8) -> Option<u8> {
|
||
match byte {
|
||
b'0'..=b'9' => Some(byte - b'0'),
|
||
b'a'..=b'f' => Some(byte - b'a' + 10),
|
||
b'A'..=b'F' => Some(byte - b'A' + 10),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
fn image_mime_type(path: &Path) -> Option<&'static str> {
|
||
match path
|
||
.extension()?
|
||
.to_string_lossy()
|
||
.to_ascii_lowercase()
|
||
.as_str()
|
||
{
|
||
"png" => Some("image/png"),
|
||
"jpg" | "jpeg" => Some("image/jpeg"),
|
||
"gif" => Some("image/gif"),
|
||
"webp" => Some("image/webp"),
|
||
"svg" => Some("image/svg+xml"),
|
||
"bmp" => Some("image/bmp"),
|
||
"ico" => Some("image/x-icon"),
|
||
"avif" => Some("image/avif"),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
fn base64_encode(bytes: &[u8]) -> String {
|
||
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||
let mut out = String::with_capacity(((bytes.len() + 2) / 3) * 4);
|
||
let mut chunks = bytes.chunks_exact(3);
|
||
for chunk in &mut chunks {
|
||
let n = ((chunk[0] as u32) << 16) | ((chunk[1] as u32) << 8) | chunk[2] as u32;
|
||
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
|
||
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
|
||
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
|
||
out.push(TABLE[(n & 0x3f) as usize] as char);
|
||
}
|
||
|
||
match chunks.remainder() {
|
||
[a] => {
|
||
let n = (*a as u32) << 16;
|
||
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
|
||
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
|
||
out.push('=');
|
||
out.push('=');
|
||
}
|
||
[a, b] => {
|
||
let n = ((*a as u32) << 16) | ((*b as u32) << 8);
|
||
out.push(TABLE[((n >> 18) & 0x3f) as usize] as char);
|
||
out.push(TABLE[((n >> 12) & 0x3f) as usize] as char);
|
||
out.push(TABLE[((n >> 6) & 0x3f) as usize] as char);
|
||
out.push('=');
|
||
}
|
||
_ => {}
|
||
}
|
||
|
||
out
|
||
}
|
||
|
||
fn add_mark_highlights<'a>(events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
|
||
let mut out = Vec::with_capacity(events.len());
|
||
let mut code_block_depth = 0usize;
|
||
|
||
for event in events {
|
||
match &event {
|
||
MdEvent::Start(Tag::CodeBlock(_)) => code_block_depth += 1,
|
||
MdEvent::End(TagEnd::CodeBlock) => {
|
||
code_block_depth = code_block_depth.saturating_sub(1);
|
||
}
|
||
MdEvent::Text(text) if code_block_depth == 0 && text.contains("==") => {
|
||
push_mark_highlight_events(text.as_ref(), &mut out);
|
||
continue;
|
||
}
|
||
_ => {}
|
||
}
|
||
out.push(event);
|
||
}
|
||
|
||
out
|
||
}
|
||
|
||
fn push_mark_highlight_events<'a>(text: &str, out: &mut Vec<MdEvent<'a>>) {
|
||
let mut rest = text;
|
||
|
||
while let Some(open) = rest.find("==") {
|
||
let after_open = open + 2;
|
||
let Some(close_rel) = rest[after_open..].find("==") else {
|
||
break;
|
||
};
|
||
let close = after_open + close_rel;
|
||
let body = &rest[after_open..close];
|
||
if body.trim().is_empty() {
|
||
break;
|
||
}
|
||
|
||
if open > 0 {
|
||
out.push(MdEvent::Text(CowStr::Boxed(
|
||
rest[..open].to_string().into_boxed_str(),
|
||
)));
|
||
}
|
||
out.push(MdEvent::Html(CowStr::Borrowed(
|
||
r#"<mark class="mdp-mark">"#,
|
||
)));
|
||
out.push(MdEvent::Text(CowStr::Boxed(
|
||
body.to_string().into_boxed_str(),
|
||
)));
|
||
out.push(MdEvent::Html(CowStr::Borrowed("</mark>")));
|
||
rest = &rest[close + 2..];
|
||
}
|
||
|
||
if !rest.is_empty() {
|
||
out.push(MdEvent::Text(CowStr::Boxed(
|
||
rest.to_string().into_boxed_str(),
|
||
)));
|
||
}
|
||
}
|
||
|
||
fn add_heading_ids<'a>(mut events: Vec<MdEvent<'a>>) -> Vec<MdEvent<'a>> {
|
||
let mut seen: HashMap<String, usize> = HashMap::new();
|
||
|
||
for i in 0..events.len() {
|
||
let generate_id = match &events[i] {
|
||
MdEvent::Start(Tag::Heading { id: Some(id), .. }) => {
|
||
register_heading_id(id.as_ref(), &mut seen);
|
||
false
|
||
}
|
||
MdEvent::Start(Tag::Heading { id: None, .. }) => true,
|
||
_ => false,
|
||
};
|
||
|
||
if !generate_id {
|
||
continue;
|
||
}
|
||
|
||
let text = collect_heading_text(&events, i);
|
||
let base = heading_slug(&text);
|
||
let id_value = unique_heading_id(base, &mut seen);
|
||
if let MdEvent::Start(Tag::Heading { id, .. }) = &mut events[i] {
|
||
*id = Some(CowStr::Boxed(id_value.into_boxed_str()));
|
||
}
|
||
}
|
||
|
||
events
|
||
}
|
||
|
||
fn collect_heading_text(events: &[MdEvent<'_>], start: usize) -> String {
|
||
let mut text = String::new();
|
||
|
||
for event in events.iter().skip(start + 1) {
|
||
match event {
|
||
MdEvent::End(TagEnd::Heading(_)) => break,
|
||
MdEvent::Text(value)
|
||
| MdEvent::Code(value)
|
||
| MdEvent::InlineMath(value)
|
||
| MdEvent::DisplayMath(value) => text.push_str(value.as_ref()),
|
||
MdEvent::SoftBreak | MdEvent::HardBreak => text.push(' '),
|
||
_ => {}
|
||
}
|
||
}
|
||
|
||
text
|
||
}
|
||
|
||
fn heading_slug(text: &str) -> String {
|
||
let mut slug = String::new();
|
||
let mut last_dash = false;
|
||
|
||
for c in text.trim().chars().flat_map(char::to_lowercase) {
|
||
if c.is_alphanumeric() || c == '_' || c == '-' {
|
||
slug.push(c);
|
||
last_dash = false;
|
||
} else if c.is_whitespace() && !slug.is_empty() && !last_dash {
|
||
slug.push('-');
|
||
last_dash = true;
|
||
}
|
||
}
|
||
|
||
while slug.ends_with('-') {
|
||
slug.pop();
|
||
}
|
||
|
||
if slug.is_empty() {
|
||
"section".to_string()
|
||
} else {
|
||
slug
|
||
}
|
||
}
|
||
|
||
fn register_heading_id(id: &str, seen: &mut HashMap<String, usize>) {
|
||
if !id.is_empty() {
|
||
*seen.entry(id.to_string()).or_insert(0) += 1;
|
||
}
|
||
}
|
||
|
||
fn unique_heading_id(base: String, seen: &mut HashMap<String, usize>) -> String {
|
||
let count = seen.entry(base.clone()).or_insert(0);
|
||
let id = if *count == 0 {
|
||
base
|
||
} else {
|
||
format!("{base}-{count}")
|
||
};
|
||
*count += 1;
|
||
id
|
||
}
|
||
|
||
// 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.
|
||
const HLJS_CODE: &str = include_str!("../assets/hljs/vs-dark.css");
|
||
// 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 PREVIEW_ENHANCE_JS: &str = include_str!("../assets/enhance/preview-enhance.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");
|
||
const MAX_RECENT_FILES: usize = 8;
|
||
|
||
fn html_escape_ta(s: &str) -> String {
|
||
s.replace('&', "&").replace('<', "<")
|
||
}
|
||
|
||
fn html_escape_attr(s: &str) -> String {
|
||
s.replace('&', "&")
|
||
.replace('"', """)
|
||
.replace('<', "<")
|
||
}
|
||
|
||
fn html_escape_text(s: &str) -> String {
|
||
s.replace('&', "&")
|
||
.replace('<', "<")
|
||
.replace('>', ">")
|
||
}
|
||
|
||
fn recent_files_path() -> PathBuf {
|
||
config_dir().join("recent-files.txt")
|
||
}
|
||
|
||
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::<Vec<_>>();
|
||
serde_json::to_string(&tabs).expect("tab state is serializable")
|
||
}
|
||
|
||
fn missing_preview_html(tab_id: u64, path: &Path, s: &Strings) -> String {
|
||
format!(
|
||
r#"<div class="missing-file"><div class="missing-mark">!</div><h2>{}</h2><p>{}</p><code>{}</code><div class="missing-actions"><button type="button" data-locate-tab="{tab_id}">{}</button><button type="button" data-close-tab="{tab_id}">{}</button></div></div>"#,
|
||
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 load_recent_files() -> Vec<PathBuf> {
|
||
let Ok(txt) = fs::read_to_string(recent_files_path()) else {
|
||
return Vec::new();
|
||
};
|
||
let mut files = Vec::new();
|
||
for line in txt.lines() {
|
||
if line.is_empty() {
|
||
continue;
|
||
}
|
||
let path = session::strip_verbatim(PathBuf::from(line));
|
||
if !path.exists() || files.iter().any(|p| p == &path) {
|
||
continue;
|
||
}
|
||
files.push(path);
|
||
if files.len() == MAX_RECENT_FILES {
|
||
break;
|
||
}
|
||
}
|
||
files
|
||
}
|
||
|
||
fn save_recent_files(files: &[PathBuf]) {
|
||
let dir = config_dir();
|
||
let _ = fs::create_dir_all(&dir);
|
||
let body = files
|
||
.iter()
|
||
.take(MAX_RECENT_FILES)
|
||
.map(|p| p.to_string_lossy())
|
||
.collect::<Vec<_>>()
|
||
.join("\n");
|
||
let _ = fs::write(dir.join("recent-files.txt"), body);
|
||
}
|
||
|
||
fn remember_recent_file(files: &Arc<Mutex<Vec<PathBuf>>>, path: &Path) {
|
||
let mut recent = files.lock().unwrap();
|
||
recent.retain(|p| p != path);
|
||
recent.insert(0, path.to_path_buf());
|
||
recent.truncate(MAX_RECENT_FILES);
|
||
save_recent_files(&recent);
|
||
}
|
||
|
||
fn forget_recent_file(files: &Arc<Mutex<Vec<PathBuf>>>, path: &Path) -> bool {
|
||
let mut recent = files.lock().unwrap();
|
||
let original_len = recent.len();
|
||
recent.retain(|p| p != path);
|
||
if recent.len() == original_len {
|
||
return false;
|
||
}
|
||
save_recent_files(&recent);
|
||
true
|
||
}
|
||
|
||
fn base_href_for_file(path: &Path) -> Option<String> {
|
||
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<String> {
|
||
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#"<div class="{empty_class}"><div class="icon">#</div><div>{}</div><div class="empty-actions"><button class="empty-open" type="button" data-open-file>{}</button><button class="empty-open empty-new" type="button" data-new-file title="{}">{}</button></div>"#,
|
||
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#"<div class="recent"><div class="recent-title">{}</div><div class="recent-list">"#,
|
||
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#"<button class="recent-item" type="button" data-recent-index="{index}"><span class="recent-name">{}</span><span class="recent-path">{}</span></button>"#,
|
||
html_escape_text(&name),
|
||
html_escape_text(&parent)
|
||
));
|
||
}
|
||
html.push_str("</div></div>");
|
||
}
|
||
|
||
html.push_str("</div>");
|
||
html
|
||
}
|
||
|
||
fn build_page(
|
||
preview_html: &str,
|
||
raw_md: &str,
|
||
base_href: Option<&str>,
|
||
flags: EnhanceFlags,
|
||
s: &Strings,
|
||
home: bool,
|
||
) -> String {
|
||
let body_class = if home { "home" } else { "" };
|
||
let base_tag = base_href
|
||
.map(|href| format!(r#"<base id="base-href" href="{}">"#, html_escape_attr(href)))
|
||
.unwrap_or_else(|| r#"<base id="base-href">"#.to_string());
|
||
format!(
|
||
r#"<!DOCTYPE html><html><head><meta charset="utf-8">
|
||
{base_tag}
|
||
<style id="hljs-code">{css_code}</style>
|
||
<style>
|
||
:root {{ color-scheme: light dark; --chrome-top: 10px; --content-scale: 1; }}
|
||
/* Reserve scrollbar space permanently so the fixed toolbar doesn't shift
|
||
between modes (one with scrollbar, one without). */
|
||
html {{ overflow-y: scroll; scrollbar-gutter: stable; }}
|
||
body {{
|
||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
|
||
margin: 0; padding: 0;
|
||
line-height: 1.6; font-size: 15px;
|
||
color: #1a1a1a; background: #fff;
|
||
}}
|
||
body.has-tabs {{ --chrome-top: 50px; }}
|
||
#app {{ width: 100%; box-sizing: border-box; margin: 0 auto; padding: 24px 48px; }}
|
||
#preview {{ font-size: calc(15px * var(--content-scale)); }}
|
||
#preview .front-matter {{
|
||
margin: 0 0 1.5em;
|
||
padding: .85em 0;
|
||
border-top: 1px solid #e1e4e8;
|
||
border-bottom: 1px solid #e1e4e8;
|
||
color: #59636e;
|
||
}}
|
||
#preview .front-matter pre {{
|
||
margin: 0;
|
||
padding: 0;
|
||
border-radius: 0;
|
||
overflow: visible;
|
||
background: transparent;
|
||
color: inherit;
|
||
font: inherit;
|
||
white-space: pre-wrap;
|
||
overflow-wrap: anywhere;
|
||
}}
|
||
#preview h1,#preview h2,#preview h3,#preview h4 {{ margin-top: 1.4em; }}
|
||
#preview h1 {{ border-bottom: 1px solid #e1e4e8; padding-bottom: .3em; }}
|
||
#preview h2 {{ border-bottom: 1px solid #e1e4e8; padding-bottom: .2em; }}
|
||
/* Heading folding: triangle shows on heading hover; the body collapses down to
|
||
the next heading of the same or higher level. State is per-render only. */
|
||
#preview .mdp-fold > h1,
|
||
#preview .mdp-fold > h2,
|
||
#preview .mdp-fold > h3,
|
||
#preview .mdp-fold > h4,
|
||
#preview .mdp-fold > h5,
|
||
#preview .mdp-fold > h6 {{ position: relative; }}
|
||
/* Fixed 90%-of-H2 size for every heading level. */
|
||
#preview .mdp-fold-toggle {{
|
||
position: absolute; left: -34px; top: 50%;
|
||
width: 30px; height: 30px; padding: 0; border: 0; border-radius: 50%;
|
||
transform: translateY(-50%);
|
||
display: grid; place-items: center;
|
||
background: transparent; color: #999; cursor: pointer;
|
||
opacity: 0; transition: opacity .12s ease, background .12s ease;
|
||
}}
|
||
#preview .mdp-fold-toggle svg {{ grid-area: 1 / 1; overflow: visible; }}
|
||
#preview .mdp-fold-toggle .mdp-fold-i-right {{ display: none; width: 13.5px; height: 20px; }}
|
||
#preview .mdp-fold-toggle .mdp-fold-i-down {{ display: block; width: 20px; height: 13.5px; }}
|
||
#preview h1:hover > .mdp-fold-toggle,
|
||
#preview h2:hover > .mdp-fold-toggle,
|
||
#preview h3:hover > .mdp-fold-toggle,
|
||
#preview h4:hover > .mdp-fold-toggle,
|
||
#preview h5:hover > .mdp-fold-toggle,
|
||
#preview h6:hover > .mdp-fold-toggle,
|
||
#preview .mdp-fold-toggle:focus-visible {{ opacity: .6; }}
|
||
#preview .mdp-fold-toggle:hover {{ opacity: 1; background: rgba(0,0,0,.07); }}
|
||
#preview .mdp-fold.collapsed > :is(h1, h2, h3, h4, h5, h6) > .mdp-fold-toggle .mdp-fold-i-right {{ display: block; }}
|
||
#preview .mdp-fold.collapsed > :is(h1, h2, h3, h4, h5, h6) > .mdp-fold-toggle .mdp-fold-i-down {{ display: none; }}
|
||
#preview .mdp-fold.collapsed > .mdp-fold-body {{ display: none; }}
|
||
#preview code {{ background: #f0f0f0; padding: 2px 6px; border-radius: 4px; font-size: 90%; }}
|
||
/* Code blocks stay dark (VS Dark) even in the light app theme. */
|
||
#preview pre {{ background: #1e1e1e; color: #d4d4d4; padding: 16px; border-radius: 8px; overflow-x: auto; }}
|
||
#preview pre code {{ background: none; padding: 0; font-size: 14px; }}
|
||
#preview blockquote {{ border-left: 4px solid #ddd; margin: 0; padding: 0 1em; color: #666; }}
|
||
#preview .markdown-alert-note,
|
||
#preview .markdown-alert-tip,
|
||
#preview .markdown-alert-important,
|
||
#preview .markdown-alert-warning,
|
||
#preview .markdown-alert-caution {{
|
||
margin: 1em 0;
|
||
padding: 0.75em 1em;
|
||
border-radius: 6px;
|
||
color: inherit;
|
||
}}
|
||
#preview .markdown-alert-title {{
|
||
display: flex;
|
||
align-items: center;
|
||
gap: .35em;
|
||
margin: 0 0 .45em;
|
||
font-weight: 600;
|
||
line-height: 1.25;
|
||
}}
|
||
#preview .markdown-alert-title + p {{ margin-top: 0; }}
|
||
#preview .markdown-alert-note {{ border-color: #0969da; background: #ddf4ff; }}
|
||
#preview .markdown-alert-tip {{ border-color: #1a7f37; background: #dafbe1; }}
|
||
#preview .markdown-alert-important {{ border-color: #8250df; background: #fbefff; }}
|
||
#preview .markdown-alert-warning {{ border-color: #9a6700; background: #fff8c5; }}
|
||
#preview .markdown-alert-caution {{ border-color: #cf222e; background: #ffebe9; }}
|
||
#preview .markdown-alert-note .markdown-alert-title {{ color: #0969da; }}
|
||
#preview .markdown-alert-tip .markdown-alert-title {{ color: #1a7f37; }}
|
||
#preview .markdown-alert-important .markdown-alert-title {{ color: #8250df; }}
|
||
#preview .markdown-alert-warning .markdown-alert-title {{ color: #9a6700; }}
|
||
#preview .markdown-alert-caution .markdown-alert-title {{ color: #cf222e; }}
|
||
#preview .mdp-mark {{ border-radius: 3px; padding: 0 0.12em; background: #fff2a8; color: inherit; }}
|
||
#preview mark.search-hit {{ border-radius: 3px; padding: 0 0.12em; background: #fff2a8; color: inherit; }}
|
||
#preview mark.search-hit.current {{ background: #ffcc4d; color: #1a1a1a; }}
|
||
#preview table {{ border-collapse: collapse; width: 100%; }}
|
||
#preview .mdp-table-wrap {{
|
||
width: min(calc(100vw - 64px), 1280px);
|
||
margin: 1em 0 1em 50%;
|
||
transform: translateX(-50%);
|
||
overflow-x: auto;
|
||
-webkit-overflow-scrolling: touch;
|
||
}}
|
||
#preview .mdp-table-wrap table {{ width: max-content; min-width: 100%; }}
|
||
#preview table th, #preview table td {{ border: 1px solid #ddd; padding: 8px 12px; text-align: left; }}
|
||
#preview table th {{ background: #f6f8fa; font-weight: 600; color: #1a1a1a; white-space: nowrap; }}
|
||
#preview table td {{ min-width: 64px; max-width: 360px; vertical-align: top; overflow-wrap: break-word; }}
|
||
#preview img {{ max-width: 100%; }}
|
||
#preview .katex-display {{ overflow-x: auto; overflow-y: hidden; padding: 0.15em 0; }}
|
||
#preview .mdp-mermaid {{ margin: 1.2em 0; overflow-x: auto; text-align: center; }}
|
||
/* Compensate zoom's percentage width so window-fitted diagrams can grow and scroll. */
|
||
#preview .mdp-mermaid svg {{ max-width: 100%; height: auto; display: block; margin: 0 auto; width: calc(100% * var(--content-scale)); zoom: var(--content-scale); }}
|
||
#preview .mdp-mermaid-error, #preview .mdp-math-error {{ color: #b42318; }}
|
||
#preview hr {{ border: none; border-top: 1px solid #e1e4e8; margin: 2em 0; }}
|
||
#preview a {{ color: #0969da; text-decoration: none; }}
|
||
#preview a:hover {{ text-decoration: underline; }}
|
||
#preview ul, #preview ol {{ padding-left: 2em; }}
|
||
#preview input[type="checkbox"] {{ margin-right: 6px; }}
|
||
#preview dl {{ margin: 1em 0; }}
|
||
#preview dt {{ font-weight: 600; }}
|
||
#preview dd {{ margin: 0 0 .6em 1.5em; }}
|
||
#preview .footnote-reference {{ font-size: .75em; }}
|
||
#preview .footnote-definition {{
|
||
margin-top: 1.5em;
|
||
padding-top: .75em;
|
||
border-top: 1px solid #e1e4e8;
|
||
color: #59636e;
|
||
font-size: .9em;
|
||
}}
|
||
#preview .footnote-definition-label {{ margin-right: .35em; font-weight: 600; }}
|
||
.empty {{ display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||
min-height: 60vh; color: #999; font-size: 18px; gap: 12px; text-align: center; }}
|
||
.empty.has-recent {{
|
||
justify-content: flex-start;
|
||
min-height: calc(100vh - var(--chrome-top) - 38px);
|
||
padding: clamp(56px, 10vh, 96px) 0 40px;
|
||
box-sizing: border-box;
|
||
}}
|
||
.empty .icon {{ font-size: 48px; opacity: 0.4; }}
|
||
.empty-actions {{ display: flex; gap: 8px; margin-top: 6px; }}
|
||
.empty-open {{
|
||
min-height: 40px; padding: 0 16px;
|
||
border: 1px solid #ddd; border-radius: 8px; background: #fff;
|
||
color: #1a1a1a; font: inherit; font-size: 15px; cursor: pointer;
|
||
}}
|
||
.empty-open:hover {{ background: #f5f5f5; color: #000; }}
|
||
.recent {{ width: min(480px, 100%); margin-top: 16px; text-align: left; }}
|
||
.recent-title {{ margin: 0 0 8px; padding: 0; border: 0; font-size: 11px; font-weight: 600; letter-spacing: 0; color: #b6b6b6; text-transform: uppercase; }}
|
||
.recent-list {{ display: grid; gap: 6px; }}
|
||
.recent-item {{
|
||
width: 100%; min-height: 44px; padding: 7px 10px; border: 1px solid #eee;
|
||
border-radius: 8px; background: #fff; color: inherit; text-align: left; cursor: pointer;
|
||
display: grid; gap: 1px;
|
||
}}
|
||
.recent-item:hover {{ background: #f7f7f7; }}
|
||
.recent-name {{ color: #555; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}
|
||
.recent-path {{ color: #aaa; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}
|
||
.tabbar {{
|
||
display: none; position: sticky; top: 0; z-index: 110; height: 40px;
|
||
box-sizing: border-box; align-items: stretch; gap: 4px; padding: 4px 8px;
|
||
border-bottom: 1px solid #e6e6e6; background: rgba(248,248,248,0.96);
|
||
backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px);
|
||
}}
|
||
body.has-tabs .tabbar {{ display: flex; }}
|
||
.tabs {{ display: flex; flex: 1; min-width: 0; gap: 4px; overflow-x: auto; scrollbar-width: none; }}
|
||
.tabs::-webkit-scrollbar {{ display: none; }}
|
||
.tab {{
|
||
flex: 0 1 180px; min-width: 96px; max-width: 200px; height: 31px;
|
||
display: flex; align-items: center; gap: 7px; padding: 0 8px 0 10px;
|
||
box-sizing: border-box; border: 1px solid transparent; border-radius: 7px;
|
||
color: #6b6b6b; background: transparent; cursor: default; user-select: none;
|
||
font-size: 13px;
|
||
}}
|
||
.tab:hover {{ background: rgba(0,0,0,0.045); }}
|
||
.tab.dragging {{ opacity: .55; cursor: grabbing; }}
|
||
.tab.active {{ color: #202020; background: #fff; border-color: #ddd; box-shadow: 0 1px 2px rgba(0,0,0,.04); }}
|
||
.tab.missing {{ color: #a15c00; }}
|
||
.tab-status {{ width: 7px; height: 7px; flex: 0 0 auto; border-radius: 50%; background: transparent; }}
|
||
.tab.dirty .tab-status {{ background: #2979c9; }}
|
||
.tab.missing .tab-status {{ width: auto; height: auto; background: none; border-radius: 0; font-weight: 700; }}
|
||
.tab-name {{ min-width: 0; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }}
|
||
.tab-close {{
|
||
width: 20px; height: 20px; flex: 0 0 auto; padding: 0; border: 0; border-radius: 5px;
|
||
display: grid; place-items: center; color: inherit; background: transparent; cursor: pointer;
|
||
font: 16px/1 -apple-system, BlinkMacSystemFont, sans-serif; opacity: .58;
|
||
}}
|
||
.tab-close:hover {{ opacity: 1; background: rgba(0,0,0,.08); }}
|
||
.tab-close[hidden] {{ display: none; }}
|
||
.tab-menu {{
|
||
position: fixed; z-index: 200; min-width: 188px; padding: 4px;
|
||
background: #fff; border: 1px solid #ddd; border-radius: 8px;
|
||
box-shadow: 0 8px 24px rgba(0,0,0,.16);
|
||
}}
|
||
.tab-menu[hidden] {{ display: none; }}
|
||
.tab-menu-path {{
|
||
max-width: 280px; padding: 3px 8px 5px; overflow: hidden;
|
||
color: #8a8a8a; font-size: 11px; line-height: 1.3;
|
||
white-space: nowrap; text-overflow: ellipsis;
|
||
}}
|
||
.tab-menu button {{
|
||
display: block; width: 100%; padding: 5px 8px; border: 0; border-radius: 5px;
|
||
background: transparent; color: #222; text-align: left; font: inherit;
|
||
font-size: 13px; cursor: pointer;
|
||
}}
|
||
.tab-menu button:hover {{ background: #f2f2f2; }}
|
||
.tab-menu button:disabled {{ opacity: .42; cursor: default; }}
|
||
.tab-menu button:disabled:hover {{ background: transparent; }}
|
||
.tab-open {{
|
||
width: 31px; height: 31px; flex: 0 0 auto; padding: 0; border: 0; border-radius: 7px;
|
||
color: #666; background: transparent; cursor: pointer; font: 20px/1 -apple-system, sans-serif;
|
||
}}
|
||
.tab-open:hover {{ color: #111; background: rgba(0,0,0,.06); }}
|
||
.doc-stats {{
|
||
flex: 0 0 auto; align-self: center; padding: 0 6px;
|
||
color: #8b8b8b; font-size: 11px; white-space: nowrap; user-select: none;
|
||
font-variant-numeric: tabular-nums;
|
||
}}
|
||
.missing-file {{ min-height: 55vh; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; text-align: center; }}
|
||
.missing-file h2, .missing-file p {{ margin: 0; }}
|
||
.missing-file p {{ color: #777; }}
|
||
.missing-file code {{ max-width: min(620px, 90vw); overflow-wrap: anywhere; color: #8a5a12; }}
|
||
.missing-mark {{ width: 38px; height: 38px; border: 2px solid #c98322; border-radius: 50%; display: grid; place-items: center; color: #a15c00; font-weight: 700; font-size: 22px; }}
|
||
.missing-actions {{ display: flex; gap: 8px; margin-top: 8px; }}
|
||
.missing-actions button {{ min-height: 36px; padding: 0 13px; border: 1px solid #d8d8d8; border-radius: 7px; background: #fff; color: #333; cursor: pointer; font: inherit; }}
|
||
.missing-actions button:hover {{ background: #f4f4f4; }}
|
||
|
||
/* Floating toolbar (top-right) — hover-reveal, hidden in empty state */
|
||
.toolbar {{
|
||
position: fixed; top: var(--chrome-top); right: 12px;
|
||
display: flex; gap: 6px; z-index: 100;
|
||
opacity: 0; pointer-events: none;
|
||
transition: opacity 0.18s ease;
|
||
}}
|
||
html:hover .toolbar {{ opacity: 1; pointer-events: auto; }}
|
||
body.home .toolbar {{ display: none !important; }}
|
||
.toolbar button {{
|
||
width: 34px; height: 34px; padding: 0;
|
||
background: rgba(255,255,255,0.8);
|
||
backdrop-filter: blur(6px);
|
||
-webkit-backdrop-filter: blur(6px);
|
||
border: 1px solid rgba(0,0,0,0.08);
|
||
border-radius: 8px;
|
||
display: grid; place-items: center;
|
||
cursor: pointer; color: #555;
|
||
transition: color 0.15s, background 0.15s;
|
||
}}
|
||
.toolbar button:hover {{ color: #000; background: rgba(255,255,255,1); }}
|
||
.toolbar button[hidden] {{ display: none !important; }}
|
||
.zoom-control {{ position: relative; }}
|
||
.zoom-popover {{
|
||
position: absolute; top: 40px; right: 0;
|
||
display: none; align-items: center; gap: 2px; padding: 4px;
|
||
border: 1px solid rgba(0,0,0,.1); border-radius: 8px;
|
||
background: rgba(255,255,255,.96); box-shadow: 0 6px 20px rgba(0,0,0,.12);
|
||
backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
|
||
}}
|
||
.zoom-control.open .zoom-popover {{ display: flex; }}
|
||
.toolbar .zoom-popover button {{ width: 30px; height: 30px; border: 0; background: transparent; }}
|
||
.toolbar .zoom-popover button:hover {{ background: rgba(0,0,0,.06); }}
|
||
.toolbar .zoom-popover .zoom-reset {{
|
||
width: 52px; font-size: 11px; font-variant-numeric: tabular-nums;
|
||
}}
|
||
.findbar {{
|
||
position: fixed; top: var(--chrome-top); left: 50%; transform: translateX(-50%);
|
||
display: none; align-items: center; gap: 6px; z-index: 101;
|
||
padding: 6px; border: 1px solid rgba(0,0,0,0.08); border-radius: 10px;
|
||
background: rgba(255,255,255,0.96); box-shadow: 0 8px 24px rgba(0,0,0,0.12);
|
||
backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
|
||
}}
|
||
body.finding .findbar {{ display: flex; }}
|
||
.findbar input {{
|
||
width: min(42vw, 320px); height: 30px; box-sizing: border-box; border: 0;
|
||
outline: none; background: transparent; color: inherit; font: inherit;
|
||
}}
|
||
.findbar span {{ min-width: 14px; color: #8c959f; text-align: center; }}
|
||
.findbar button {{
|
||
width: 30px; height: 30px; padding: 0; border: 0; border-radius: 7px;
|
||
display: grid; place-items: center; color: #555; background: transparent; cursor: pointer;
|
||
}}
|
||
.findbar button:hover {{ background: #f0f0f0; color: #111; }}
|
||
@media (prefers-color-scheme: dark) {{
|
||
body {{ color: #d4d4d4; background: #1e1e1e; }}
|
||
#preview a {{ color: #6cb6ff; }}
|
||
#preview h1, #preview h2 {{ border-color: #333; }}
|
||
#preview .mdp-fold-toggle {{ color: #aaa; }}
|
||
#preview .mdp-fold-toggle:hover {{ background: rgba(255,255,255,.1); }}
|
||
#preview .front-matter {{ border-color: #333; color: #a9b1ba; }}
|
||
#preview .front-matter pre {{ background: transparent !important; }}
|
||
#preview code:not(pre code) {{ background: #2d2d2d; }}
|
||
#preview blockquote {{ border-color: #444; color: #aaa; }}
|
||
#preview .footnote-definition {{ border-color: #444; color: #aaa; }}
|
||
#preview .markdown-alert-note,
|
||
#preview .markdown-alert-tip,
|
||
#preview .markdown-alert-important,
|
||
#preview .markdown-alert-warning,
|
||
#preview .markdown-alert-caution {{ background: #161b22; color: #d4d4d4; }}
|
||
#preview .markdown-alert-note {{ border-color: #2f81f7; }}
|
||
#preview .markdown-alert-tip {{ border-color: #3fb950; }}
|
||
#preview .markdown-alert-important {{ border-color: #a371f7; }}
|
||
#preview .markdown-alert-warning {{ border-color: #d29922; }}
|
||
#preview .markdown-alert-caution {{ border-color: #f85149; }}
|
||
#preview .markdown-alert-note .markdown-alert-title {{ color: #2f81f7; }}
|
||
#preview .markdown-alert-tip .markdown-alert-title {{ color: #3fb950; }}
|
||
#preview .markdown-alert-important .markdown-alert-title {{ color: #a371f7; }}
|
||
#preview .markdown-alert-warning .markdown-alert-title {{ color: #d29922; }}
|
||
#preview .markdown-alert-caution .markdown-alert-title {{ color: #f85149; }}
|
||
#preview table th {{ background: #2d2d2d; color: #f0f0f0; }}
|
||
#preview table td, #preview table th {{ border-color: #444; }}
|
||
#preview hr {{ border-color: #333; }}
|
||
.toolbar button {{
|
||
background: rgba(40,40,40,0.8);
|
||
border-color: rgba(255,255,255,0.1);
|
||
color: #bbb;
|
||
}}
|
||
.toolbar button:hover {{ color: #fff; background: rgba(55,55,55,1); }}
|
||
.zoom-popover {{ background: rgba(34,34,34,.96); border-color: rgba(255,255,255,.12); }}
|
||
.toolbar .zoom-popover button:hover {{ background: rgba(255,255,255,.1); }}
|
||
.empty-open {{ background: #242424; border-color: #444; color: #ddd; }}
|
||
.empty-open:hover {{ background: #2d2d2d; color: #fff; }}
|
||
.recent-name {{ color: #ddd; }}
|
||
.recent-item {{ background: #242424; border-color: #333; }}
|
||
.recent-item:hover {{ background: #2d2d2d; }}
|
||
.findbar {{ background: rgba(34,34,34,0.96); border-color: rgba(255,255,255,0.1); }}
|
||
.findbar button:hover {{ background: #333; color: #fff; }}
|
||
.tabbar {{ background: rgba(28,28,28,.96); border-color: #363636; }}
|
||
.tab {{ color: #aaa; }}
|
||
.tab:hover {{ background: rgba(255,255,255,.07); }}
|
||
.tab.active {{ color: #eee; background: #2c2c2c; border-color: #444; }}
|
||
.tab.missing {{ color: #e3a04b; }}
|
||
.tab-close:hover, .tab-open:hover {{ background: rgba(255,255,255,.1); color: #fff; }}
|
||
.tab-menu {{ background: #2a2a2a; border-color: #444; box-shadow: 0 8px 24px rgba(0,0,0,.45); }}
|
||
.tab-menu-path {{ color: #999; }}
|
||
.tab-menu button {{ color: #ddd; }}
|
||
.tab-menu button:hover {{ background: rgba(255,255,255,.08); }}
|
||
.tab-menu button:disabled:hover {{ background: transparent; }}
|
||
.missing-file p {{ color: #aaa; }}
|
||
.missing-actions button {{ background: #292929; border-color: #444; color: #ddd; }}
|
||
.missing-actions button:hover {{ background: #333; }}
|
||
}}
|
||
|
||
/* Source editor textarea — height is auto-grown by JS to match content,
|
||
so the page (html) owns the only vertical scrollbar. */
|
||
#editor {{
|
||
display: none;
|
||
width: 100%;
|
||
box-sizing: border-box;
|
||
border: none; outline: none; resize: none;
|
||
overflow: hidden;
|
||
font: calc(14px * var(--content-scale))/1.6 "SF Mono","Menlo","Consolas",monospace;
|
||
background: transparent; color: inherit;
|
||
padding: 0;
|
||
}}
|
||
body.editing #preview {{ display: none; }}
|
||
body.editing #editor {{ display: block; padding: 16px 48px; }}
|
||
body.editing #app {{ max-width: none; padding: 0; }}
|
||
|
||
@page {{
|
||
margin: 12mm;
|
||
}}
|
||
|
||
@media print {{
|
||
.toolbar, .tabbar, #editor {{ display: none !important; }}
|
||
#preview {{ display: block !important; }}
|
||
#app {{ max-width: none; padding: 0; }}
|
||
#preview .mdp-table-wrap {{ width: auto; margin: 1em 0; transform: none; overflow: visible; }}
|
||
#preview pre {{ -webkit-print-color-adjust: exact; print-color-adjust: exact; }}
|
||
#preview .mdp-fold-body {{ display: block !important; }}
|
||
#preview .mdp-fold-toggle {{ display: none !important; }}
|
||
}}
|
||
</style></head><body class="{body_class}">
|
||
<div class="tabbar" id="tabbar"><div class="tabs" id="tabs"></div><div class="doc-stats" id="doc-stats" aria-live="polite"></div><button class="tab-open" id="tab-open" type="button" title="{new_tab}" aria-label="{new_tab}">+</button></div>
|
||
<div class="tab-menu" id="tab-menu" hidden><div class="tab-menu-path" id="tab-menu-path"></div><button type="button" id="tab-menu-reveal">{btn_open_location}</button><button type="button" id="tab-menu-new-window">{btn_new_window}</button></div>
|
||
<div class="toolbar">
|
||
<button id="btn-toggle" title="{btn_edit}" aria-label="{btn_edit}"></button>
|
||
<div class="zoom-control" id="zoom-control">
|
||
<button id="btn-zoom" title="{btn_zoom}" aria-label="{btn_zoom}"></button>
|
||
<div class="zoom-popover">
|
||
<button id="btn-zoom-out" title="{btn_zoom_out}" aria-label="{btn_zoom_out}">−</button>
|
||
<button id="btn-zoom-reset" class="zoom-reset" title="{btn_zoom_reset}" aria-label="{btn_zoom_reset}">100%</button>
|
||
<button id="btn-zoom-in" title="{btn_zoom_in}" aria-label="{btn_zoom_in}">+</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div class="findbar" role="search">
|
||
<input id="find-input" type="search" placeholder="{search_placeholder}" aria-label="{search_placeholder}">
|
||
<span id="find-state"></span>
|
||
<button id="find-prev" title="Previous" aria-label="Previous"></button>
|
||
<button id="find-next" title="Next" aria-label="Next"></button>
|
||
<button id="find-close" title="Close" aria-label="Close"></button>
|
||
</div>
|
||
<div id="app">
|
||
<div id="preview">{preview_html}</div>
|
||
<textarea id="editor" spellcheck="false">{raw_md_escaped}</textarea>
|
||
</div>
|
||
<script>
|
||
(function(){{
|
||
var ICON_EDIT = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>';
|
||
var ICON_VIEW = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>';
|
||
var ICON_ZOOM = '<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/><path d="M8 11h6"/><path d="M11 8v6"/></svg>';
|
||
var ICON_UP = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18 15-6-6-6 6"/></svg>';
|
||
var ICON_DOWN = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>';
|
||
var ICON_CLOSE = '<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>';
|
||
var L_EDIT = '{btn_edit}', L_VIEW = '{btn_preview}', L_HOME = '{home_tab}';
|
||
window.__mdPreviewFoldLabel = '{fold_toggle}';
|
||
window.__mdPreviewCannotSave = '{cannot_save_js}';
|
||
|
||
var btnToggle = document.getElementById('btn-toggle');
|
||
var btnZoom = document.getElementById('btn-zoom');
|
||
var btnZoomOut = document.getElementById('btn-zoom-out');
|
||
var btnZoomReset = document.getElementById('btn-zoom-reset');
|
||
var btnZoomIn = document.getElementById('btn-zoom-in');
|
||
var zoomControl = document.getElementById('zoom-control');
|
||
var findInput = document.getElementById('find-input');
|
||
var findState = document.getElementById('find-state');
|
||
var findPrev = document.getElementById('find-prev');
|
||
var findNext = document.getElementById('find-next');
|
||
var findClose = document.getElementById('find-close');
|
||
var tabsEl = document.getElementById('tabs');
|
||
var docStats = document.getElementById('doc-stats');
|
||
var tabOpen = document.getElementById('tab-open');
|
||
var tabMenu = document.getElementById('tab-menu');
|
||
var tabMenuPath = document.getElementById('tab-menu-path');
|
||
var tabMenuReveal = document.getElementById('tab-menu-reveal');
|
||
var tabMenuNewWindow = document.getElementById('tab-menu-new-window');
|
||
var tabMenuTargetId = 0;
|
||
var tabDrag = null;
|
||
var suppressTabClickUntil = 0;
|
||
var ta = document.getElementById('editor');
|
||
var dirty = false;
|
||
var activeTabId = 0;
|
||
var tabCount = 0;
|
||
var pendingAutosaveTimer = 0;
|
||
var autosavePaused = false;
|
||
var saveBlocked = false;
|
||
var AUTOSAVE_DEBOUNCE_MS = 700;
|
||
var composingFind = false;
|
||
var pendingFindTimer = 0;
|
||
var FIND_DEBOUNCE_MS = 300;
|
||
// The strip stays hidden while the only tab is Home, matching the
|
||
// original start-up page. Set to false to keep the tab bar always on.
|
||
var HIDE_SINGLE_HOME_TAB = true;
|
||
var findHits = [];
|
||
var currentFindHit = -1;
|
||
var lastFindQuery = '';
|
||
var STAT_WORDS = '{stat_words_js}';
|
||
var STAT_CHARS = '{stat_chars_js}';
|
||
var ZOOM_SAVE_DEBOUNCE_MS = 400;
|
||
var pendingZoomSaveTimer = 0;
|
||
var ZOOM_MIN = 50;
|
||
var ZOOM_MAX = 300;
|
||
var ZOOM_STEP = 5;
|
||
var ZOOM_WHEEL_THROTTLE_MS = 90;
|
||
var zoomWheelAt = 0;
|
||
var zoomPercent = 100;
|
||
|
||
btnToggle.innerHTML = ICON_EDIT;
|
||
btnZoom.innerHTML = ICON_ZOOM;
|
||
findPrev.innerHTML = ICON_UP;
|
||
findNext.innerHTML = ICON_DOWN;
|
||
findClose.innerHTML = ICON_CLOSE;
|
||
|
||
function inEdit() {{ return document.body.classList.contains('editing'); }}
|
||
function textSegments(text) {{
|
||
if (typeof Intl !== 'undefined' && Intl.Segmenter) {{
|
||
var segmenter = new Intl.Segmenter(undefined, {{ granularity: 'grapheme' }});
|
||
return Array.from(segmenter.segment(text), function(item) {{ return item.segment; }});
|
||
}}
|
||
return Array.from(text);
|
||
}}
|
||
function updateDocumentStats(raw) {{
|
||
var segments = textSegments(String(raw || ''));
|
||
var words = segments.reduce(function(total, segment) {{
|
||
return total + (/^\s+$/u.test(segment) ? 0 : 1);
|
||
}}, 0);
|
||
var number = new Intl.NumberFormat().format;
|
||
docStats.textContent =
|
||
number(words) + ' ' + STAT_WORDS + ' · ' + number(segments.length) + ' ' + STAT_CHARS;
|
||
}}
|
||
function queueZoomSave() {{
|
||
if (pendingZoomSaveTimer) clearTimeout(pendingZoomSaveTimer);
|
||
pendingZoomSaveTimer = setTimeout(function() {{
|
||
pendingZoomSaveTimer = 0;
|
||
if (window.ipc) window.ipc.postMessage('zoom:' + zoomPercent);
|
||
}}, ZOOM_SAVE_DEBOUNCE_MS);
|
||
}}
|
||
function applyZoom(percent, persist) {{
|
||
zoomPercent = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, percent));
|
||
document.documentElement.style.setProperty('--content-scale', String(zoomPercent / 100));
|
||
btnZoomReset.textContent = zoomPercent + '%';
|
||
if (persist) queueZoomSave();
|
||
if (inEdit()) autoResize();
|
||
}}
|
||
function changeZoom(delta) {{
|
||
applyZoom(zoomPercent + delta, true);
|
||
}}
|
||
function currentScrollProgress() {{
|
||
var root = document.documentElement;
|
||
var max = Math.max(root.scrollHeight - window.innerHeight, 0);
|
||
var y = window.scrollY || root.scrollTop || 0;
|
||
return max > 0 ? Math.min(1, Math.max(0, y / max)) : 0;
|
||
}}
|
||
function restoreScrollProgress(progress) {{
|
||
function restore() {{
|
||
var max = Math.max(document.documentElement.scrollHeight - window.innerHeight, 0);
|
||
window.scrollTo(window.scrollX || 0, max * progress);
|
||
}}
|
||
restore();
|
||
requestAnimationFrame(function() {{
|
||
restore();
|
||
requestAnimationFrame(restore);
|
||
}});
|
||
}}
|
||
applyZoom(100, false);
|
||
window.__mdPreviewSetZoom = function(percent) {{ applyZoom(percent, false); }};
|
||
updateDocumentStats(ta.value);
|
||
function shortenPath(path, max) {{
|
||
if (!path || path.length <= max) return path || '';
|
||
var head = Math.ceil((max - 3) / 2);
|
||
var tail = Math.floor((max - 3) / 2);
|
||
return path.slice(0, head) + '...' + path.slice(-tail);
|
||
}}
|
||
function suppressTabTooltips() {{
|
||
Array.prototype.forEach.call(tabsEl.querySelectorAll('.tab[title]'), function(tab) {{
|
||
tab.setAttribute('data-saved-title', tab.getAttribute('title'));
|
||
tab.removeAttribute('title');
|
||
}});
|
||
}}
|
||
function restoreTabTooltips() {{
|
||
Array.prototype.forEach.call(tabsEl.querySelectorAll('.tab[data-saved-title]'), function(tab) {{
|
||
var title = tab.getAttribute('data-saved-title');
|
||
tab.removeAttribute('data-saved-title');
|
||
if (title) tab.setAttribute('title', title);
|
||
}});
|
||
}}
|
||
function hideTabMenu() {{
|
||
if (!tabMenu || tabMenu.hidden) return;
|
||
tabMenu.hidden = true;
|
||
tabMenuTargetId = 0;
|
||
restoreTabTooltips();
|
||
}}
|
||
function showTabMenu(id, x, y) {{
|
||
if (!tabMenu) return;
|
||
if (!tabMenu.hidden) hideTabMenu();
|
||
suppressTabTooltips();
|
||
tabMenuTargetId = id;
|
||
var tabEl = tabsEl.querySelector('.tab[data-tab-id="' + id + '"]');
|
||
var isHome = tabEl ? tabEl.classList.contains('home') : false;
|
||
var path = tabEl ? (tabEl.getAttribute('data-tab-path') || '') : '';
|
||
if (tabMenuPath) {{
|
||
tabMenuPath.textContent = isHome ? L_HOME : shortenPath(path, 42);
|
||
if (!isHome && path) tabMenuPath.setAttribute('title', path);
|
||
else tabMenuPath.removeAttribute('title');
|
||
}}
|
||
tabMenu.hidden = false;
|
||
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1 || isHome;
|
||
if (tabMenuReveal) tabMenuReveal.disabled = isHome || !path;
|
||
tabMenu.style.left = '0px';
|
||
tabMenu.style.top = '0px';
|
||
var rect = tabMenu.getBoundingClientRect();
|
||
var left = Math.max(8, Math.min(x, window.innerWidth - rect.width - 8));
|
||
var top = Math.max(8, Math.min(y, window.innerHeight - rect.height - 8));
|
||
tabMenu.style.left = left + 'px';
|
||
tabMenu.style.top = top + 'px';
|
||
}}
|
||
function detachTab(id) {{
|
||
if (tabCount <= 1) return;
|
||
if (saveBlocked) {{
|
||
window.alert(window.__mdPreviewCannotSave || 'Discard unsaved changes?');
|
||
return;
|
||
}}
|
||
requestTabAction('detach', id);
|
||
}}
|
||
document.addEventListener('contextmenu', function(e) {{
|
||
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||
if (tab) {{
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
showTabMenu(tab.getAttribute('data-tab-id'), e.clientX, e.clientY);
|
||
return;
|
||
}}
|
||
hideTabMenu();
|
||
if (!inEdit() || e.target !== ta) e.preventDefault();
|
||
}});
|
||
function setDirty(d) {{
|
||
if (dirty === d) return;
|
||
dirty = d;
|
||
window.ipc.postMessage(d ? 'dirty:1' : 'dirty:0');
|
||
}}
|
||
function cancelPendingAutosave() {{
|
||
if (!pendingAutosaveTimer) return;
|
||
clearTimeout(pendingAutosaveTimer);
|
||
pendingAutosaveTimer = 0;
|
||
}}
|
||
function save() {{
|
||
cancelPendingAutosave();
|
||
if (!dirty) return;
|
||
window.ipc.postMessage('save:' + ta.value);
|
||
}}
|
||
function scheduleAutosave() {{
|
||
cancelPendingAutosave();
|
||
if (autosavePaused) return;
|
||
pendingAutosaveTimer = setTimeout(function() {{
|
||
pendingAutosaveTimer = 0;
|
||
if (dirty) save();
|
||
}}, AUTOSAVE_DEBOUNCE_MS);
|
||
}}
|
||
window.__mdPreviewSave = save;
|
||
function requestTabAction(action, id) {{
|
||
cancelPendingAutosave();
|
||
var message = 'tab-action:' + action + ':' + id;
|
||
if (dirty) {{
|
||
if (saveBlocked) {{
|
||
if (!window.confirm(window.__mdPreviewCannotSave || 'Discard unsaved changes?')) return;
|
||
}} else {{
|
||
message += '\n' + ta.value;
|
||
}}
|
||
}}
|
||
window.ipc.postMessage(message);
|
||
}}
|
||
function openFile() {{
|
||
if (inEdit()) leaveEdit();
|
||
window.ipc.postMessage('open');
|
||
}}
|
||
window.__mdPreviewOpenFile = openFile;
|
||
function newFile() {{
|
||
if (inEdit()) leaveEdit();
|
||
window.ipc.postMessage('new-file');
|
||
}}
|
||
window.__mdPreviewNewFile = newFile;
|
||
function newTab() {{
|
||
// Reuse the close/activate path so a dirty editor is saved before the
|
||
// Home tab replaces it.
|
||
requestTabAction('new-tab', 0);
|
||
}}
|
||
function showFind() {{
|
||
if (document.body.classList.contains('home')) return;
|
||
if (inEdit()) return;
|
||
document.body.classList.add('finding');
|
||
setTimeout(function(){{ findInput.focus(); findInput.select(); }}, 0);
|
||
}}
|
||
window.__mdPreviewShowFind = showFind;
|
||
function hideFind() {{
|
||
document.body.classList.remove('finding');
|
||
findInput.value = '';
|
||
clearFindHits();
|
||
if (pendingFindTimer) {{ clearTimeout(pendingFindTimer); pendingFindTimer = 0; }}
|
||
var sel = window.getSelection && window.getSelection();
|
||
if (sel && sel.removeAllRanges) sel.removeAllRanges();
|
||
}}
|
||
function updateFindState() {{
|
||
findState.textContent = findHits.length ? (currentFindHit + 1) + '/' + findHits.length : '';
|
||
}}
|
||
function clearFindHits() {{
|
||
findHits.forEach(function(mark) {{
|
||
var parent = mark.parentNode;
|
||
if (!parent) return;
|
||
parent.replaceChild(document.createTextNode(mark.textContent), mark);
|
||
parent.normalize();
|
||
}});
|
||
findHits = [];
|
||
currentFindHit = -1;
|
||
lastFindQuery = '';
|
||
updateFindState();
|
||
}}
|
||
function focusFindInput(selectionStart, selectionEnd) {{
|
||
if (!document.body.classList.contains('finding')) return;
|
||
try {{
|
||
findInput.focus({{ preventScroll: true }});
|
||
}} catch (_) {{
|
||
findInput.focus();
|
||
}}
|
||
if (typeof selectionStart === 'number' && typeof selectionEnd === 'number') {{
|
||
try {{ findInput.setSelectionRange(selectionStart, selectionEnd); }} catch (_) {{}}
|
||
}}
|
||
}}
|
||
function restoreFindInput(selectionStart, selectionEnd) {{
|
||
setTimeout(function() {{ focusFindInput(selectionStart, selectionEnd); }}, 0);
|
||
requestAnimationFrame(function() {{
|
||
focusFindInput(selectionStart, selectionEnd);
|
||
setTimeout(function() {{ focusFindInput(selectionStart, selectionEnd); }}, 80);
|
||
}});
|
||
}}
|
||
function selectFindHit(index) {{
|
||
if (!findHits.length) {{
|
||
currentFindHit = -1;
|
||
updateFindState();
|
||
return;
|
||
}}
|
||
if (currentFindHit >= 0 && findHits[currentFindHit]) {{
|
||
findHits[currentFindHit].classList.remove('current');
|
||
}}
|
||
currentFindHit = (index + findHits.length) % findHits.length;
|
||
var hit = findHits[currentFindHit];
|
||
hit.classList.add('current');
|
||
if (window.__mdPreviewExpandFold) window.__mdPreviewExpandFold(hit);
|
||
hit.scrollIntoView({{ block: 'center', inline: 'nearest' }});
|
||
updateFindState();
|
||
}}
|
||
function runFindQuery(query) {{
|
||
clearFindHits();
|
||
query = String(query || '').trim();
|
||
if (!query) return;
|
||
lastFindQuery = query;
|
||
var needle = query.toLowerCase();
|
||
var previewEl = document.getElementById('preview');
|
||
var walker = document.createTreeWalker(previewEl, NodeFilter.SHOW_TEXT, {{
|
||
acceptNode: function(node) {{
|
||
if (!node.nodeValue || node.nodeValue.toLowerCase().indexOf(needle) < 0) {{
|
||
return NodeFilter.FILTER_REJECT;
|
||
}}
|
||
var parent = node.parentElement;
|
||
if (!parent || parent.closest('script,style,svg,mark.search-hit,.katex,.mdp-mermaid')) {{
|
||
return NodeFilter.FILTER_REJECT;
|
||
}}
|
||
return NodeFilter.FILTER_ACCEPT;
|
||
}}
|
||
}});
|
||
var nodes = [];
|
||
while (walker.nextNode()) nodes.push(walker.currentNode);
|
||
nodes.forEach(function(node) {{
|
||
var text = node.nodeValue;
|
||
var lower = text.toLowerCase();
|
||
var fragment = document.createDocumentFragment();
|
||
var start = 0;
|
||
var index;
|
||
while ((index = lower.indexOf(needle, start)) >= 0) {{
|
||
if (index > start) fragment.appendChild(document.createTextNode(text.slice(start, index)));
|
||
var mark = document.createElement('mark');
|
||
mark.className = 'search-hit';
|
||
mark.textContent = text.slice(index, index + query.length);
|
||
findHits.push(mark);
|
||
fragment.appendChild(mark);
|
||
start = index + query.length;
|
||
}}
|
||
if (start < text.length) fragment.appendChild(document.createTextNode(text.slice(start)));
|
||
node.parentNode.replaceChild(fragment, node);
|
||
}});
|
||
selectFindHit(0);
|
||
}}
|
||
function runFind(backward) {{
|
||
var q = findInput.value;
|
||
if (!q) {{ clearFindHits(); return; }}
|
||
var hadFocus = document.activeElement === findInput;
|
||
var selectionStart = findInput.selectionStart;
|
||
var selectionEnd = findInput.selectionEnd;
|
||
var normalized = String(q || '').trim();
|
||
if (!normalized) {{
|
||
clearFindHits();
|
||
}} else if (normalized !== lastFindQuery) {{
|
||
runFindQuery(normalized);
|
||
}} else {{
|
||
selectFindHit(currentFindHit + (backward ? -1 : 1));
|
||
}}
|
||
if (hadFocus) restoreFindInput(selectionStart, selectionEnd);
|
||
}}
|
||
function scheduleFind() {{
|
||
if (pendingFindTimer) clearTimeout(pendingFindTimer);
|
||
pendingFindTimer = setTimeout(function() {{
|
||
pendingFindTimer = 0;
|
||
if (!composingFind) runFindQuery(findInput.value);
|
||
}}, FIND_DEBOUNCE_MS);
|
||
}}
|
||
// Grow textarea height to its content so the page (html) owns the sole
|
||
// scrollbar; avoids the double-scrollbar you see if textarea keeps its
|
||
// own internal scroll.
|
||
function autoResize() {{
|
||
var x = window.scrollX || document.documentElement.scrollLeft || 0;
|
||
var y = window.scrollY || document.documentElement.scrollTop || 0;
|
||
ta.style.height = 'auto';
|
||
var h = Math.max(ta.scrollHeight, window.innerHeight);
|
||
ta.style.height = h + 'px';
|
||
window.scrollTo(x, y);
|
||
}}
|
||
function enterEdit() {{
|
||
if (document.body.classList.contains('home')) return;
|
||
var progress = currentScrollProgress();
|
||
document.body.classList.add('editing');
|
||
btnToggle.innerHTML = ICON_VIEW;
|
||
btnToggle.title = L_VIEW;
|
||
btnToggle.setAttribute('aria-label', L_VIEW);
|
||
autoResize();
|
||
try {{
|
||
ta.focus({{ preventScroll: true }});
|
||
}} catch (_) {{
|
||
ta.focus();
|
||
}}
|
||
restoreScrollProgress(progress);
|
||
}}
|
||
function leaveEdit() {{
|
||
var progress = currentScrollProgress();
|
||
if (dirty) save();
|
||
document.body.classList.remove('editing');
|
||
btnToggle.innerHTML = ICON_EDIT;
|
||
btnToggle.title = L_EDIT;
|
||
btnToggle.setAttribute('aria-label', L_EDIT);
|
||
restoreScrollProgress(progress);
|
||
}}
|
||
window.__mdPreviewToggleEdit = function() {{
|
||
if (inEdit()) leaveEdit(); else enterEdit();
|
||
}};
|
||
window.__mdPreviewEnterEdit = function() {{
|
||
if (!inEdit()) enterEdit();
|
||
}};
|
||
window.__mdPreviewCloseActiveTab = function() {{
|
||
if (activeTabId) requestTabAction('close', activeTabId);
|
||
}};
|
||
|
||
tabOpen.addEventListener('click', newTab);
|
||
if (tabMenuNewWindow) {{
|
||
tabMenuNewWindow.addEventListener('click', function(e) {{
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
var id = tabMenuTargetId;
|
||
hideTabMenu();
|
||
if (id) detachTab(id);
|
||
}});
|
||
}}
|
||
if (tabMenuReveal) {{
|
||
tabMenuReveal.addEventListener('click', function(e) {{
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
var id = tabMenuTargetId;
|
||
hideTabMenu();
|
||
if (id) window.ipc.postMessage('reveal-tab:' + id);
|
||
}});
|
||
}}
|
||
tabsEl.addEventListener('pointerdown', function(e) {{
|
||
if (e.button !== 0 || tabCount <= 1) return;
|
||
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||
if (!tab || (e.target.closest && e.target.closest('.tab-close'))) return;
|
||
if (tab.classList.contains('home')) return;
|
||
hideTabMenu();
|
||
tabDrag = {{ id: tab.getAttribute('data-tab-id'), startY: e.clientY, element: tab, pointerId: e.pointerId, dragged: false }};
|
||
try {{ tab.setPointerCapture(e.pointerId); }} catch (err) {{}}
|
||
}});
|
||
tabsEl.addEventListener('pointermove', function(e) {{
|
||
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
|
||
if (!tabDrag.dragged && Math.abs(e.clientY - tabDrag.startY) >= 24) {{
|
||
tabDrag.dragged = true;
|
||
tabDrag.element.classList.add('dragging');
|
||
}}
|
||
}});
|
||
tabsEl.addEventListener('pointerup', function(e) {{
|
||
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
|
||
var drag = tabDrag;
|
||
tabDrag = null;
|
||
drag.element.classList.remove('dragging');
|
||
try {{
|
||
if (drag.element.hasPointerCapture(e.pointerId)) drag.element.releasePointerCapture(e.pointerId);
|
||
}} catch (err) {{}}
|
||
if (!drag.dragged) return;
|
||
suppressTabClickUntil = Date.now() + 350;
|
||
if (tabCount > 1) detachTab(drag.id);
|
||
}});
|
||
tabsEl.addEventListener('pointercancel', function(e) {{
|
||
if (!tabDrag || e.pointerId !== tabDrag.pointerId) return;
|
||
var drag = tabDrag;
|
||
tabDrag = null;
|
||
drag.element.classList.remove('dragging');
|
||
}});
|
||
window.addEventListener('resize', hideTabMenu);
|
||
window.addEventListener('scroll', hideTabMenu, true);
|
||
window.addEventListener('blur', hideTabMenu);
|
||
document.addEventListener('click', function(e) {{
|
||
if (Date.now() < suppressTabClickUntil) {{
|
||
var suppressedTab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||
if (suppressedTab) {{
|
||
suppressTabClickUntil = 0;
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
return;
|
||
}}
|
||
}}
|
||
if (tabMenu && !tabMenu.hidden) hideTabMenu();
|
||
var closeTab = e.target && e.target.closest ? e.target.closest('[data-close-tab]') : null;
|
||
if (closeTab) {{
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
requestTabAction('close', closeTab.getAttribute('data-close-tab'));
|
||
return;
|
||
}}
|
||
var locateTab = e.target && e.target.closest ? e.target.closest('[data-locate-tab]') : null;
|
||
if (locateTab) {{
|
||
e.preventDefault();
|
||
window.ipc.postMessage('locate-tab:' + locateTab.getAttribute('data-locate-tab'));
|
||
return;
|
||
}}
|
||
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||
if (tab) {{
|
||
e.preventDefault();
|
||
requestTabAction('activate', tab.getAttribute('data-tab-id'));
|
||
return;
|
||
}}
|
||
var newFileBtn = e.target && e.target.closest ? e.target.closest('[data-new-file]') : null;
|
||
if (newFileBtn) {{
|
||
e.preventDefault();
|
||
newFile();
|
||
return;
|
||
}}
|
||
var openBtn = e.target && e.target.closest ? e.target.closest('[data-open-file]') : null;
|
||
if (openBtn) {{
|
||
e.preventDefault();
|
||
openFile();
|
||
return;
|
||
}}
|
||
var recentBtn = e.target && e.target.closest ? e.target.closest('[data-recent-index]') : null;
|
||
if (recentBtn) {{
|
||
e.preventDefault();
|
||
window.ipc.postMessage('open-recent:' + recentBtn.getAttribute('data-recent-index'));
|
||
}}
|
||
}});
|
||
findInput.addEventListener('compositionstart', function() {{ composingFind = true; }});
|
||
findInput.addEventListener('compositionend', function() {{ composingFind = false; scheduleFind(); }});
|
||
findInput.addEventListener('input', function(e) {{
|
||
if (composingFind || e.isComposing) return;
|
||
scheduleFind();
|
||
}});
|
||
findInput.addEventListener('keydown', function(e) {{
|
||
if (composingFind || e.isComposing) return;
|
||
if (e.key === 'Enter') {{ e.preventDefault(); runFind(e.shiftKey); }}
|
||
if (e.key === 'Escape') {{ e.preventDefault(); hideFind(); }}
|
||
}});
|
||
findPrev.addEventListener('click', function() {{ runFind(true); }});
|
||
findNext.addEventListener('click', function() {{ runFind(false); }});
|
||
findClose.addEventListener('click', hideFind);
|
||
|
||
btnToggle.addEventListener('click', function() {{
|
||
window.__mdPreviewToggleEdit();
|
||
}});
|
||
btnZoom.addEventListener('click', function(e) {{
|
||
e.stopPropagation();
|
||
zoomControl.classList.toggle('open');
|
||
}});
|
||
btnZoomOut.addEventListener('click', function() {{ changeZoom(-ZOOM_STEP); }});
|
||
btnZoomReset.addEventListener('click', function() {{ applyZoom(100, true); }});
|
||
btnZoomIn.addEventListener('click', function() {{ changeZoom(ZOOM_STEP); }});
|
||
function onContentWheel(e) {{
|
||
if (!e.ctrlKey) return;
|
||
e.preventDefault();
|
||
if (Math.abs(e.deltaY) < 0.01) return;
|
||
var now = Date.now();
|
||
if (now - zoomWheelAt < ZOOM_WHEEL_THROTTLE_MS) return;
|
||
zoomWheelAt = now;
|
||
changeZoom(e.deltaY < 0 ? ZOOM_STEP : -ZOOM_STEP);
|
||
}}
|
||
window.addEventListener('wheel', onContentWheel, {{ passive: false }});
|
||
ta.addEventListener('input', function() {{ setDirty(true); scheduleAutosave(); autoResize(); updateDocumentStats(ta.value); }});
|
||
window.addEventListener('resize', function() {{ if (inEdit()) autoResize(); }});
|
||
document.addEventListener('click', function(e) {{
|
||
if (!zoomControl.contains(e.target)) zoomControl.classList.remove('open');
|
||
}});
|
||
|
||
document.addEventListener('keydown', function(e) {{
|
||
if (e.key === 'Escape' && tabMenu && !tabMenu.hidden) {{
|
||
hideTabMenu();
|
||
return;
|
||
}}
|
||
if ((e.metaKey || e.ctrlKey) && (e.key === 'w' || e.key === 'W')) {{
|
||
if (activeTabId) {{
|
||
e.preventDefault();
|
||
requestTabAction('close', activeTabId);
|
||
}}
|
||
return;
|
||
}}
|
||
if ((e.metaKey || e.ctrlKey) && (e.key === 'n' || e.key === 'N')) {{
|
||
e.preventDefault();
|
||
newFile();
|
||
return;
|
||
}}
|
||
if ((e.metaKey || e.ctrlKey) && (e.key === '+' || e.key === '=' || e.code === 'NumpadAdd')) {{
|
||
e.preventDefault();
|
||
changeZoom(ZOOM_STEP);
|
||
return;
|
||
}}
|
||
if ((e.metaKey || e.ctrlKey) && (e.key === '-' || e.code === 'NumpadSubtract')) {{
|
||
e.preventDefault();
|
||
changeZoom(-ZOOM_STEP);
|
||
return;
|
||
}}
|
||
if ((e.metaKey || e.ctrlKey) && (e.key === '0' || e.code === 'Numpad0')) {{
|
||
e.preventDefault();
|
||
applyZoom(100, true);
|
||
return;
|
||
}}
|
||
if ((e.metaKey || e.ctrlKey) && (e.key === 'r' || e.key === 'R')) {{
|
||
e.preventDefault();
|
||
if (!inEdit()) window.ipc.postMessage('refresh');
|
||
return;
|
||
}}
|
||
if ((e.metaKey || e.ctrlKey) && (e.key === 'o' || e.key === 'O')) {{
|
||
e.preventDefault();
|
||
openFile();
|
||
return;
|
||
}}
|
||
if ((e.metaKey || e.ctrlKey) && (e.key === 'f' || e.key === 'F')) {{
|
||
if (inEdit()) return;
|
||
e.preventDefault();
|
||
showFind();
|
||
return;
|
||
}}
|
||
if ((e.metaKey || e.ctrlKey) && (e.key === 'e' || e.key === 'E')) {{
|
||
e.preventDefault();
|
||
if (inEdit()) leaveEdit(); else enterEdit();
|
||
return;
|
||
}}
|
||
if ((e.metaKey || e.ctrlKey) && (e.key === 's' || e.key === 'S')) {{
|
||
if (inEdit()) {{ e.preventDefault(); save(); }}
|
||
return;
|
||
}}
|
||
if ((e.metaKey || e.ctrlKey) && (e.key === 'p' || e.key === 'P')) {{
|
||
e.preventDefault();
|
||
if (inEdit()) leaveEdit();
|
||
setTimeout(function(){{ window.ipc.postMessage('print'); }}, 0);
|
||
return;
|
||
}}
|
||
if (e.key === 'Escape' && document.body.classList.contains('finding')) {{ hideFind(); return; }}
|
||
if (e.key === 'Escape' && inEdit()) {{ leaveEdit(); }}
|
||
}});
|
||
|
||
// Called by Rust after a save (only preview is refreshed) or after an
|
||
// external file change (both preview + textarea are refreshed).
|
||
window.__setPreview = function(previewHtml, needsMath, needsMermaid) {{
|
||
if (arguments.length > 1 && window.__setFeatureFlags) {{
|
||
window.__setFeatureFlags(needsMath, needsMermaid);
|
||
}}
|
||
document.getElementById('preview').innerHTML = previewHtml;
|
||
(window.requestIdleCallback || function(fn){{ return setTimeout(fn, 0); }})(function() {{
|
||
if (typeof hljs !== 'undefined') hljs.highlightAll();
|
||
if (window.__enhancePreview) window.__enhancePreview();
|
||
}});
|
||
}};
|
||
window.__setBaseHref = function(baseHref) {{
|
||
var base = document.getElementById('base-href');
|
||
if (!base) {{
|
||
base = document.createElement('base');
|
||
base.id = 'base-href';
|
||
document.head.insertBefore(base, document.head.firstChild);
|
||
}}
|
||
if (baseHref) base.setAttribute('href', baseHref);
|
||
else base.removeAttribute('href');
|
||
}};
|
||
window.__markSaved = function(savedRaw) {{
|
||
if (typeof savedRaw === 'string' && ta.value !== savedRaw) {{
|
||
window.ipc.postMessage('dirty:1');
|
||
return;
|
||
}}
|
||
autosavePaused = false;
|
||
saveBlocked = false;
|
||
setDirty(false);
|
||
}};
|
||
window.__markSaveBlocked = function() {{
|
||
saveBlocked = true;
|
||
autosavePaused = true;
|
||
}};
|
||
window.__mdPreviewPauseAutosave = function() {{
|
||
cancelPendingAutosave();
|
||
autosavePaused = true;
|
||
}};
|
||
window.__mdPreviewResolveExternalChange = function() {{
|
||
cancelPendingAutosave();
|
||
window.ipc.postMessage('external-change:' + (dirty ? 'dirty' : 'clean'));
|
||
}};
|
||
window.__setTabs = function(tabs) {{
|
||
hideTabMenu();
|
||
tabs = Array.isArray(tabs) ? tabs : [];
|
||
tabCount = tabs.length;
|
||
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1;
|
||
tabsEl.textContent = '';
|
||
activeTabId = 0;
|
||
var showTabBar = HIDE_SINGLE_HOME_TAB
|
||
? (tabs.length > 1 || (tabs.length === 1 && !tabs[0].home))
|
||
: tabs.length > 0;
|
||
document.body.classList.toggle('has-tabs', showTabBar);
|
||
tabs.forEach(function(tab) {{
|
||
var isHome = !!tab.home;
|
||
var item = document.createElement('div');
|
||
item.className = 'tab' + (isHome ? ' home' : '') + (tab.active ? ' active' : '') + (tab.missing ? ' missing' : '') + (tab.dirty ? ' dirty' : '');
|
||
item.setAttribute('data-tab-id', tab.id);
|
||
item.setAttribute('data-tab-path', isHome ? '' : tab.path);
|
||
item.setAttribute('role', 'button');
|
||
item.setAttribute('tabindex', '0');
|
||
item.title = isHome ? L_HOME : tab.path;
|
||
if (tab.active) activeTabId = tab.id;
|
||
var status = document.createElement('span');
|
||
status.className = 'tab-status';
|
||
status.textContent = tab.missing ? '!' : '';
|
||
var name = document.createElement('span');
|
||
name.className = 'tab-name';
|
||
name.textContent = isHome ? L_HOME : tab.name;
|
||
var close = document.createElement('button');
|
||
close.className = 'tab-close';
|
||
close.type = 'button';
|
||
close.setAttribute('data-close-tab', tab.id);
|
||
close.setAttribute('aria-label', 'Close ' + (isHome ? L_HOME : tab.name));
|
||
close.textContent = '×';
|
||
// A lone Home tab is the start-up page; there is nothing to close.
|
||
if (tabCount === 1 && isHome) close.hidden = true;
|
||
item.appendChild(status);
|
||
item.appendChild(name);
|
||
item.appendChild(close);
|
||
tabsEl.appendChild(item);
|
||
if (tab.active) requestAnimationFrame(function() {{ item.scrollIntoView({{ block: 'nearest', inline: 'nearest' }}); }});
|
||
}});
|
||
}};
|
||
tabsEl.addEventListener('keydown', function(e) {{
|
||
if (e.key !== 'Enter' && e.key !== ' ') return;
|
||
var tab = e.target && e.target.closest ? e.target.closest('[data-tab-id]') : null;
|
||
if (!tab) return;
|
||
e.preventDefault();
|
||
requestTabAction('activate', tab.getAttribute('data-tab-id'));
|
||
}});
|
||
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid) {{
|
||
document.body.classList.remove('home');
|
||
document.body.classList.remove('missing');
|
||
hideFind();
|
||
window.__setBaseHref(baseHref);
|
||
window.__setPreview(previewHtml, needsMath, needsMermaid);
|
||
if (!inEdit() || !dirty) {{
|
||
autosavePaused = false;
|
||
ta.value = rawMd;
|
||
updateDocumentStats(rawMd);
|
||
setDirty(false);
|
||
if (inEdit()) autoResize();
|
||
}}
|
||
}};
|
||
window.__setEmptyPreview = function(previewHtml) {{
|
||
document.body.classList.add('home');
|
||
document.body.classList.remove('missing');
|
||
document.body.classList.remove('editing');
|
||
btnToggle.innerHTML = ICON_EDIT;
|
||
btnToggle.title = L_EDIT;
|
||
btnToggle.setAttribute('aria-label', L_EDIT);
|
||
cancelPendingAutosave();
|
||
autosavePaused = false;
|
||
hideFind();
|
||
window.__setBaseHref('');
|
||
document.getElementById('preview').innerHTML = previewHtml;
|
||
ta.value = '';
|
||
updateDocumentStats('');
|
||
setDirty(false);
|
||
window.scrollTo(0, 0);
|
||
}};
|
||
window.__setMissing = function(previewHtml) {{
|
||
document.body.classList.remove('home');
|
||
document.body.classList.add('missing');
|
||
document.body.classList.remove('editing');
|
||
btnToggle.innerHTML = ICON_EDIT;
|
||
btnToggle.title = L_EDIT;
|
||
btnToggle.setAttribute('aria-label', L_EDIT);
|
||
cancelPendingAutosave();
|
||
autosavePaused = false;
|
||
hideFind();
|
||
window.__setBaseHref('');
|
||
document.getElementById('preview').innerHTML = previewHtml;
|
||
ta.value = '';
|
||
updateDocumentStats('');
|
||
setDirty(false);
|
||
window.scrollTo(0, 0);
|
||
}};
|
||
|
||
// Defer hljs parse + initial highlight to idle time.
|
||
// hljs itself is NOT inlined in this page — Rust injects it via
|
||
// evaluate_script once we tell it we're painted. Until that injection
|
||
// runs, typeof hljs === 'undefined' and highlightAll is skipped; once
|
||
// it lands, hljs.highlightAll() gets called by the injected bootstrap
|
||
// and __setPreview.
|
||
|
||
// Signal Rust after first paint (triggers hljs inject; bench mode exits).
|
||
requestAnimationFrame(function() {{
|
||
requestAnimationFrame(function() {{
|
||
if (window.ipc) window.ipc.postMessage('ready');
|
||
}});
|
||
}});
|
||
}})();
|
||
window.__mdPreviewFeatureFlags = {{ math: {needs_math}, mermaid: {needs_mermaid} }};
|
||
{preview_enhance_js}
|
||
if(window.__enhancePreview)window.__enhancePreview();
|
||
</script>
|
||
</body></html>"#,
|
||
css_code = HLJS_CODE,
|
||
base_tag = base_tag,
|
||
preview_html = preview_html,
|
||
raw_md_escaped = html_escape_ta(raw_md),
|
||
new_tab = s.new_tab,
|
||
home_tab = escape_js(s.home_tab),
|
||
btn_new_window = s.btn_new_window,
|
||
btn_open_location = s.btn_open_location,
|
||
btn_edit = s.btn_edit,
|
||
btn_preview = s.btn_preview,
|
||
fold_toggle = s.fold_toggle,
|
||
cannot_save_js = escape_js(s.cannot_save),
|
||
btn_zoom = s.btn_zoom,
|
||
btn_zoom_out = s.btn_zoom_out,
|
||
btn_zoom_reset = s.btn_zoom_reset,
|
||
btn_zoom_in = s.btn_zoom_in,
|
||
search_placeholder = s.search_placeholder,
|
||
stat_words_js = escape_js(s.stat_words),
|
||
stat_chars_js = escape_js(s.stat_chars),
|
||
body_class = body_class,
|
||
needs_math = flags.math,
|
||
needs_mermaid = flags.mermaid,
|
||
preview_enhance_js = PREVIEW_ENHANCE_JS,
|
||
)
|
||
}
|
||
|
||
fn escape_js(s: &str) -> String {
|
||
s.replace('\\', "\\\\")
|
||
.replace('\'', "\\'")
|
||
.replace('\n', "\\n")
|
||
.replace('\r', "\\r")
|
||
}
|
||
|
||
fn watch_scope_for_file(path: &Path) -> &Path {
|
||
path.parent()
|
||
.filter(|parent| !parent.as_os_str().is_empty())
|
||
.unwrap_or(path)
|
||
}
|
||
|
||
fn event_path_matches_file(event_path: &Path, target: &Path) -> bool {
|
||
event_path == target
|
||
|| (target.file_name().is_some()
|
||
&& event_path.file_name() == target.file_name()
|
||
&& event_path.parent() == target.parent())
|
||
}
|
||
|
||
fn event_should_reload_file(ev: &Event, target: &Path) -> bool {
|
||
if ev.need_rescan() {
|
||
return true;
|
||
}
|
||
|
||
if !(ev.kind.is_modify() || ev.kind.is_create() || ev.kind.is_remove()) {
|
||
return false;
|
||
}
|
||
|
||
ev.paths
|
||
.iter()
|
||
.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().edit_on_open);
|
||
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#"<span class="math math-inline">\{x\}</span>"#));
|
||
}
|
||
|
||
#[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#"<span class="math math-inline">\bar{\mu}_{n}</span>"#));
|
||
assert!(html.contains(r#"<span class="math math-inline">x_{n}</span>"#));
|
||
assert!(!html.contains("<em>"));
|
||
}
|
||
|
||
#[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("<br />"), "{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#"<blockquote class="markdown-alert-important">"#));
|
||
assert!(html.contains("<p>This is an alert</p>"));
|
||
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 默认只读讨论。<br />\n2.2 默认工作流"),
|
||
"{html}"
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn blank_lines_still_create_paragraphs() {
|
||
let html = md_to_html("first line\n\nsecond line");
|
||
|
||
assert_eq!(html.matches("<p>").count(), 2, "{html}");
|
||
assert!(!html.contains("<br />"), "{html}");
|
||
}
|
||
|
||
#[test]
|
||
fn soft_breaks_inside_headings_stay_soft() {
|
||
let html = md_to_html("First heading line\nsecond heading line\n===");
|
||
|
||
assert!(html.contains("<h1"), "{html}");
|
||
assert!(!html.contains("<br />"), "{html}");
|
||
}
|
||
|
||
#[test]
|
||
fn soft_breaks_in_list_items_become_hard_breaks() {
|
||
let html = md_to_html("- first line\n second line");
|
||
|
||
assert!(html.contains("<li>first line<br />"), "{html}");
|
||
assert!(html.contains("second line</li>"), "{html}");
|
||
}
|
||
|
||
#[test]
|
||
fn code_blocks_keep_newlines_without_br() {
|
||
let html = md_to_html("~~~text\nline one\nline two\n~~~");
|
||
|
||
assert!(!html.contains("<br />"), "{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("<dl>"), "{html}");
|
||
assert!(html.contains("<dt>Term</dt>"), "{html}");
|
||
assert!(html.contains("<dd>Definition</dd>"), "{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#"<h1 id="bom-heading">BOM heading</h1>"#),
|
||
"{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#"<h1 id="body">Body</h1>"#),
|
||
"{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 <mark class="mdp-mark">highlight & tag</mark> here"#));
|
||
assert!(html.contains("<code>==literal==</code>"));
|
||
}
|
||
|
||
#[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("", Some(&dir));
|
||
|
||
assert!(html.contains(r#"<img src="data:image/png;base64,YWJj" alt="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("", Some(&dir));
|
||
|
||
assert!(html.contains(r#"<img src="assets/missing.png" alt="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("", Some(&dir));
|
||
|
||
assert!(html.contains(r#"<img src="../secret.png" alt="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#"<aside class="front-matter">"#));
|
||
assert!(html.contains("name: skill-creator-lite"));
|
||
assert!(html.contains("description: Skill 创建封装工具。"));
|
||
assert!(html.contains("<h1 id=\"body\">Body</h1>"));
|
||
assert!(!html.contains("<h2"));
|
||
}
|
||
|
||
#[test]
|
||
fn yaml_front_matter_accepts_dots_and_escapes_html() {
|
||
let html = md_to_html("---\ntitle: <script>alert(1)</script>\n...\nParagraph");
|
||
|
||
assert!(html.contains("title: <script>alert(1)</script>"));
|
||
assert!(!html.contains("<script>alert(1)</script>"));
|
||
assert!(html.contains("<p>Paragraph</p>"));
|
||
}
|
||
|
||
#[test]
|
||
fn horizontal_rules_and_setext_headings_are_not_front_matter() {
|
||
let html = md_to_html("Title\n---\n\nParagraph\n\n---");
|
||
|
||
assert!(!html.contains(r#"<aside class="front-matter">"#));
|
||
assert!(html.contains(r#"<h2 id="title">Title</h2>"#));
|
||
assert!(html.contains("<hr />"));
|
||
}
|
||
|
||
#[test]
|
||
fn file_urls_only_open_existing_supported_documents() {
|
||
let dir = temp_test_dir("document-links");
|
||
let linked = dir.join("含 空格.md");
|
||
let unsupported = dir.join("page.html");
|
||
fs::write(&linked, "# Linked").unwrap();
|
||
fs::write(&unsupported, "<h1>Page</h1>").unwrap();
|
||
|
||
let linked_url = url::Url::from_file_path(&linked).unwrap().to_string();
|
||
let unsupported_url = url::Url::from_file_path(&unsupported).unwrap().to_string();
|
||
let missing_url = url::Url::from_file_path(dir.join("missing.md"))
|
||
.unwrap()
|
||
.to_string();
|
||
|
||
assert_eq!(
|
||
local_document_path_from_url(&format!("{linked_url}#section")),
|
||
Some(fs::canonicalize(&linked).unwrap())
|
||
);
|
||
assert_eq!(local_document_path_from_url(&unsupported_url), None);
|
||
assert_eq!(local_document_path_from_url(&missing_url), None);
|
||
assert_eq!(
|
||
local_document_path_from_url("https://example.com/readme.md"),
|
||
None
|
||
);
|
||
let _ = fs::remove_dir_all(dir);
|
||
}
|
||
|
||
#[test]
|
||
fn document_links_resolve_against_active_file_without_webview_base() {
|
||
let dir = temp_test_dir("relative-doc-links");
|
||
fs::create_dir_all(dir.join("folder")).unwrap();
|
||
let active = dir.join("folder/current.md");
|
||
let linked = dir.join("含 空格.md");
|
||
fs::write(&linked, "# Linked").unwrap();
|
||
let expected = Some(fs::canonicalize(&linked).unwrap());
|
||
assert_eq!(
|
||
resolve_document_link("../含%20空格.md#section", Some(&active)),
|
||
expected
|
||
);
|
||
assert_eq!(
|
||
resolve_document_link("../含 空格.md", Some(&active)),
|
||
expected
|
||
);
|
||
assert_eq!(resolve_document_link("missing.md", Some(&active)), None);
|
||
assert_eq!(
|
||
resolve_document_link("https://example.com/file.md", Some(&active)),
|
||
None
|
||
);
|
||
assert_eq!(resolve_document_link("../", Some(&active)), None);
|
||
assert_eq!(resolve_document_link("relative.md", None), None);
|
||
}
|
||
|
||
#[test]
|
||
fn linux_nvidia_compat_env_only_sets_dmabuf_when_unconfigured() {
|
||
assert_eq!(
|
||
linux_webkit_compat_env(None, None, true),
|
||
Some(("WEBKIT_DISABLE_DMABUF_RENDERER", "1"))
|
||
);
|
||
assert_eq!(linux_webkit_compat_env(Some("0"), None, true), None);
|
||
assert_eq!(linux_webkit_compat_env(None, Some("1"), true), None);
|
||
assert_eq!(linux_webkit_compat_env(None, None, false), None);
|
||
}
|
||
|
||
#[test]
|
||
fn generated_heading_ids_support_cjk_anchor_links() {
|
||
let html = md_to_html("1. [需求概述](#需求概述)\n\n## 需求概述");
|
||
|
||
assert!(html.contains(r##"<a href="#%E9%9C%80%E6%B1%82%E6%A6%82%E8%BF%B0">需求概述</a>"##));
|
||
assert!(html.contains(r#"<h2 id="需求概述">需求概述</h2>"#));
|
||
}
|
||
|
||
#[test]
|
||
fn generated_heading_ids_are_unique_and_keep_explicit_ids() {
|
||
let html = md_to_html("## Intro\n## Intro\n## Custom {#fixed}\n## Fixed");
|
||
|
||
assert!(html.contains(r#"<h2 id="intro">Intro</h2>"#));
|
||
assert!(html.contains(r#"<h2 id="intro-1">Intro</h2>"#));
|
||
assert!(html.contains(r#"<h2 id="fixed">Custom</h2>"#));
|
||
assert!(html.contains(r#"<h2 id="fixed-1">Fixed</h2>"#));
|
||
}
|
||
|
||
#[test]
|
||
fn help_flags_are_recognized() {
|
||
assert!(is_help_arg("-h"));
|
||
assert!(is_help_arg("--help"));
|
||
assert!(!is_help_arg("--edit"));
|
||
}
|
||
|
||
#[test]
|
||
fn secondary_window_stays_on_source_monitor() {
|
||
assert_eq!(
|
||
clamp_secondary_position(2028, 128, 800, 600, Some((1920, 0, 1920, 1080))),
|
||
(2028, 128)
|
||
);
|
||
assert_eq!(
|
||
clamp_secondary_position(3400, 1200, 800, 600, Some((1920, 0, 1920, 1080))),
|
||
(3040, 480)
|
||
);
|
||
assert_eq!(
|
||
clamp_secondary_position(-100, -100, 800, 600, Some((0, 0, 1920, 1080))),
|
||
(0, 0)
|
||
);
|
||
assert_eq!(clamp_secondary_position(10, 10, 800, 600, None), (10, 10));
|
||
}
|
||
|
||
#[test]
|
||
fn zoom_percent_is_clamped_to_supported_range() {
|
||
assert_eq!(clamp_zoom(10), 50);
|
||
assert_eq!(clamp_zoom(50), 50);
|
||
assert_eq!(clamp_zoom(105), 105);
|
||
assert_eq!(clamp_zoom(300), 300);
|
||
assert_eq!(clamp_zoom(999), 300);
|
||
}
|
||
|
||
#[test]
|
||
fn theme_choice_parses_menu_values() {
|
||
assert_eq!(ThemeChoice::from_str("system"), ThemeChoice::System);
|
||
assert_eq!(ThemeChoice::from_str("light"), ThemeChoice::Light);
|
||
assert_eq!(ThemeChoice::from_str("dark"), ThemeChoice::Dark);
|
||
assert_eq!(ThemeChoice::from_str("unexpected"), ThemeChoice::System);
|
||
assert_eq!(ThemeChoice::Dark.as_str(), "dark");
|
||
}
|
||
|
||
#[test]
|
||
fn page_blocks_native_preview_reload_paths() {
|
||
let strings = Strings::english();
|
||
let page = build_page(
|
||
&md_to_html("# Hello"),
|
||
"# Hello",
|
||
None,
|
||
EnhanceFlags::default(),
|
||
&strings,
|
||
false,
|
||
);
|
||
|
||
assert!(page.contains("document.addEventListener('contextmenu'"));
|
||
assert!(page.contains("window.ipc.postMessage('refresh')"));
|
||
assert!(!page.contains("id=\"btn-open\""));
|
||
assert!(!page.contains("id=\"btn-print\""));
|
||
assert!(!page.contains("id=\"btn-search\""));
|
||
assert!(page.contains("window.ipc.postMessage('open')"));
|
||
assert!(page.contains("window.__mdPreviewOpenFile = openFile"));
|
||
assert!(page.contains("window.__mdPreviewShowFind = showFind"));
|
||
assert!(page.contains("window.__mdPreviewToggleEdit"));
|
||
assert!(page
|
||
.contains("if (inEdit()) return;\n\t e.preventDefault();\n\t showFind();"));
|
||
assert!(page.contains("id=\"hljs-code\""));
|
||
assert!(page.contains("#preview pre { background: #1e1e1e;"));
|
||
assert!(!page.contains("hljs-light"));
|
||
assert!(page.contains("ta.focus({ preventScroll: true })"));
|
||
assert!(page.contains("window.__setEmptyPreview"));
|
||
assert!(page.contains("id=\"tabbar\""));
|
||
assert!(page.contains("window.__setTabs"));
|
||
assert!(page.contains("tab-action:'));") || page.contains("'tab-action:' + action"));
|
||
assert!(page.contains("window.__markSaved"));
|
||
assert!(
|
||
!page.contains("window.ipc.postMessage('save:' + ta.value);\n\t setDirty(false);")
|
||
);
|
||
assert!(page.contains("compositionstart"));
|
||
assert!(page.contains("e.isComposing"));
|
||
assert!(page.contains("focusFindInput"));
|
||
assert!(page.contains("FIND_DEBOUNCE_MS = 300"));
|
||
assert!(page.contains("document.createTreeWalker(previewEl, NodeFilter.SHOW_TEXT"));
|
||
assert!(page.contains("mark.className = 'search-hit'"));
|
||
assert!(page.contains("selectFindHit(currentFindHit + (backward ? -1 : 1))"));
|
||
assert!(page.contains("#preview mark.search-hit.current"));
|
||
assert!(page.contains("restoreFindInput(selectionStart, selectionEnd)"));
|
||
assert!(page.contains("findInput.setSelectionRange(selectionStart, selectionEnd)"));
|
||
assert!(page.contains("bindAnchorNavigation"));
|
||
assert!(page.contains("event.target.closest('#preview a[href]')"));
|
||
assert!(page.contains("window.ipc.postMessage('open-local-link:' + href)"));
|
||
assert!(page.contains(".markdown-alert-important"));
|
||
assert!(page.contains(".markdown-alert-title"));
|
||
let light_alert = page.find("background: #dafbe1").unwrap();
|
||
let dark_alert = page.rfind("background: #161b22; color: #d4d4d4").unwrap();
|
||
assert!(dark_alert > light_alert);
|
||
assert!(page.contains(".mdp-mark"));
|
||
assert!(!page.contains("Local-first Markdown preview for AI-generated docs"));
|
||
}
|
||
|
||
#[test]
|
||
fn page_separates_new_file_from_open_and_debounces_autosave() {
|
||
let strings = Strings::english();
|
||
let page = build_page(
|
||
&md_to_html("# Hello"),
|
||
"# Hello",
|
||
None,
|
||
EnhanceFlags::default(),
|
||
&strings,
|
||
false,
|
||
);
|
||
|
||
assert!(page.contains("window.ipc.postMessage('new-file')"));
|
||
assert!(page.contains("tabOpen.addEventListener('click', newTab)"));
|
||
assert!(!page.contains("tabOpen.addEventListener('click', newFile)"));
|
||
assert!(!page.contains("tabOpen.addEventListener('click', openFile)"));
|
||
assert!(page.contains("requestTabAction('new-tab', 0)"));
|
||
assert!(page.contains("data-new-file"));
|
||
assert!(page.contains("HIDE_SINGLE_HOME_TAB = true"));
|
||
assert!(page.contains("tabs.length === 1 && !tabs[0].home"));
|
||
assert!(page.contains("L_HOME = 'New Tab'"));
|
||
assert!(
|
||
page.matches("if (document.body.classList.contains('home')) return;")
|
||
.count()
|
||
>= 2
|
||
);
|
||
assert!(page.contains("if (tabCount === 1 && isHome) close.hidden = true"));
|
||
assert!(page.contains("tabMenuNewWindow.disabled = tabCount <= 1 || isHome"));
|
||
assert!(page.contains("AUTOSAVE_DEBOUNCE_MS = 700"));
|
||
assert!(page.contains("pendingAutosaveTimer = setTimeout"));
|
||
assert!(page.contains("window.__markSaved = function(savedRaw)"));
|
||
assert!(page.contains("window.__markSaveBlocked"));
|
||
assert!(page.contains("var saveBlocked = false"));
|
||
assert!(page.contains("window.__mdPreviewCannotSave"));
|
||
assert!(page.contains("window.__mdPreviewResolveExternalChange"));
|
||
assert!(page.contains("'external-change:' + (dirty ? 'dirty' : 'clean')"));
|
||
assert!(page.contains("(e.key === 'n' || e.key === 'N')"));
|
||
assert!(page.contains("id=\"doc-stats\""));
|
||
assert!(page.contains("id=\"tab-menu\""));
|
||
assert!(page.contains("id=\"tab-menu-path\""));
|
||
assert!(page.contains("id=\"tab-menu-reveal\""));
|
||
assert!(page.contains("data-tab-path"));
|
||
assert!(page.contains("function shortenPath"));
|
||
assert!(page.contains("tabsEl.addEventListener('pointerdown'"));
|
||
assert!(page.contains("suppressTabClickUntil"));
|
||
assert!(page.contains("tabCount = tabs.length"));
|
||
assert!(page.contains("tabMenuNewWindow.disabled = tabCount <= 1"));
|
||
assert!(page.contains("updateDocumentStats"));
|
||
assert!(page.contains("restoreScrollProgress"));
|
||
assert!(page.contains("postMessage('zoom:' + zoomPercent)"));
|
||
assert!(page.contains("window.__mdPreviewSetZoom"));
|
||
assert!(page.contains("id=\"btn-zoom-in\""));
|
||
assert!(page.contains("id=\"btn-zoom-out\""));
|
||
assert!(page.contains("id=\"btn-zoom-reset\""));
|
||
assert!(page.contains("var ZOOM_MIN = 50"));
|
||
assert!(page.contains("var ZOOM_MAX = 300"));
|
||
assert!(page.contains("var ZOOM_STEP = 5"));
|
||
assert!(page.contains("ZOOM_WHEEL_THROTTLE_MS = 90"));
|
||
assert!(page.contains("if (!e.ctrlKey) return;"));
|
||
assert!(page.contains("window.addEventListener('wheel', onContentWheel, { passive: false })"));
|
||
}
|
||
|
||
#[test]
|
||
fn headings_get_hover_fold_toggles() {
|
||
let strings = Strings::english();
|
||
let page = build_page(
|
||
&md_to_html("# A\n\n## B\n\ntext"),
|
||
"# A\n\n## B\n\ntext",
|
||
None,
|
||
EnhanceFlags::default(),
|
||
&strings,
|
||
false,
|
||
);
|
||
|
||
assert!(page.contains("mdp-fold-toggle"));
|
||
assert!(page.contains("mdp-fold-body"));
|
||
assert!(page.contains(".mdp-fold.collapsed > .mdp-fold-body { display: none; }"));
|
||
assert!(page.contains("window.__mdPreviewFoldLabel"));
|
||
assert!(page.contains("window.__mdPreviewExpandFold"));
|
||
assert!(page.contains("sectionizeFolds"));
|
||
}
|
||
|
||
#[test]
|
||
fn closing_the_last_editing_tab_restores_the_empty_preview() {
|
||
let strings = Strings::english();
|
||
let page = build_page(
|
||
&md_to_html("# Hello"),
|
||
"# Hello",
|
||
None,
|
||
EnhanceFlags::default(),
|
||
&strings,
|
||
false,
|
||
);
|
||
let empty_start = page.find("window.__setEmptyPreview = function").unwrap();
|
||
let missing_start = page.find("window.__setMissing = function").unwrap();
|
||
let empty_handler = &page[empty_start..missing_start];
|
||
|
||
assert!(empty_handler.contains("document.body.classList.remove('editing')"));
|
||
assert!(empty_handler.contains("btnToggle.innerHTML = ICON_EDIT"));
|
||
}
|
||
|
||
#[test]
|
||
fn new_markdown_path_keeps_markdown_extensions_and_replaces_other_extensions() {
|
||
assert_eq!(
|
||
normalize_new_markdown_path(PathBuf::from("/tmp/plan")),
|
||
PathBuf::from("/tmp/plan.md")
|
||
);
|
||
assert_eq!(
|
||
normalize_new_markdown_path(PathBuf::from("/tmp/plan.markdown")),
|
||
PathBuf::from("/tmp/plan.markdown")
|
||
);
|
||
assert_eq!(
|
||
normalize_new_markdown_path(PathBuf::from("/tmp/plan.txt")),
|
||
PathBuf::from("/tmp/plan.md")
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn page_expands_multi_column_tables() {
|
||
let strings = Strings::english();
|
||
let page = build_page(
|
||
&md_to_html("| A | B | C | D |\n|---|---|---|---|\n| 1 | 2 | 3 | 4 |"),
|
||
"",
|
||
None,
|
||
EnhanceFlags::default(),
|
||
&strings,
|
||
false,
|
||
);
|
||
|
||
assert!(page.contains("mdp-table-wrap"));
|
||
assert!(page.contains("width: min(calc(100vw - 64px), 1280px)"));
|
||
assert!(page.contains("if(window.__enhancePreview)window.__enhancePreview();"));
|
||
}
|
||
|
||
#[test]
|
||
fn empty_state_exposes_open_and_recent_files() {
|
||
let strings = Strings::english();
|
||
let recent = vec![PathBuf::from("/tmp/example.md")];
|
||
let html = home_preview_html(&strings, &recent);
|
||
|
||
assert!(html.contains("Open File"));
|
||
assert!(html.contains("New File"));
|
||
assert!(html.contains("empty-actions"));
|
||
assert!(html.contains("data-new-file"));
|
||
assert!(html.contains("Recent"));
|
||
assert!(html.contains("example.md"));
|
||
assert!(html.contains("data-recent-index=\"0\""));
|
||
assert!(html.contains(r#"<div class="empty has-recent">"#));
|
||
assert!(html.contains(r#"<div class="icon">#</div>"#));
|
||
assert!(!html.contains("empty-mark"));
|
||
|
||
let page = build_page(
|
||
&html,
|
||
"",
|
||
None,
|
||
EnhanceFlags::default(),
|
||
&strings,
|
||
true,
|
||
);
|
||
assert!(page.contains(".empty.has-recent"));
|
||
assert!(!page.contains(".empty.has-recent .recent { max-height"));
|
||
assert!(page.contains("<body class=\"home\">"));
|
||
assert!(page.contains("body.home .toolbar"));
|
||
}
|
||
|
||
#[test]
|
||
fn tabs_json_marks_home_tabs_without_a_file_path() {
|
||
let mut session = DocumentSession::default();
|
||
let home = session.open_home();
|
||
|
||
let json = tabs_json(&session);
|
||
|
||
assert!(json.contains(&format!(r#""id":{home}"#)), "{json}");
|
||
assert!(json.contains(r#""home":true"#), "{json}");
|
||
assert!(json.contains(r#""path":"""#), "{json}");
|
||
}
|
||
|
||
#[test]
|
||
fn vim_style_target_rewrite_events_reload_current_file() {
|
||
let target = PathBuf::from("/tmp/note.md");
|
||
let ev = Event::new(EventKind::Create(notify::event::CreateKind::File))
|
||
.add_path(PathBuf::from("/tmp/note.md"));
|
||
|
||
assert!(event_should_reload_file(&ev, &target));
|
||
}
|
||
|
||
#[test]
|
||
fn sibling_file_events_do_not_reload_current_file() {
|
||
let target = PathBuf::from("/tmp/note.md");
|
||
let ev = Event::new(EventKind::Modify(notify::event::ModifyKind::Data(
|
||
notify::event::DataChange::Any,
|
||
)))
|
||
.add_path(PathBuf::from("/tmp/other.md"));
|
||
|
||
assert!(!event_should_reload_file(&ev, &target));
|
||
}
|
||
|
||
#[test]
|
||
fn self_write_suppression_checks_disk_content_not_only_time() {
|
||
let dir = temp_test_dir("self-write-suppression");
|
||
let path = dir.join("note.md");
|
||
fs::write(&path, "saved by app").unwrap();
|
||
let record = SelfWriteRecord {
|
||
path: path.clone(),
|
||
content: "saved by app".to_string(),
|
||
};
|
||
|
||
assert!(self_write_still_matches_disk(Some(&record), &path));
|
||
|
||
fs::write(&path, "external edit").unwrap();
|
||
assert!(!self_write_still_matches_disk(Some(&record), &path));
|
||
}
|
||
|
||
#[test]
|
||
fn sync_events_ignore_identical_bytes_but_detect_external_edits_and_reverts() {
|
||
let path = PathBuf::from("note.md");
|
||
let mut observed = Some(b"initial".to_vec());
|
||
let mut own = Some(SelfWriteRecord {
|
||
path: path.clone(),
|
||
content: "saved".to_string(),
|
||
});
|
||
assert!(!file_content_should_reload(
|
||
&path,
|
||
Some(b"initial".to_vec()),
|
||
&mut observed,
|
||
&mut own
|
||
));
|
||
assert!(!file_content_should_reload(
|
||
&path,
|
||
Some(b"saved".to_vec()),
|
||
&mut observed,
|
||
&mut own
|
||
));
|
||
for _ in 0..100 {
|
||
assert!(!file_content_should_reload(
|
||
&path,
|
||
Some(b"saved".to_vec()),
|
||
&mut observed,
|
||
&mut own
|
||
));
|
||
}
|
||
assert!(file_content_should_reload(
|
||
&path,
|
||
Some(b"external".to_vec()),
|
||
&mut observed,
|
||
&mut own
|
||
));
|
||
assert!(file_content_should_reload(
|
||
&path,
|
||
Some(b"saved".to_vec()),
|
||
&mut observed,
|
||
&mut own
|
||
));
|
||
assert!(file_content_should_reload(
|
||
&path,
|
||
None,
|
||
&mut observed,
|
||
&mut own
|
||
));
|
||
assert!(file_content_should_reload(
|
||
&path,
|
||
Some(b"saved".to_vec()),
|
||
&mut observed,
|
||
&mut own
|
||
));
|
||
}
|
||
|
||
#[test]
|
||
fn external_change_protection_uses_dirty_state_from_either_side() {
|
||
assert!(!should_protect_external_change(false, false));
|
||
assert!(should_protect_external_change(true, false));
|
||
assert!(should_protect_external_change(false, true));
|
||
assert!(should_protect_external_change(true, true));
|
||
}
|
||
|
||
#[test]
|
||
fn file_watch_scope_is_parent_directory() {
|
||
let target = PathBuf::from("/tmp/note.md");
|
||
|
||
assert_eq!(watch_scope_for_file(&target), Path::new("/tmp"));
|
||
}
|
||
|
||
#[test]
|
||
fn finder_action_parses_encoded_folder_and_kind() {
|
||
assert_eq!(
|
||
parse_finder_action(
|
||
"mdpreview://finder?action=create&path=%2Ftmp%2FMy%20Notes&kind=md"
|
||
),
|
||
Some(FinderAction::Create {
|
||
folder: PathBuf::from("/tmp/My Notes"),
|
||
kind: "md".to_string(),
|
||
})
|
||
);
|
||
assert!(parse_finder_action("https://example.com/").is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn finder_create_uses_non_conflicting_markdown_name() {
|
||
let dir = temp_test_dir("finder-create");
|
||
fs::write(dir.join("Untitled.md"), "existing").unwrap();
|
||
|
||
let created = create_finder_file(&dir, "md").unwrap();
|
||
|
||
assert_eq!(created.file_name().unwrap(), "Untitled 2.md");
|
||
assert_eq!(fs::read_to_string(created).unwrap(), "");
|
||
let _ = fs::remove_dir_all(dir);
|
||
}
|
||
}
|
||
|
||
/// Decode embedded icon.ico to an RGBA tao Icon for the window chrome.
|
||
fn load_window_icon() -> Option<tao::window::Icon> {
|
||
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()
|
||
}
|
||
|
||
#[cfg(target_os = "macos")]
|
||
fn register_as_default() {
|
||
use std::process::Command;
|
||
let marker = config_dir().join(".md-preview-registered");
|
||
if marker.exists() {
|
||
return;
|
||
}
|
||
let _ = Command::new("swift")
|
||
.arg("-")
|
||
.stdin(std::process::Stdio::piped())
|
||
.spawn()
|
||
.and_then(|mut child| {
|
||
use std::io::Write;
|
||
if let Some(ref mut stdin) = child.stdin {
|
||
let _ = stdin.write_all(b"import Foundation\nimport CoreServices\nlet _ = LSSetDefaultRoleHandlerForContentType(\"net.daringfireball.markdown\" as NSString, .viewer, \"com.mdpreview.app\" as NSString)\n");
|
||
}
|
||
child.wait()
|
||
});
|
||
let _ = fs::create_dir_all(marker.parent().unwrap());
|
||
let _ = fs::write(&marker, "");
|
||
}
|
||
|
||
/// Windows: register the ProgID in HKCU and advertise it once for Markdown
|
||
/// extensions so MD Preview shows up in the "Open with" list. Win8+ blocks
|
||
/// silent default-handler changes — only the Settings app can confirm those.
|
||
#[cfg(target_os = "windows")]
|
||
fn register_as_default() {
|
||
use winreg::enums::HKEY_CURRENT_USER;
|
||
use winreg::RegKey;
|
||
|
||
let Ok(exe) = std::env::current_exe() else {
|
||
return;
|
||
};
|
||
let exe_str = exe.to_string_lossy().to_string();
|
||
let progid = "MDPreview.md";
|
||
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
|
||
|
||
// Refresh the ProgID command on every launch: the exe is portable, so a
|
||
// moved or renamed binary must not leave "Open with" pointing at a stale path.
|
||
let progid_root = format!(r"Software\Classes\{progid}");
|
||
if let Ok((k, _)) = hkcu.create_subkey(&progid_root) {
|
||
let _ = k.set_value("", &"Markdown Document".to_string());
|
||
let _ = k.set_value("FriendlyTypeName", &"Markdown Document".to_string());
|
||
}
|
||
if let Ok((k, _)) = hkcu.create_subkey(format!(r"{progid_root}\DefaultIcon")) {
|
||
let _ = k.set_value("", &format!("\"{exe_str}\",0"));
|
||
}
|
||
if let Ok((k, _)) = hkcu.create_subkey(format!(r"{progid_root}\shell\open\command")) {
|
||
let _ = k.set_value("", &format!("\"{exe_str}\" \"%1\""));
|
||
}
|
||
|
||
// Applications\<exe-name> entry gives us a friendly label in the "Open with" menu.
|
||
if let Some(exe_name) = exe.file_name().map(|n| n.to_string_lossy().to_string()) {
|
||
let app_root = format!(r"Software\Classes\Applications\{exe_name}");
|
||
if let Ok((k, _)) = hkcu.create_subkey(&app_root) {
|
||
let _ = k.set_value("FriendlyAppName", &"MD Preview".to_string());
|
||
}
|
||
if let Ok((k, _)) = hkcu.create_subkey(format!(r"{app_root}\shell\open\command")) {
|
||
let _ = k.set_value("", &format!("\"{exe_str}\" \"%1\""));
|
||
}
|
||
if let Ok((k, _)) = hkcu.create_subkey(format!(r"{app_root}\SupportedTypes")) {
|
||
for ext in [".md", ".markdown", ".mdown", ".mkd"] {
|
||
let _ = k.set_value::<String, _>(ext, &String::new());
|
||
}
|
||
}
|
||
}
|
||
|
||
// Advertise the ProgID once; re-running this is unnecessary.
|
||
let marker_dir = config_dir();
|
||
let marker = marker_dir.join(".md-preview-registered");
|
||
if marker.exists() {
|
||
return;
|
||
}
|
||
for ext in [".md", ".markdown", ".mdown", ".mkd"] {
|
||
let path = format!(r"Software\Classes\{ext}\OpenWithProgids");
|
||
if let Ok((key, _)) = hkcu.create_subkey(&path) {
|
||
let _ = key.set_value::<String, _>(progid, &String::new());
|
||
}
|
||
}
|
||
|
||
let _ = fs::create_dir_all(&marker_dir);
|
||
let _ = fs::write(&marker, "");
|
||
// Intentionally no dialog: users can pick MD Preview via "Open with"
|
||
// whenever they want, and Win10+ blocks silent default-handler changes
|
||
// anyway — asking them to click through Settings on first launch is noise.
|
||
}
|
||
|
||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||
fn register_as_default() {}
|
||
|
||
#[cfg(target_os = "macos")]
|
||
thread_local! {
|
||
static MACOS_MENU_PROXY: std::cell::RefCell<Option<EventLoopProxy<UserEvent>>> =
|
||
const { std::cell::RefCell::new(None) };
|
||
}
|
||
|
||
#[cfg(target_os = "macos")]
|
||
fn send_macos_menu_event(event: UserEvent) {
|
||
MACOS_MENU_PROXY.with(|cell| {
|
||
if let Some(proxy) = cell.borrow().as_ref() {
|
||
let _ = proxy.send_event(event);
|
||
}
|
||
});
|
||
}
|
||
|
||
#[cfg(target_os = "macos")]
|
||
fn macos_menu_controller_class() -> &'static objc2::runtime::AnyClass {
|
||
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, NSObject, Sel};
|
||
use objc2::{sel, ClassType, MainThreadOnly};
|
||
use objc2_app_kit::{
|
||
NSAlert, NSAlertStyle, NSButton, NSControlStateValueOff, NSControlStateValueOn, NSImage,
|
||
NSMenuItem, NSView,
|
||
};
|
||
use objc2_foundation::{MainThreadMarker, NSPoint, NSRect, NSSize, NSString};
|
||
use std::sync::Once;
|
||
|
||
extern "C" fn open_file(_: &AnyObject, _: Sel, _: &AnyObject) {
|
||
send_macos_menu_event(UserEvent::OpenFile);
|
||
}
|
||
|
||
extern "C" fn new_file(_: &AnyObject, _: Sel, _: &AnyObject) {
|
||
send_macos_menu_event(UserEvent::NewFile);
|
||
}
|
||
|
||
extern "C" fn close_tab(_: &AnyObject, _: Sel, _: &AnyObject) {
|
||
send_macos_menu_event(UserEvent::CloseActiveTab);
|
||
}
|
||
|
||
extern "C" fn show_find(_: &AnyObject, _: Sel, _: &AnyObject) {
|
||
send_macos_menu_event(UserEvent::ShowFind);
|
||
}
|
||
|
||
extern "C" fn toggle_edit(_: &AnyObject, _: Sel, _: &AnyObject) {
|
||
send_macos_menu_event(UserEvent::ToggleEdit);
|
||
}
|
||
|
||
extern "C" fn print(_: &AnyObject, _: Sel, _: &AnyObject) {
|
||
send_macos_menu_event(UserEvent::Print);
|
||
}
|
||
|
||
extern "C" fn quit(_: &AnyObject, _: Sel, _: &AnyObject) {
|
||
send_macos_menu_event(UserEvent::Quit);
|
||
}
|
||
|
||
extern "C" fn set_theme(_: &AnyObject, _: Sel, sender: &NSMenuItem) {
|
||
let choice = match sender.tag() {
|
||
102 => ThemeChoice::Light,
|
||
103 => ThemeChoice::Dark,
|
||
_ => ThemeChoice::System,
|
||
};
|
||
let selected = sender.tag();
|
||
if let Some(menu) = unsafe { sender.menu() } {
|
||
for index in 0..menu.numberOfItems() {
|
||
if let Some(item) = menu.itemAtIndex(index) {
|
||
let tag = item.tag();
|
||
if (101..=103).contains(&tag) {
|
||
item.setState(if tag == selected {
|
||
NSControlStateValueOn
|
||
} else {
|
||
NSControlStateValueOff
|
||
});
|
||
}
|
||
}
|
||
}
|
||
}
|
||
send_macos_menu_event(UserEvent::SetTheme(choice));
|
||
}
|
||
|
||
fn rect(x: f64, y: f64, width: f64, height: f64) -> NSRect {
|
||
NSRect::new(NSPoint::new(x, y), NSSize::new(width, height))
|
||
}
|
||
|
||
fn symbol_button(
|
||
symbol: &str,
|
||
fallback_title: &str,
|
||
tooltip: &str,
|
||
action: Sel,
|
||
target: &AnyObject,
|
||
mtm: MainThreadMarker,
|
||
) -> objc2::rc::Retained<NSButton> {
|
||
let accessibility = NSString::from_str(tooltip);
|
||
let symbol_name = NSString::from_str(symbol);
|
||
let button = if let Some(image) =
|
||
NSImage::imageWithSystemSymbolName_accessibilityDescription(
|
||
&symbol_name,
|
||
Some(&accessibility),
|
||
) {
|
||
unsafe {
|
||
NSButton::buttonWithImage_target_action(&image, Some(target), Some(action), mtm)
|
||
}
|
||
} else {
|
||
unsafe {
|
||
NSButton::buttonWithTitle_target_action(
|
||
&NSString::from_str(fallback_title),
|
||
Some(target),
|
||
Some(action),
|
||
mtm,
|
||
)
|
||
}
|
||
};
|
||
button.setBordered(false);
|
||
button.setToolTip(Some(&accessibility));
|
||
button
|
||
}
|
||
|
||
extern "C" fn show_about(controller: &AnyObject, _: Sel, _: &AnyObject) {
|
||
let Some(mtm) = MainThreadMarker::new() else {
|
||
return;
|
||
};
|
||
|
||
let alert = NSAlert::new(mtm);
|
||
alert.setAlertStyle(NSAlertStyle::Informational);
|
||
alert.setMessageText(&NSString::from_str("MD Preview"));
|
||
alert.setInformativeText(&NSString::from_str(&format!(
|
||
"Version {}\n\nFollow local document links between lightweight tabs, keep your reading position between preview and source, and inspect character counts or zoom the content without changing the app chrome.",
|
||
env!("CARGO_PKG_VERSION")
|
||
)));
|
||
|
||
alert.addButtonWithTitle(&NSString::from_str("OK"));
|
||
|
||
alert.runModal();
|
||
}
|
||
|
||
static REGISTER_CLASS: Once = Once::new();
|
||
REGISTER_CLASS.call_once(|| {
|
||
let mut builder = ClassBuilder::new(c"MDPreviewMenuController", NSObject::class()).unwrap();
|
||
unsafe {
|
||
builder.add_method(
|
||
sel!(mdPreviewOpenFile:),
|
||
open_file as extern "C" fn(_, _, _),
|
||
);
|
||
builder.add_method(sel!(mdPreviewNewFile:), new_file as extern "C" fn(_, _, _));
|
||
builder.add_method(
|
||
sel!(mdPreviewCloseTab:),
|
||
close_tab as extern "C" fn(_, _, _),
|
||
);
|
||
builder.add_method(
|
||
sel!(mdPreviewShowFind:),
|
||
show_find as extern "C" fn(_, _, _),
|
||
);
|
||
builder.add_method(
|
||
sel!(mdPreviewToggleEdit:),
|
||
toggle_edit as extern "C" fn(_, _, _),
|
||
);
|
||
builder.add_method(sel!(mdPreviewPrint:), print as extern "C" fn(_, _, _));
|
||
builder.add_method(
|
||
sel!(mdPreviewSetTheme:),
|
||
set_theme as extern "C" fn(_, _, _),
|
||
);
|
||
builder.add_method(
|
||
sel!(mdPreviewShowAbout:),
|
||
show_about as extern "C" fn(_, _, _),
|
||
);
|
||
}
|
||
let _ = builder.register();
|
||
});
|
||
|
||
AnyClass::get(c"MDPreviewMenuController").unwrap()
|
||
}
|
||
|
||
#[cfg(target_os = "macos")]
|
||
fn install_macos_menu(proxy: EventLoopProxy<UserEvent>, theme: ThemeChoice) {
|
||
use objc2::rc::Retained;
|
||
use objc2::runtime::{AnyObject, Sel};
|
||
use objc2::{msg_send, sel, MainThreadOnly};
|
||
use objc2_app_kit::{
|
||
NSApplication, NSControlStateValueOff, NSControlStateValueOn, NSEventModifierFlags, NSMenu,
|
||
NSMenuItem,
|
||
};
|
||
use objc2_foundation::{MainThreadMarker, NSString};
|
||
|
||
let Some(mtm) = MainThreadMarker::new() else {
|
||
return;
|
||
};
|
||
MACOS_MENU_PROXY.with(|cell| {
|
||
*cell.borrow_mut() = Some(proxy);
|
||
});
|
||
|
||
fn menu(title: &str, mtm: MainThreadMarker) -> objc2::rc::Retained<NSMenu> {
|
||
NSMenu::initWithTitle(NSMenu::alloc(mtm), &NSString::from_str(title))
|
||
}
|
||
|
||
fn item(
|
||
title: &str,
|
||
action: Option<Sel>,
|
||
key: &str,
|
||
modifiers: NSEventModifierFlags,
|
||
mtm: MainThreadMarker,
|
||
) -> objc2::rc::Retained<NSMenuItem> {
|
||
let item = unsafe {
|
||
NSMenuItem::initWithTitle_action_keyEquivalent(
|
||
NSMenuItem::alloc(mtm),
|
||
&NSString::from_str(title),
|
||
action,
|
||
&NSString::from_str(key),
|
||
)
|
||
};
|
||
item.setKeyEquivalentModifierMask(modifiers);
|
||
item
|
||
}
|
||
|
||
fn command_item(
|
||
title: &str,
|
||
action: Sel,
|
||
key: &str,
|
||
modifiers: NSEventModifierFlags,
|
||
target: &AnyObject,
|
||
mtm: MainThreadMarker,
|
||
) -> objc2::rc::Retained<NSMenuItem> {
|
||
let item = item(title, Some(action), key, modifiers, mtm);
|
||
unsafe {
|
||
item.setTarget(Some(target));
|
||
}
|
||
item
|
||
}
|
||
|
||
let app = NSApplication::sharedApplication(mtm);
|
||
let main_menu = menu("", mtm);
|
||
let controller: Retained<AnyObject> = unsafe { msg_send![macos_menu_controller_class(), new] };
|
||
let controller_ptr = Retained::into_raw(controller);
|
||
let controller = unsafe { &*controller_ptr };
|
||
|
||
let app_menu = menu("MD Preview", mtm);
|
||
app_menu.setAutoenablesItems(false);
|
||
app_menu.addItem(&command_item(
|
||
"About MD Preview",
|
||
sel!(mdPreviewShowAbout:),
|
||
"",
|
||
NSEventModifierFlags::empty(),
|
||
controller,
|
||
mtm,
|
||
));
|
||
app_menu.addItem(&NSMenuItem::separatorItem(mtm));
|
||
app_menu.addItem(&command_item(
|
||
"Quit MD Preview",
|
||
sel!(mdPreviewQuit:),
|
||
"q",
|
||
NSEventModifierFlags::Command,
|
||
controller,
|
||
mtm,
|
||
));
|
||
let app_menu_item = item("MD Preview", None, "", NSEventModifierFlags::empty(), mtm);
|
||
app_menu_item.setSubmenu(Some(&app_menu));
|
||
main_menu.addItem(&app_menu_item);
|
||
|
||
let file_menu = menu("File", mtm);
|
||
file_menu.setAutoenablesItems(false);
|
||
file_menu.addItem(&command_item(
|
||
"New Markdown...",
|
||
sel!(mdPreviewNewFile:),
|
||
"n",
|
||
NSEventModifierFlags::Command,
|
||
controller,
|
||
mtm,
|
||
));
|
||
file_menu.addItem(&command_item(
|
||
"Open...",
|
||
sel!(mdPreviewOpenFile:),
|
||
"o",
|
||
NSEventModifierFlags::Command,
|
||
controller,
|
||
mtm,
|
||
));
|
||
file_menu.addItem(&command_item(
|
||
"Close Tab",
|
||
sel!(mdPreviewCloseTab:),
|
||
"w",
|
||
NSEventModifierFlags::Command,
|
||
controller,
|
||
mtm,
|
||
));
|
||
file_menu.addItem(&NSMenuItem::separatorItem(mtm));
|
||
file_menu.addItem(&command_item(
|
||
"Print...",
|
||
sel!(mdPreviewPrint:),
|
||
"p",
|
||
NSEventModifierFlags::Command,
|
||
controller,
|
||
mtm,
|
||
));
|
||
let file_menu_item = item("File", None, "", NSEventModifierFlags::empty(), mtm);
|
||
file_menu_item.setSubmenu(Some(&file_menu));
|
||
main_menu.addItem(&file_menu_item);
|
||
|
||
let edit_menu = menu("Edit", mtm);
|
||
edit_menu.addItem(&item(
|
||
"Undo",
|
||
Some(sel!(undo:)),
|
||
"z",
|
||
NSEventModifierFlags::Command,
|
||
mtm,
|
||
));
|
||
edit_menu.addItem(&item(
|
||
"Redo",
|
||
Some(sel!(redo:)),
|
||
"z",
|
||
NSEventModifierFlags::Command | NSEventModifierFlags::Shift,
|
||
mtm,
|
||
));
|
||
edit_menu.addItem(&NSMenuItem::separatorItem(mtm));
|
||
edit_menu.addItem(&item(
|
||
"Cut",
|
||
Some(sel!(cut:)),
|
||
"x",
|
||
NSEventModifierFlags::Command,
|
||
mtm,
|
||
));
|
||
edit_menu.addItem(&item(
|
||
"Copy",
|
||
Some(sel!(copy:)),
|
||
"c",
|
||
NSEventModifierFlags::Command,
|
||
mtm,
|
||
));
|
||
edit_menu.addItem(&item(
|
||
"Paste",
|
||
Some(sel!(paste:)),
|
||
"v",
|
||
NSEventModifierFlags::Command,
|
||
mtm,
|
||
));
|
||
edit_menu.addItem(&item(
|
||
"Select All",
|
||
Some(sel!(selectAll:)),
|
||
"a",
|
||
NSEventModifierFlags::Command,
|
||
mtm,
|
||
));
|
||
let edit_menu_item = item("Edit", None, "", NSEventModifierFlags::empty(), mtm);
|
||
edit_menu_item.setSubmenu(Some(&edit_menu));
|
||
main_menu.addItem(&edit_menu_item);
|
||
|
||
let view_menu = menu("View", mtm);
|
||
view_menu.setAutoenablesItems(false);
|
||
view_menu.addItem(&command_item(
|
||
"Find",
|
||
sel!(mdPreviewShowFind:),
|
||
"",
|
||
NSEventModifierFlags::empty(),
|
||
controller,
|
||
mtm,
|
||
));
|
||
view_menu.addItem(&command_item(
|
||
"Toggle Edit Mode",
|
||
sel!(mdPreviewToggleEdit:),
|
||
"e",
|
||
NSEventModifierFlags::Command,
|
||
controller,
|
||
mtm,
|
||
));
|
||
view_menu.addItem(&NSMenuItem::separatorItem(mtm));
|
||
let theme_menu = menu("Theme", mtm);
|
||
theme_menu.setAutoenablesItems(false);
|
||
for (label, choice, tag) in [
|
||
("System", ThemeChoice::System, 101),
|
||
("Light", ThemeChoice::Light, 102),
|
||
("Dark", ThemeChoice::Dark, 103),
|
||
] {
|
||
let theme_item = command_item(
|
||
label,
|
||
sel!(mdPreviewSetTheme:),
|
||
"",
|
||
NSEventModifierFlags::empty(),
|
||
controller,
|
||
mtm,
|
||
);
|
||
theme_item.setTag(tag);
|
||
theme_item.setState(if choice == theme {
|
||
NSControlStateValueOn
|
||
} else {
|
||
NSControlStateValueOff
|
||
});
|
||
theme_menu.addItem(&theme_item);
|
||
}
|
||
let theme_menu_item = item("Theme", None, "", NSEventModifierFlags::empty(), mtm);
|
||
theme_menu_item.setSubmenu(Some(&theme_menu));
|
||
view_menu.addItem(&theme_menu_item);
|
||
let view_menu_item = item("View", None, "", NSEventModifierFlags::empty(), mtm);
|
||
view_menu_item.setSubmenu(Some(&view_menu));
|
||
main_menu.addItem(&view_menu_item);
|
||
|
||
app.setMainMenu(Some(&main_menu));
|
||
}
|
||
|
||
#[cfg(not(target_os = "macos"))]
|
||
fn install_macos_menu(_proxy: EventLoopProxy<UserEvent>, _theme: ThemeChoice) {}
|
||
|
||
#[cfg(any(target_os = "linux", test))]
|
||
fn linux_webkit_compat_env(
|
||
disable_dmabuf: Option<&str>,
|
||
disable_compositing: Option<&str>,
|
||
nvidia_driver_present: bool,
|
||
) -> Option<(&'static str, &'static str)> {
|
||
if disable_dmabuf.is_some() || disable_compositing.is_some() || !nvidia_driver_present {
|
||
return None;
|
||
}
|
||
|
||
Some(("WEBKIT_DISABLE_DMABUF_RENDERER", "1"))
|
||
}
|
||
|
||
#[cfg(target_os = "linux")]
|
||
fn apply_linux_webkit_compat_env() {
|
||
let nvidia_driver_present = Path::new("/proc/driver/nvidia/version").exists();
|
||
if let Some((key, value)) = linux_webkit_compat_env(
|
||
std::env::var("WEBKIT_DISABLE_DMABUF_RENDERER")
|
||
.ok()
|
||
.as_deref(),
|
||
std::env::var("WEBKIT_DISABLE_COMPOSITING_MODE")
|
||
.ok()
|
||
.as_deref(),
|
||
nvidia_driver_present,
|
||
) {
|
||
std::env::set_var(key, value);
|
||
}
|
||
}
|
||
|
||
#[cfg(not(target_os = "linux"))]
|
||
fn apply_linux_webkit_compat_env() {}
|
||
|
||
fn is_supported_document(path: &Path) -> bool {
|
||
path.extension()
|
||
.map(|extension| {
|
||
matches!(
|
||
extension.to_string_lossy().to_ascii_lowercase().as_str(),
|
||
"md" | "markdown" | "mdown" | "mkd" | "txt"
|
||
)
|
||
})
|
||
.unwrap_or(false)
|
||
}
|
||
|
||
#[cfg(windows)]
|
||
fn reveal_in_explorer(path: &Path) -> bool {
|
||
let mut command = std::process::Command::new("explorer.exe");
|
||
if path.is_file() {
|
||
command.arg("/select,").arg(path);
|
||
} else if let Some(parent) = path.parent().filter(|parent| parent.is_dir()) {
|
||
command.arg(parent);
|
||
} else {
|
||
return false;
|
||
}
|
||
command.spawn().is_ok()
|
||
}
|
||
|
||
#[cfg(not(windows))]
|
||
fn reveal_in_explorer(path: &Path) -> bool {
|
||
let target = if path.exists() {
|
||
path
|
||
} else {
|
||
path.parent().unwrap_or(path)
|
||
};
|
||
open::that(target).is_ok()
|
||
}
|
||
|
||
fn resolve_document_link(value: &str, active: Option<&Path>) -> Option<PathBuf> {
|
||
let url = match url::Url::parse(value) {
|
||
Ok(url) => url,
|
||
Err(url::ParseError::RelativeUrlWithoutBase) => {
|
||
url::Url::from_file_path(active?).ok()?.join(value).ok()?
|
||
}
|
||
Err(_) => return None,
|
||
};
|
||
local_document_path_from_url(url.as_str())
|
||
}
|
||
|
||
fn local_document_path_from_url(value: &str) -> Option<PathBuf> {
|
||
let url = url::Url::parse(value).ok()?;
|
||
if url.scheme() != "file" {
|
||
return None;
|
||
}
|
||
let path = url.to_file_path().ok()?;
|
||
if !path.is_file() || !is_supported_document(&path) {
|
||
return None;
|
||
}
|
||
fs::canonicalize(path).ok()
|
||
}
|
||
|
||
fn install_file_watcher(
|
||
holder: &Arc<Mutex<Option<notify::RecommendedWatcher>>>,
|
||
proxy: &EventLoopProxy<UserEvent>,
|
||
last_self_write: &Arc<Mutex<Option<SelfWriteRecord>>>,
|
||
window_id: WindowId,
|
||
path: Option<PathBuf>,
|
||
) {
|
||
let mut current = holder.lock().unwrap();
|
||
*current = None;
|
||
*last_self_write.lock().unwrap() = None;
|
||
let Some(path) = path else {
|
||
return;
|
||
};
|
||
let mut observed_content = fs::read(&path).ok();
|
||
let target_path = path.clone();
|
||
let callback_path = path.clone();
|
||
let proxy = proxy.clone();
|
||
let last_self_write = Arc::clone(last_self_write);
|
||
if let Ok(mut watcher) = notify::recommended_watcher(move |result: Result<Event, _>| {
|
||
if let Ok(event) = result {
|
||
if event_should_reload_file(&event, &callback_path) {
|
||
let content = fs::read(&callback_path).ok();
|
||
let mut last_self_write = last_self_write.lock().unwrap();
|
||
if file_content_should_reload(
|
||
&callback_path,
|
||
content,
|
||
&mut observed_content,
|
||
&mut last_self_write,
|
||
) {
|
||
let _ =
|
||
proxy.send_event(UserEvent::FileChanged(window_id, callback_path.clone()));
|
||
}
|
||
}
|
||
}
|
||
}) {
|
||
let scope = watch_scope_for_file(&target_path);
|
||
if scope.exists() && watcher.watch(scope, RecursiveMode::NonRecursive).is_ok() {
|
||
*current = Some(watcher);
|
||
}
|
||
}
|
||
}
|
||
|
||
fn file_content_should_reload(
|
||
path: &Path,
|
||
content: Option<Vec<u8>>,
|
||
observed: &mut Option<Vec<u8>>,
|
||
last_self_write: &mut Option<SelfWriteRecord>,
|
||
) -> bool {
|
||
if content == *observed {
|
||
return false;
|
||
}
|
||
let is_self_write = last_self_write.as_ref().is_some_and(|record| {
|
||
record.path == path && content.as_deref() == Some(record.content.as_bytes())
|
||
});
|
||
*observed = content;
|
||
if is_self_write {
|
||
return false;
|
||
}
|
||
// A subsequent revert to our old snapshot is a real change too.
|
||
if observed.is_some() {
|
||
*last_self_write = None;
|
||
}
|
||
true
|
||
}
|
||
|
||
fn self_write_still_matches_disk(record: Option<&SelfWriteRecord>, path: &Path) -> bool {
|
||
let Some(record) = record else {
|
||
return false;
|
||
};
|
||
record.path == path
|
||
&& fs::read(path)
|
||
.map(|content| content == record.content.as_bytes())
|
||
.unwrap_or(false)
|
||
}
|
||
|
||
fn should_protect_external_change(webview_dirty: bool, session_dirty: bool) -> bool {
|
||
webview_dirty || session_dirty
|
||
}
|
||
|
||
#[derive(Debug, PartialEq, Eq)]
|
||
enum FinderAction {
|
||
Create { folder: PathBuf, kind: String },
|
||
Terminal { folder: PathBuf },
|
||
}
|
||
|
||
fn parse_finder_action(value: &str) -> Option<FinderAction> {
|
||
let url = url::Url::parse(value).ok()?;
|
||
if url.scheme() != "mdpreview" || url.host_str() != Some("finder") {
|
||
return None;
|
||
}
|
||
let query = url.query_pairs().collect::<HashMap<_, _>>();
|
||
let folder = PathBuf::from(query.get("path")?.as_ref());
|
||
match query.get("action")?.as_ref() {
|
||
"create" => Some(FinderAction::Create {
|
||
folder,
|
||
kind: query
|
||
.get("kind")
|
||
.map(|value| value.to_string())
|
||
.unwrap_or_else(|| "md".to_string()),
|
||
}),
|
||
"terminal" => Some(FinderAction::Terminal { folder }),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
fn create_finder_file(folder: &Path, kind: &str) -> std::io::Result<PathBuf> {
|
||
if !folder.is_dir() {
|
||
return Err(std::io::Error::new(
|
||
std::io::ErrorKind::NotFound,
|
||
"Finder target folder does not exist",
|
||
));
|
||
}
|
||
let (extension, contents): (&str, &[u8]) = match kind {
|
||
"txt" => ("txt", b""),
|
||
"json" => ("json", b"{}\n"),
|
||
"html" => (
|
||
"html",
|
||
b"<!doctype html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <title></title>\n</head>\n<body>\n</body>\n</html>\n",
|
||
),
|
||
_ => ("md", b""),
|
||
};
|
||
let mut path = folder.join(format!("Untitled.{extension}"));
|
||
let mut index = 2;
|
||
while path.exists() {
|
||
path = folder.join(format!("Untitled {index}.{extension}"));
|
||
index += 1;
|
||
}
|
||
fs::write(&path, contents)?;
|
||
Ok(path)
|
||
}
|
||
|
||
fn normalize_new_markdown_path(mut path: PathBuf) -> PathBuf {
|
||
let is_markdown = path
|
||
.extension()
|
||
.and_then(|extension| extension.to_str())
|
||
.map(|extension| {
|
||
matches!(
|
||
extension.to_ascii_lowercase().as_str(),
|
||
"md" | "markdown" | "mdown" | "mkd"
|
||
)
|
||
})
|
||
.unwrap_or(false);
|
||
if !is_markdown {
|
||
path.set_extension("md");
|
||
}
|
||
path
|
||
}
|
||
|
||
fn open_terminal(folder: &Path) -> bool {
|
||
std::process::Command::new("open")
|
||
.args(["-a", "Terminal"])
|
||
.arg(folder)
|
||
.spawn()
|
||
.is_ok()
|
||
}
|
||
|
||
#[cfg(target_os = "macos")]
|
||
fn register_finder_extension() {
|
||
let Ok(executable) = std::env::current_exe() else {
|
||
return;
|
||
};
|
||
let Some(contents) = executable.parent().and_then(Path::parent) else {
|
||
return;
|
||
};
|
||
let Some(bundle) = contents.parent() else {
|
||
return;
|
||
};
|
||
let extension = bundle.join("Contents/PlugIns/MDPreviewFinderExtension.appex");
|
||
if bundle.extension().and_then(|value| value.to_str()) != Some("app") || !extension.exists() {
|
||
return;
|
||
}
|
||
|
||
let marker = config_dir().join(".finder-extension-onboarded-v1");
|
||
let lsregister = "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister";
|
||
let _ = std::process::Command::new(lsregister)
|
||
.args(["-f", "-R", "-trusted"])
|
||
.arg(bundle)
|
||
.status();
|
||
let _ = std::process::Command::new("pluginkit")
|
||
.arg("-a")
|
||
.arg(bundle)
|
||
.status();
|
||
let _ = std::process::Command::new("pluginkit")
|
||
.args(["-e", "use", "-i", "com.mdpreview.app.FinderExtension"])
|
||
.status();
|
||
|
||
if marker.exists() {
|
||
return;
|
||
}
|
||
let active = std::process::Command::new("pluginkit")
|
||
.args(["-m", "-A", "-p", "com.apple.FinderSync"])
|
||
.output()
|
||
.ok()
|
||
.filter(|output| output.status.success())
|
||
.map(|output| String::from_utf8_lossy(&output.stdout).into_owned())
|
||
.map(|output| {
|
||
output.lines().any(|line| {
|
||
line.trim_start().starts_with('+')
|
||
&& line.contains("com.mdpreview.app.FinderExtension")
|
||
})
|
||
})
|
||
.unwrap_or(false);
|
||
if !active {
|
||
show_info_dialog(
|
||
"Enable the Finder Extension",
|
||
"Open System Settings > General > Login Items & Extensions > Finder, then enable MD Preview.",
|
||
);
|
||
}
|
||
let _ = fs::create_dir_all(config_dir());
|
||
let _ = fs::write(marker, "1");
|
||
}
|
||
|
||
#[cfg(not(target_os = "macos"))]
|
||
fn register_finder_extension() {}
|
||
|
||
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<Mutex<Vec<PathBuf>>>,
|
||
strings: &Strings,
|
||
proxy: &EventLoopProxy<UserEvent>,
|
||
) -> 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<Mutex<Vec<PathBuf>>>,
|
||
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);
|
||
}
|
||
|
||
fn render_active_document(
|
||
webview: &WebView,
|
||
window: &Window,
|
||
session: &mut DocumentSession,
|
||
recent_files: &Arc<Mutex<Vec<PathBuf>>>,
|
||
enhance_flags: &Arc<Mutex<EnhanceFlags>>,
|
||
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(&format!(
|
||
"if(window.__setContent)window.__setContent('{}', '{}', '{}', {}, {});",
|
||
escape_js(&html),
|
||
escape_js(&raw),
|
||
escape_js(&base_href),
|
||
flags.math,
|
||
flags.mermaid
|
||
));
|
||
for script in build_enhancer_bootstrap(flags, *loaded_enhancers) {
|
||
let _ = webview.evaluate_script(&script);
|
||
}
|
||
loaded_enhancers.math |= flags.math;
|
||
loaded_enhancers.mermaid |= flags.mermaid;
|
||
if active.edit_on_open {
|
||
if let Some(tab) = session.get_mut(active.id) {
|
||
tab.edit_on_open = false;
|
||
}
|
||
let _ = webview.evaluate_script(
|
||
"if(window.__mdPreviewEnterEdit)window.__mdPreviewEnterEdit();",
|
||
);
|
||
}
|
||
}
|
||
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#"<div class="missing-file"><h2>{}</h2><p>{}</p><code>{}</code><button type="button" data-open-file>{}</button><button type="button" data-close-tab="{}">{}</button></div>"#,
|
||
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,
|
||
)
|
||
}
|
||
|
||
fn build_webview(
|
||
window: &Window,
|
||
web_context: &mut WebContext,
|
||
window_id: WindowId,
|
||
session: Arc<Mutex<DocumentSession>>,
|
||
last_self_write: Arc<Mutex<Option<SelfWriteRecord>>>,
|
||
recent_files: Arc<Mutex<Vec<PathBuf>>>,
|
||
proxy: EventLoopProxy<UserEvent>,
|
||
initial_page: String,
|
||
) -> Result<WebView, String> {
|
||
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 if url.starts_with("file:") {
|
||
false
|
||
} else {
|
||
true
|
||
}
|
||
})
|
||
.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::<usize>() {
|
||
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(2, ':');
|
||
let action = parts.next().unwrap_or("");
|
||
let id = parts.next().and_then(|value| value.parse::<u64>().ok());
|
||
let Some(id) = id else {
|
||
return;
|
||
};
|
||
if let Some(content) = pending_content {
|
||
let path = session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||
let Some(path) = path else {
|
||
return;
|
||
};
|
||
*last_self_write.lock().unwrap() = Some(SelfWriteRecord {
|
||
path: path.clone(),
|
||
content: content.to_string(),
|
||
});
|
||
match fs::write(&path, content) {
|
||
Ok(()) => {
|
||
let _ = proxy_for_ipc.send_event(UserEvent::FileSaved(window_id, path));
|
||
}
|
||
Err(error) => {
|
||
let _ = proxy_for_ipc.send_event(UserEvent::SaveFailed(
|
||
window_id,
|
||
path.clone(),
|
||
error.to_string(),
|
||
));
|
||
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::<u64>() {
|
||
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::<u64>() {
|
||
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::<u32>() {
|
||
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:") {
|
||
let path = session.lock().unwrap().active_path().map(Path::to_path_buf);
|
||
if let Some(path) = path {
|
||
*last_self_write.lock().unwrap() = Some(SelfWriteRecord {
|
||
path: path.clone(),
|
||
content: content.to_string(),
|
||
});
|
||
match fs::write(&path, content) {
|
||
Ok(()) => {
|
||
let _ = proxy_for_ipc.send_event(UserEvent::FileSaved(window_id, path));
|
||
}
|
||
Err(error) => {
|
||
let _ = proxy_for_ipc.send_event(UserEvent::SaveFailed(
|
||
window_id,
|
||
path.clone(),
|
||
error.to_string(),
|
||
));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
})
|
||
.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::<Vec<_>>();
|
||
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.
|
||
#[cfg(target_os = "windows")]
|
||
let builder = {
|
||
use wry::WebViewBuilderExtWindows;
|
||
match std::env::var("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS") {
|
||
Ok(arguments) => builder.with_additional_browser_args(&arguments),
|
||
Err(_) => builder,
|
||
}
|
||
};
|
||
|
||
#[cfg(target_os = "linux")]
|
||
let webview = {
|
||
use tao::platform::unix::WindowExtUnix;
|
||
use wry::WebViewBuilderExtUnix;
|
||
|
||
let vbox = window
|
||
.default_vbox()
|
||
.expect("failed to get default GTK container");
|
||
builder.build_gtk(vbox)
|
||
};
|
||
#[cfg(not(target_os = "linux"))]
|
||
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<i32>, PhysicalSize<u32>) {
|
||
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<UserEvent>,
|
||
app: &mut AppState,
|
||
proxy: &EventLoopProxy<UserEvent>,
|
||
initial_session: DocumentSession,
|
||
source_window_id: WindowId,
|
||
) -> Result<WindowId, String> {
|
||
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() {
|
||
apply_linux_webkit_compat_env();
|
||
|
||
// Bench instrumentation: MD_PREVIEW_BENCH=1 makes the app print
|
||
// cold-start timings to stderr and exit as soon as the first paint
|
||
// lands. Costs nothing outside bench mode.
|
||
let bench = std::env::var("MD_PREVIEW_BENCH").is_ok();
|
||
let t0 = Instant::now();
|
||
let bench_log = |label: &str| {
|
||
if bench {
|
||
eprintln!("[bench] +{}ms {}", t0.elapsed().as_millis(), label);
|
||
}
|
||
};
|
||
bench_log("main_start");
|
||
|
||
// CLI: md-preview [--edit] [file.md ...]
|
||
let args = std::env::args().skip(1).collect::<Vec<_>>();
|
||
if args.iter().any(|arg| is_help_arg(arg)) {
|
||
print_help();
|
||
return;
|
||
}
|
||
let edit_from_cli = args.iter().any(|arg| arg == "--edit");
|
||
let cli_paths = args
|
||
.into_iter()
|
||
.filter(|arg| arg != "--edit")
|
||
.map(PathBuf::from)
|
||
.map(|path| {
|
||
if path.is_relative() {
|
||
std::env::current_dir().unwrap_or_default().join(path)
|
||
} else {
|
||
path
|
||
}
|
||
})
|
||
.filter(|path| {
|
||
if path.exists() && is_supported_document(path) {
|
||
true
|
||
} else {
|
||
eprintln!("File not found or unsupported: {}", path.display());
|
||
false
|
||
}
|
||
})
|
||
.collect::<Vec<_>>();
|
||
|
||
let primary = if bench {
|
||
None
|
||
} else {
|
||
match instance::acquire(
|
||
&config_dir(),
|
||
&instance::Launch {
|
||
paths: cli_paths.clone(),
|
||
edit: edit_from_cli,
|
||
},
|
||
) {
|
||
Ok(Some(primary)) => Some(primary),
|
||
Ok(None) => return,
|
||
Err(error) => {
|
||
show_warning_dialog("Could Not Open MD Preview", &error.to_string());
|
||
return;
|
||
}
|
||
}
|
||
};
|
||
|
||
let strings = Strings::english();
|
||
register_as_default();
|
||
register_finder_extension();
|
||
bench_log("after_register");
|
||
|
||
let mut initial_session = DocumentSession::default();
|
||
for path in cli_paths {
|
||
initial_session.open(path, edit_from_cli);
|
||
}
|
||
if initial_session.tabs.is_empty() {
|
||
initial_session.open_home();
|
||
}
|
||
|
||
let event_loop: EventLoop<UserEvent> = EventLoopBuilder::with_user_event().build();
|
||
let proxy = event_loop.create_proxy();
|
||
if let Some(primary) = primary {
|
||
let proxy = proxy.clone();
|
||
primary.listen(move |launch| {
|
||
proxy
|
||
.send_event(UserEvent::OpenPaths(None, launch.paths, launch.edit))
|
||
.is_ok()
|
||
});
|
||
}
|
||
let initial_theme = load_theme_choice();
|
||
install_macos_menu(proxy.clone(), initial_theme);
|
||
|
||
let title = initial_session
|
||
.active()
|
||
.and_then(|tab| tab.file_path())
|
||
.and_then(|path| path.file_name())
|
||
.map(|name| format!("{} — MD Preview", name.to_string_lossy()))
|
||
.unwrap_or_else(|| "MD Preview".to_string());
|
||
|
||
let geom = load_window_geom()
|
||
.filter(|g| geom_visible(g, &event_loop))
|
||
.unwrap_or_else(|| centered_geom(&event_loop));
|
||
|
||
let mut window_builder = WindowBuilder::new()
|
||
.with_title(&title)
|
||
.with_inner_size(LogicalSize::new(geom.w, geom.h))
|
||
.with_position(LogicalPosition::new(geom.x, geom.y))
|
||
.with_theme(initial_theme.tao_theme());
|
||
if let Some(icon) = load_window_icon() {
|
||
window_builder = window_builder.with_window_icon(Some(icon));
|
||
}
|
||
let window = window_builder
|
||
.build(&event_loop)
|
||
.expect("failed to build window");
|
||
let window_id = window.id();
|
||
bench_log("window_built");
|
||
let recent_files: Arc<Mutex<Vec<PathBuf>>> = Arc::new(Mutex::new(load_recent_files()));
|
||
|
||
let initial_page = build_startup_page(&strings);
|
||
let initial_flags = EnhanceFlags::default();
|
||
|
||
let document_session = Arc::new(Mutex::new(initial_session));
|
||
let enhance_flags: Arc<Mutex<EnhanceFlags>> = Arc::new(Mutex::new(initial_flags));
|
||
let last_self_write: Arc<Mutex<Option<SelfWriteRecord>>> = Arc::new(Mutex::new(None));
|
||
|
||
// Windows: steer WebView2's cache/cookie tree into %LOCALAPPDATA% instead of
|
||
// letting it drop next to the exe. Other platforms: use default (None).
|
||
let data_dir: Option<PathBuf> = {
|
||
#[cfg(target_os = "windows")]
|
||
{
|
||
let d = config_dir().join("WebView2");
|
||
let _ = fs::create_dir_all(&d);
|
||
Some(d)
|
||
}
|
||
#[cfg(not(target_os = "windows"))]
|
||
{
|
||
None
|
||
}
|
||
};
|
||
let mut web_context = wry::WebContext::new(data_dir);
|
||
|
||
let webview = match build_webview(
|
||
&window,
|
||
&mut web_context,
|
||
window_id,
|
||
Arc::clone(&document_session),
|
||
Arc::clone(&last_self_write),
|
||
Arc::clone(&recent_files),
|
||
proxy.clone(),
|
||
initial_page,
|
||
) {
|
||
Ok(webview) => webview,
|
||
Err(error) => {
|
||
eprintln!("Could not initialize WebView: {error}");
|
||
show_warning_dialog("Could Not Open MD Preview", &error);
|
||
return;
|
||
}
|
||
};
|
||
bench_log("webview_built");
|
||
// hljs + extra language packs aren't part of first-paint HTML anymore.
|
||
// We push them in via evaluate_script the moment the webview tells us
|
||
// it's painted (IPC 'ready'). Keeps ~125KB out of the HTML-parse critical
|
||
// path so the app window shows content faster on cold start.
|
||
let hljs_bootstrap = format!(
|
||
"(function(){{{hljs_js};{hljs_extra};try{{window.hljs=hljs;}}catch(e){{}}if(typeof hljs!=='undefined'&&hljs.highlightAll){{hljs.highlightAll();}}}})();",
|
||
hljs_js = HLJS_JS,
|
||
hljs_extra = HLJS_EXTRA_LANGS,
|
||
);
|
||
|
||
// File watcher state
|
||
let watcher_holder: Arc<Mutex<Option<notify::RecommendedWatcher>>> = Arc::new(Mutex::new(None));
|
||
|
||
let initial_dirty = document_session
|
||
.lock()
|
||
.unwrap()
|
||
.active()
|
||
.map(|tab| tab.dirty)
|
||
.unwrap_or(false);
|
||
let mut app = AppState {
|
||
windows: HashMap::from([(
|
||
window_id,
|
||
WindowState {
|
||
window,
|
||
webview,
|
||
session: Arc::clone(&document_session),
|
||
last_self_write: Arc::clone(&last_self_write),
|
||
watcher: Arc::clone(&watcher_holder),
|
||
enhance_flags: Arc::clone(&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: initial_dirty,
|
||
is_primary: true,
|
||
},
|
||
)]),
|
||
active_window: window_id,
|
||
recent_files: Arc::clone(&recent_files),
|
||
strings,
|
||
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", "txt"])
|
||
.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::<Vec<_>>();
|
||
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;
|
||
moved.edit_on_open = 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", "txt"])
|
||
.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;
|
||
}
|
||
}
|
||
// macOS: Finder file opens and embedded Finder Sync actions arrive here.
|
||
TaoEvent::Opened { urls } => {
|
||
let mut paths = Vec::new();
|
||
for url in urls {
|
||
if let Ok(path) = url.to_file_path() {
|
||
if is_supported_document(&path) {
|
||
paths.push(path);
|
||
}
|
||
continue;
|
||
}
|
||
if let Some(action) = parse_finder_action(url.as_str()) {
|
||
match action {
|
||
FinderAction::Create { folder, kind } => match create_finder_file(&folder, &kind) {
|
||
Ok(path) if kind == "md" => {
|
||
let _ = proxy.send_event(UserEvent::OpenPaths(
|
||
None,
|
||
vec![path],
|
||
true,
|
||
));
|
||
}
|
||
Ok(_) => {}
|
||
Err(error) => show_warning_dialog("Could Not Create File", &error.to_string()),
|
||
},
|
||
FinderAction::Terminal { folder } => {
|
||
if !open_terminal(&folder) {
|
||
show_warning_dialog("Could Not Open Terminal", &folder.to_string_lossy());
|
||
}
|
||
}
|
||
}
|
||
}
|
||
}
|
||
if !paths.is_empty() {
|
||
let _ = proxy.send_event(UserEvent::OpenPaths(None, paths, false));
|
||
}
|
||
}
|
||
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,
|
||
..
|
||
} => {
|
||
if app.windows.contains_key(&window_id) {
|
||
close_window(&mut app, window_id, control_flow);
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
});
|
||
}
|