feat: add Home as the default tab

- Model Home as a tab without a file path (Option<PathBuf>)
- + creates a Home tab; opening a file from Home reuses that tab
- Add a New File button to the Home page (replaces + for file creation)
- Closing the last file tab falls back to a Home tab
- Hide the tab strip while the only tab is Home
- Keep Home tabs out of detach, reveal, watcher, and duplicate checks
This commit is contained in:
2026-10-28 18:21:53 +08:00
parent abeb426a43
commit 809b7b0299
4 changed files with 449 additions and 119 deletions

View File

@@ -36,6 +36,7 @@ struct SelfWriteRecord {
#[derive(Debug)]
enum UserEvent {
NewFile(WindowId),
NewTab(WindowId),
OpenFile(WindowId),
OpenPaths(Option<WindowId>, Vec<PathBuf>, bool),
ActivateTab(WindowId, u64),
@@ -192,6 +193,9 @@ 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,
@@ -221,6 +225,9 @@ impl Strings {
drop_hint: "Drop a .md file here or press Cmd/Ctrl+O to open",
cannot_read: "无法读取文件",
open_file: "Open File",
new_file: "新建文件",
new_tab: "新建标签页",
home_tab: "首页",
recent_title: "Recent",
missing_title: "文件已移动或删除",
missing_body: "这个标签会继续保留。你可以重新定位文件,或关闭标签。",
@@ -246,6 +253,9 @@ impl 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: "Home",
recent_title: "Recent",
missing_title: "File Moved or Deleted",
missing_body: "This tab is kept. Locate the file again or close the tab.",
@@ -865,15 +875,21 @@ fn tabs_json(session: &DocumentSession) -> String {
.tabs
.iter()
.map(|tab| {
// The page localizes the Home label; rust only flags the kind.
let name = tab
.path
.file_name()
.file_path()
.and_then(|path| path.file_name())
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| tab.path.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": tab.path.to_string_lossy(),
"path": path,
"home": tab.is_home(),
"active": session.active_id == Some(tab.id),
"missing": tab.missing,
"dirty": tab.dirty,
@@ -1079,16 +1095,18 @@ fn build_enhancer_bootstrap(flags: EnhanceFlags, loaded: EnhanceFlags) -> Vec<St
scripts
}
fn empty_preview_html(s: &Strings, recent_files: &[PathBuf]) -> String {
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><button class="empty-open" type="button" data-open-file>{}</button>"#,
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_text(s.open_file),
html_escape_attr(s.btn_new),
html_escape_text(s.new_file)
);
if !recent_files.is_empty() {
@@ -1124,9 +1142,9 @@ fn build_page(
base_href: Option<&str>,
flags: EnhanceFlags,
s: &Strings,
empty: bool,
home: bool,
) -> String {
let body_class = if empty { "empty" } else { "" };
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());
@@ -1276,13 +1294,14 @@ body.has-tabs {{ --chrome-top: 50px; }}
min-height: 60vh; color: #999; font-size: 18px; gap: 12px; text-align: center; }}
.empty.has-recent {{
justify-content: flex-start;
min-height: calc(100vh - 48px);
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 {{
margin-top: 6px; min-height: 40px; padding: 0 16px;
min-height: 40px; padding: 0 16px;
border: 1px solid #ddd; border-radius: 8px; background: #fff;
color: #1a1a1a; font: inherit; font-size: 15px; cursor: pointer;
}}
@@ -1328,6 +1347,7 @@ body.has-tabs {{ --chrome-top: 50px; }}
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;
@@ -1374,7 +1394,7 @@ body.has-tabs {{ --chrome-top: 50px; }}
transition: opacity 0.18s ease;
}}
html:hover .toolbar {{ opacity: 1; pointer-events: auto; }}
body.empty .toolbar {{ display: none !important; }}
body.home .toolbar {{ display: none !important; }}
.toolbar button {{
width: 34px; height: 34px; padding: 0;
background: rgba(255,255,255,0.8);
@@ -1510,7 +1530,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
#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="{btn_new}" aria-label="{btn_new}">+</button></div>
<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>
@@ -1542,7 +1562,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
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}';
var L_EDIT = '{btn_edit}', L_VIEW = '{btn_preview}', L_HOME = '{home_tab}';
window.__mdPreviewFoldLabel = '{fold_toggle}';
window.__mdPreviewCannotSave = '{cannot_save_js}';
@@ -1578,6 +1598,9 @@ body.editing #app {{ max-width: none; padding: 0; }}
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 = '';
@@ -1683,15 +1706,16 @@ body.editing #app {{ max-width: none; padding: 0; }}
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 = shortenPath(path, 42);
if (path) tabMenuPath.setAttribute('title', path);
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;
if (tabMenuReveal) tabMenuReveal.disabled = !path;
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();
@@ -1765,8 +1789,13 @@ body.editing #app {{ max-width: none; padding: 0; }}
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('empty')) return;
if (document.body.classList.contains('home')) return;
if (inEdit()) return;
document.body.classList.add('finding');
setTimeout(function(){{ findInput.focus(); findInput.select(); }}, 0);
@@ -1905,6 +1934,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
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;
@@ -1937,7 +1967,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
if (activeTabId) requestTabAction('close', activeTabId);
}};
tabOpen.addEventListener('click', newFile);
tabOpen.addEventListener('click', newTab);
if (tabMenuNewWindow) {{
tabMenuNewWindow.addEventListener('click', function(e) {{
e.preventDefault();
@@ -1960,6 +1990,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
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) {{}}
@@ -2022,6 +2053,12 @@ body.editing #app {{ max-width: none; padding: 0; }}
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();
@@ -2192,28 +2229,34 @@ body.editing #app {{ max-width: none; padding: 0; }}
if (tabMenuNewWindow) tabMenuNewWindow.disabled = tabCount <= 1;
tabsEl.textContent = '';
activeTabId = 0;
document.body.classList.toggle('has-tabs', tabs.length > 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' + (tab.active ? ' active' : '') + (tab.missing ? ' missing' : '') + (tab.dirty ? ' dirty' : '');
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', tab.path);
item.setAttribute('data-tab-path', isHome ? '' : tab.path);
item.setAttribute('role', 'button');
item.setAttribute('tabindex', '0');
item.title = tab.path;
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 = 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 ' + tab.name);
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);
@@ -2229,7 +2272,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
requestTabAction('activate', tab.getAttribute('data-tab-id'));
}});
window.__setContent = function(previewHtml, rawMd, baseHref, needsMath, needsMermaid) {{
document.body.classList.remove('empty');
document.body.classList.remove('home');
document.body.classList.remove('missing');
hideFind();
window.__setBaseHref(baseHref);
@@ -2243,7 +2286,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
}}
}};
window.__setEmptyPreview = function(previewHtml) {{
document.body.classList.add('empty');
document.body.classList.add('home');
document.body.classList.remove('missing');
document.body.classList.remove('editing');
btnToggle.innerHTML = ICON_EDIT;
@@ -2260,7 +2303,7 @@ body.editing #app {{ max-width: none; padding: 0; }}
window.scrollTo(0, 0);
}};
window.__setMissing = function(previewHtml) {{
document.body.classList.remove('empty');
document.body.classList.remove('home');
document.body.classList.add('missing');
document.body.classList.remove('editing');
btnToggle.innerHTML = ICON_EDIT;
@@ -2300,7 +2343,8 @@ if(window.__enhancePreview)window.__enhancePreview();
base_tag = base_tag,
preview_html = preview_html,
raw_md_escaped = html_escape_ta(raw_md),
btn_new = s.btn_new,
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,
@@ -2792,8 +2836,21 @@ mod tests {
);
assert!(page.contains("window.ipc.postMessage('new-file')"));
assert!(page.contains("tabOpen.addEventListener('click', newFile)"));
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 = 'Home'"));
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)"));
@@ -2904,9 +2961,12 @@ mod tests {
fn empty_state_exposes_open_and_recent_files() {
let strings = Strings::for_lang(Lang::En);
let recent = vec![PathBuf::from("/tmp/example.md")];
let html = empty_preview_html(&strings, &recent);
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\""));
@@ -2924,6 +2984,20 @@ mod tests {
);
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]
@@ -3651,11 +3725,11 @@ fn install_file_watcher(
) {
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();
*last_self_write.lock().unwrap() = None;
let target_path = path.clone();
let callback_path = path.clone();
let proxy = proxy.clone();
@@ -3861,7 +3935,11 @@ 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 == normalized) {
if let Some(tab) = session
.tabs
.iter()
.find(|tab| tab.path.as_deref() == Some(normalized.as_path()))
{
return Some((*window_id, tab.id));
}
}
@@ -3908,8 +3986,8 @@ fn focus_open_tab(
.session
.lock()
.unwrap()
.active()
.map(|tab| tab.path.clone());
.active_path()
.map(Path::to_path_buf);
install_file_watcher(&ws.watcher, proxy, &ws.last_self_write, window_id, path);
true
}
@@ -3920,20 +3998,38 @@ fn update_tabs(webview: &WebView, session: &DocumentSession) {
}
fn update_window_title(window: &Window, session: &DocumentSession) {
let title = session
.active()
.map(|tab| {
let name = tab
.path
.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| tab.path.to_string_lossy().to_string());
format!("{}{} — MD Preview", if tab.dirty { "• " } else { "" }, name)
})
.unwrap_or_else(|| "MD Preview".to_string());
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,
@@ -3944,24 +4040,23 @@ fn render_active_document(
strings: &Strings,
) -> bool {
let Some(active) = session.active().cloned() else {
let html = empty_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);
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(&active.path) {
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, &active.path);
let html = md_to_html_with_base(&raw, active.path.parent());
let base_href = base_href_for_file(&active.path).unwrap_or_default();
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!(
@@ -3996,7 +4091,7 @@ fn render_active_document(
"The file disappeared while it still has unsaved edits. The editor content has been kept.",
);
} else {
let html = missing_preview_html(active.id, &active.path, strings);
let html = missing_preview_html(active.id, &path, strings);
let _ = webview.evaluate_script(&format!(
"if(window.__setMissing)window.__setMissing('{}');",
escape_js(&html)
@@ -4013,7 +4108,7 @@ fn render_active_document(
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(&active.path.to_string_lossy()),
html_escape_text(&path.to_string_lossy()),
html_escape_text(strings.open_file),
active.id,
html_escape_text(strings.close_tab),
@@ -4036,7 +4131,7 @@ fn render_active_document(
// persisted path data in this page; load the active tab after the ready IPC.
fn build_startup_page(strings: &Strings) -> String {
build_page(
&empty_preview_html(strings, &[]),
&home_preview_html(strings, &[]),
"",
None,
EnhanceFlags::default(),
@@ -4104,7 +4199,7 @@ fn build_webview(
}
}
} else if let Some(url) = body.strip_prefix("open-local-link:") {
let active_path = session.lock().unwrap().active().map(|tab| tab.path.clone());
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),
@@ -4124,7 +4219,7 @@ fn build_webview(
return;
};
if let Some(content) = pending_content {
let path = session.lock().unwrap().active().map(|tab| tab.path.clone());
let path = session.lock().unwrap().active_path().map(Path::to_path_buf);
let Some(path) = path else {
return;
};
@@ -4156,6 +4251,9 @@ fn build_webview(
"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:") {
@@ -4185,11 +4283,11 @@ fn build_webview(
save_zoom(percent);
}
} else if body == "refresh" {
if let Some(path) = session.lock().unwrap().active().map(|tab| tab.path.clone()) {
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().map(|tab| tab.path.clone());
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(),
@@ -4325,6 +4423,10 @@ fn create_window_with_session(
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);
@@ -4469,6 +4571,9 @@ fn main() {
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();
@@ -4485,7 +4590,8 @@ fn main() {
let title = initial_session
.active()
.and_then(|tab| tab.path.file_name())
.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());
@@ -4622,7 +4728,8 @@ fn main() {
.lock()
.unwrap()
.active()
.and_then(|tab| tab.path.parent().map(Path::to_path_buf));
.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);
@@ -4673,6 +4780,16 @@ fn main() {
));
}
}
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 {
@@ -4719,7 +4836,11 @@ fn main() {
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);
session.open(path, edit_on_open);
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);
@@ -4731,7 +4852,7 @@ fn main() {
drop(session);
ws.render_active(&recent_files, &strings);
}
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
let path = ws.session.lock().unwrap().active_path().map(Path::to_path_buf);
install_file_watcher(
&ws.watcher,
&proxy,
@@ -4749,7 +4870,7 @@ fn main() {
if session.activate(id) {
drop(session);
ws.render_active(&recent_files, &strings);
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
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);
}
}
@@ -4759,20 +4880,34 @@ fn main() {
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 session.tabs.is_empty() {
if multiple_windows {
drop(session);
close_window(&mut app, window_id, control_flow);
} else {
drop(session);
ws.render_active(&recent_files, &strings);
}
} else if was_active {
if was_active {
drop(session);
ws.render_active(&recent_files, &strings);
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
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);
@@ -4787,6 +4922,9 @@ fn main() {
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);
@@ -4833,7 +4971,7 @@ fn main() {
if !close_source {
drop(session);
ws.render_active(&recent_files, &strings);
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
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);
}
}
@@ -4848,7 +4986,8 @@ fn main() {
.tabs
.iter()
.find(|tab| tab.id == tab_id)
.map(|tab| tab.path.clone())
.and_then(|tab| tab.file_path())
.map(Path::to_path_buf)
});
if let Some(path) = path {
if !reveal_in_explorer(&path) {
@@ -4901,7 +5040,7 @@ fn main() {
if session.relocate(id, path) && session.activate(id) {
drop(session);
ws.render_active(&recent_files, &strings);
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
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.");
@@ -4912,14 +5051,7 @@ fn main() {
let Some(ws) = app.windows.get_mut(&window_id) else {
return;
};
if ws
.session
.lock()
.unwrap()
.active()
.map(|tab| tab.path.as_path())
== Some(path.as_path())
{
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();",
@@ -4937,7 +5069,7 @@ fn main() {
return;
}
let mut session = ws.session.lock().unwrap();
if session.active().map(|tab| tab.path.as_path()) == Some(path.as_path()) {
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() {
@@ -4969,8 +5101,12 @@ fn main() {
ws.warned_external_change = None;
}
let mut session = ws.session.lock().unwrap();
let active_matches = session.active().map(|tab| tab.path.as_path()) == Some(path.as_path());
if let Some(tab) = session.tabs.iter_mut().find(|tab| tab.path == path) {
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;
}
@@ -5052,13 +5188,13 @@ fn main() {
.evaluate_script("if(window.__mdPreviewShowFind)window.__mdPreviewShowFind();");
}
TaoEvent::UserEvent(UserEvent::RecentChanged) => {
let html = empty_preview_html(&strings, &recent_files.lock().unwrap());
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().tabs.is_empty() {
if ws.session.lock().unwrap().active_is_home() {
let _ = ws.webview.evaluate_script(&js);
}
}
@@ -5110,7 +5246,7 @@ fn main() {
if !ws.page_ready {
ws.page_ready = true;
ws.render_active(&recent_files, &strings);
let path = ws.session.lock().unwrap().active().map(|tab| tab.path.clone());
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(..) {