A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
Add Note editor with spellcheck and remote images, basically just trying to improve markdown rendering, still have many issues
RoversX96bbcd4e4ef9
diff --git a/Cargo.lock b/Cargo.lockindex 05d8fd51..6b80aa6e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4846,7 +4846,9 @@ dependencies = ["base64 0.22.1","bytes","encoding_rs",+ "futures-channel","futures-core",+ "futures-util","h2","http","http-body",@@ -7357,6 +7359,7 @@ dependencies = ["ratelim","rayon","regex",+ "reqwest","resvg","serde","serde_json",@@ -7374,6 +7377,7 @@ dependencies = ["tiny-skia","trash","umask",+ "unicode-linebreak","unicode-normalization","unicode-segmentation","unicode-width",@@ -7848,6 +7852,7 @@ dependencies = ["metrics","mio 0.8.11","objc",+ "objc2","objc2-core-graphics","plist","promise",diff --git a/config/src/config.rs b/config/src/config.rsindex c2e7af55..d3085557 100644--- a/config/src/config.rs+++ b/config/src/config.rs@@ -721,6 +721,14 @@ pub struct Config {#[dynamic(default = "default_true")]pub use_ime: bool,+ /// Enable local, platform-provided spelling checks in the Note editor.+ #[dynamic(default = "default_true")]+ pub note_spellcheck_enabled: bool,+ /// Allow Note documents to load HTTP/HTTPS images. Remote images are+ /// fetched lazily by the Note host and are subject to strict size and+ /// network-address limits.+ #[dynamic(default = "default_true")]+ pub note_remote_images_enabled: bool,#[dynamic(default)]pub xim_im_name: Option<String>,#[dynamic(default)]@@ -2444,6 +2452,11 @@ mod tests {assert_eq!(Config::default().default_cwd.as_ref(), Some(&*HOME_DIR));}+ #[test]+ fn remote_note_images_are_enabled_by_default() {+ assert!(Config::default().note_remote_images_enabled);+ }+#[test]fn import_loader_restores_env_and_collects_raw_keys() {let _env_lock = ENV_LOCK.lock().unwrap();diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.tomlindex 6a20ea9c..05cdfb98 100644--- a/wezterm-gui/Cargo.toml+++ b/wezterm-gui/Cargo.toml@@ -81,6 +81,7 @@ rangeset.workspace = trueratelim.workspace = truerayon.workspace = trueregex.workspace = true+reqwest = { workspace = true, features = ["blocking"] }resvg.workspace = trueserde = {workspace=true, features = ["rc", "derive"]}serde_json.workspace = true@@ -98,6 +99,7 @@ thinkterm-syntax = { path = "../thinkterm-syntax" }trash.workspace = trueumask.workspace = trueunicode-normalization.workspace = true+unicode-linebreak = "0.1"unicode-segmentation.workspace = trueunicode-width.workspace = trueuuid = { workspace = true, features = ["v4"] }diff --git a/wezterm-gui/src/markdown_editor/document.rs b/wezterm-gui/src/markdown_editor/document.rsindex b33d5493..a33ec4ba 100644--- a/wezterm-gui/src/markdown_editor/document.rs+++ b/wezterm-gui/src/markdown_editor/document.rs@@ -2,6 +2,7 @@ use parking_lot::Mutex;use std::ops::Range;use std::path::PathBuf;use std::sync::Arc;+use std::time::SystemTime;use unicode_segmentation::UnicodeSegmentation;#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]@@ -50,6 +51,13 @@ impl SourceSelection {}#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum SelectionGranularity {+ Character,+ Word,+ MarkdownBlock,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub(crate) enum EditorMode {LivePreview,Source,@@ -64,6 +72,12 @@ pub(crate) enum SaveState {Failed(String),}+#[derive(Debug, Clone)]+pub(crate) struct DocumentSnapshot {+ pub revision: u64,+ pub source: Arc<str>,+}+#[derive(Debug, Clone)]pub(crate) struct EditorViewState {pub selection: SourceSelection,@@ -96,6 +110,21 @@ struct EditRecord {after: SourceSelection,}+#[derive(Debug, Clone)]+struct DocumentEdit {+ replaced: Range<usize>,+ inserted_len: usize,+}++impl DocumentEdit {+ fn new(replaced: Range<usize>, inserted_len: usize) -> Self {+ Self {+ replaced,+ inserted_len,+ }+ }+}+#[derive(Debug)]pub(crate) struct MarkdownDocumentSession {#[allow(dead_code)]@@ -104,29 +133,43 @@ pub(crate) struct MarkdownDocumentSession {source: String,revision: u64,saved_revision: u64,+ published: DocumentSnapshot,+ /// Immutable view of the current edit revision. Large notes must not be+ /// copied once for projection and then copied again for autosave during+ /// the same revision.+ snapshot_cache: Option<DocumentSnapshot>,save_state: SaveState,line_starts: Vec<usize>,undo: Vec<EditRecord>,redo: Vec<EditRecord>,save_lock: Arc<Mutex<()>>,+ disk_stamp: Option<(SystemTime, u64)>,}const MAX_UNDO_RECORDS: usize = 512;impl MarkdownDocumentSession {pub(crate) fn new(document_id: String, path: PathBuf, source: String) -> Self {+ let disk_stamp = file_disk_stamp(&path);let line_starts = line_starts(&source);+ let published = DocumentSnapshot {+ revision: 0,+ source: Arc::from(source.as_str()),+ };Self {document_id,path,source,revision: 0,saved_revision: 0,+ snapshot_cache: Some(published.clone()),+ published,save_state: SaveState::Saved,line_starts,undo: vec![],redo: vec![],save_lock: Arc::new(Mutex::new(())),+ disk_stamp,}}@@ -146,20 +189,56 @@ impl MarkdownDocumentSession {self.revision != self.saved_revision}- pub(crate) fn snapshot_for_save(&mut self) -> (u64, PathBuf, String) {- let revision = self.revision;+ pub(crate) fn current_snapshot(&mut self) -> DocumentSnapshot {+ if let Some(snapshot) = self+ .snapshot_cache+ .as_ref()+ .filter(|snapshot| snapshot.revision == self.revision)+ {+ return snapshot.clone();+ }+ let snapshot = DocumentSnapshot {+ revision: self.revision,+ source: Arc::from(self.source.as_str()),+ };+ self.snapshot_cache = Some(snapshot.clone());+ snapshot+ }++ pub(crate) fn published_snapshot(&self) -> DocumentSnapshot {+ self.published.clone()+ }++ pub(crate) fn snapshot_for_save(&mut self) -> (u64, PathBuf, Arc<str>) {+ let snapshot = self.current_snapshot();+ let revision = snapshot.revision;self.save_state = SaveState::Saving(revision);- (revision, self.path.clone(), self.source.clone())+ (revision, self.path.clone(), snapshot.source)}pub(crate) fn save_lock(&self) -> Arc<Mutex<()>> {Arc::clone(&self.save_lock)}- pub(crate) fn finish_save(&mut self, revision: u64, result: anyhow::Result<()>) {+ pub(crate) fn finish_save(+ &mut self,+ revision: u64,+ source: Arc<str>,+ result: anyhow::Result<()>,+ ) {match result {Ok(()) => {- self.saved_revision = self.saved_revision.max(revision);+ self.disk_stamp = file_disk_stamp(&self.path);+ if revision >= self.saved_revision {+ self.saved_revision = revision;+ self.published = DocumentSnapshot {+ revision,+ source: Arc::clone(&source),+ };+ if revision == self.revision {+ self.snapshot_cache = Some(DocumentSnapshot { revision, source });+ }+ }self.save_state = if self.saved_revision == self.revision {SaveState::Saved} else {@@ -175,6 +254,55 @@ impl MarkdownDocumentSession {(range.start != range.end).then(|| &self.source[range])}+ pub(crate) fn can_undo(&self) -> bool {+ !self.undo.is_empty()+ }++ pub(crate) fn can_redo(&self) -> bool {+ !self.redo.is_empty()+ }++ pub(crate) fn disk_stamp(&self) -> Option<(SystemTime, u64)> {+ self.disk_stamp+ }++ /// Apply a watcher snapshot using the product's explicit last-writer-wins+ /// policy. A changed disk stamp with identical text is our own atomic save+ /// and only advances the stamp; genuinely changed text replaces even a+ /// dirty buffer and clears undo/redo so stale edits cannot be replayed onto+ /// another application's version.+ pub(crate) fn apply_external_snapshot(+ &mut self,+ view: &mut EditorViewState,+ modified: SystemTime,+ len: u64,+ source: String,+ ) -> bool {+ let stamp = (modified, len);+ if self.disk_stamp == Some(stamp) {+ return false;+ }+ self.disk_stamp = Some(stamp);+ if self.source == source {+ return false;+ }++ self.source = source;+ self.revision = self.revision.wrapping_add(1);+ self.saved_revision = self.revision;+ self.published = DocumentSnapshot {+ revision: self.revision,+ source: Arc::from(self.source.as_str()),+ };+ self.snapshot_cache = Some(self.published.clone());+ self.save_state = SaveState::Saved;+ self.line_starts = line_starts(&self.source);+ self.undo.clear();+ self.redo.clear();+ self.clamp_view(view);+ true+ }+pub(crate) fn set_caret(&self, view: &mut EditorViewState, byte: usize, extend: bool) {let byte = clamp_char_boundary(&self.source, byte);if extend {@@ -193,6 +321,21 @@ impl MarkdownDocumentSession {view.preferred_column = None;}+ pub(crate) fn word_range_at(&self, byte: usize) -> Range<usize> {+ unicode_word_range_at(&self.source, byte)+ }++ pub(crate) fn source_line_selection_range(&self, byte: usize) -> Range<usize> {+ let line = self.line_index(byte);+ let start = self.line_starts[line];+ let end = self+ .line_starts+ .get(line + 1)+ .copied()+ .unwrap_or(self.source.len());+ start..end+ }+pub(crate) fn clamp_view(&self, view: &mut EditorViewState) {view.selection.anchor.byte = clamp_char_boundary(&self.source, view.selection.anchor.byte);view.selection.focus.byte = clamp_char_boundary(&self.source, view.selection.focus.byte);@@ -218,6 +361,27 @@ impl MarkdownDocumentSession {self.replace_range(view, range, &filtered)}+ pub(crate) fn delete_selection(&mut self, view: &mut EditorViewState) -> bool {+ if view.mode == EditorMode::ReadOnly || view.selection.is_caret() {+ return false;+ }+ let range = self.clamped_selection_range(view);+ self.replace_range(view, range, "")+ }++ pub(crate) fn replace_range_at_revision(+ &mut self,+ view: &mut EditorViewState,+ revision: u64,+ range: Range<usize>,+ replacement: &str,+ ) -> bool {+ if self.revision != revision || view.mode == EditorMode::ReadOnly {+ return false;+ }+ self.replace_range(view, range, replacement)+ }+pub(crate) fn surround_selection(&mut self,view: &mut EditorViewState,@@ -390,26 +554,34 @@ impl MarkdownDocumentSession {}pub(crate) fn undo(&mut self, view: &mut EditorViewState) -> bool {+ let stage = crate::input_diagnostics::StageTimer::begin("note_edit");let Some(edit) = self.undo.pop() else {+ stage.finish(false);return false;};let end = edit.start + edit.inserted.len();self.source.replace_range(edit.start..end, &edit.deleted);view.selection = edit.before;+ let mutation = DocumentEdit::new(edit.start..end, edit.deleted.len());self.redo.push(edit);- self.note_mutation();+ self.note_mutation(mutation);+ stage.finish(true);true}pub(crate) fn redo(&mut self, view: &mut EditorViewState) -> bool {+ let stage = crate::input_diagnostics::StageTimer::begin("note_edit");let Some(edit) = self.redo.pop() else {+ stage.finish(false);return false;};let end = edit.start + edit.deleted.len();self.source.replace_range(edit.start..end, &edit.inserted);view.selection = edit.after;+ let mutation = DocumentEdit::new(edit.start..end, edit.inserted.len());self.undo.push(edit);- self.note_mutation();+ self.note_mutation(mutation);+ stage.finish(true);true}@@ -419,14 +591,17 @@ impl MarkdownDocumentSession {range: Range<usize>,inserted: &str,) -> bool {+ let stage = crate::input_diagnostics::StageTimer::begin("note_edit");let start = clamp_char_boundary(&self.source, range.start);let end = clamp_char_boundary(&self.source, range.end).max(start);if start == end && inserted.is_empty() {+ stage.finish(false);return false;}let before = view.selection;let deleted = self.source[start..end].to_string();self.source.replace_range(start..end, inserted);+ let mutation = DocumentEdit::new(start..end, inserted.len());let after = SourceSelection::caret(start + inserted.len());view.selection = after;view.preferred_column = None;@@ -441,14 +616,55 @@ impl MarkdownDocumentSession {self.undo.remove(0);}self.redo.clear();- self.note_mutation();+ self.note_mutation(mutation);+ stage.finish(true);true}- fn note_mutation(&mut self) {+ fn note_mutation(&mut self, edit: DocumentEdit) {self.revision = self.revision.wrapping_add(1);+ self.snapshot_cache = None;self.save_state = SaveState::Dirty;- self.line_starts = line_starts(&self.source);+ self.update_line_starts(&edit);+ }++ fn update_line_starts(&mut self, edit: &DocumentEdit) {+ let anchor_index = self+ .line_starts+ .partition_point(|start| *start <= edit.replaced.start)+ .saturating_sub(1);+ let anchor = self.line_starts[anchor_index];+ let suffix_index = self+ .line_starts+ .partition_point(|start| *start <= edit.replaced.end);+ let deleted_len = edit.replaced.end.saturating_sub(edit.replaced.start);+ let shifted_suffix = self.line_starts[suffix_index..]+ .iter()+ .map(|start| {+ if edit.inserted_len >= deleted_len {+ start.saturating_add(edit.inserted_len - deleted_len)+ } else {+ start.saturating_sub(deleted_len - edit.inserted_len)+ }+ })+ .collect::<Vec<_>>();+ let rebuild_end = shifted_suffix+ .first()+ .copied()+ .unwrap_or(self.source.len())+ .min(self.source.len());++ self.line_starts.truncate(anchor_index + 1);+ self.line_starts.extend(+ self.source[anchor..rebuild_end]+ .match_indices('\n')+ .map(|(relative, _)| anchor + relative + 1),+ );+ for start in shifted_suffix {+ if self.line_starts.last().copied() != Some(start) {+ self.line_starts.push(start);+ }+ }}fn clamped_selection_range(&self, view: &EditorViewState) -> Range<usize> {@@ -478,6 +694,11 @@ impl MarkdownDocumentSession {}}+fn file_disk_stamp(path: &std::path::Path) -> Option<(SystemTime, u64)> {+ let metadata = std::fs::metadata(path).ok()?;+ Some((metadata.modified().ok()?, metadata.len()))+}+fn line_starts(source: &str) -> Vec<usize> {let mut starts = vec![0];starts.extend(@@ -560,6 +781,43 @@ fn next_word_boundary(source: &str, byte: usize) -> usize {cursor}+fn unicode_word_range_at(source: &str, byte: usize) -> Range<usize> {+ if source.is_empty() {+ return 0..0;+ }+ let byte = clamp_char_boundary(source, byte);+ let seed_start = if byte == source.len() {+ previous_grapheme_boundary(source, byte)+ } else {+ byte+ };+ let seed_end = next_grapheme_boundary(source, seed_start);+ let seed = &source[seed_start..seed_end];+ if seed.contains(['\r', '\n']) {+ return seed_start..seed_start;+ }+ let class = word_class(seed);+ let mut start = seed_start;+ while start > 0 {+ let previous = previous_grapheme_boundary(source, start);+ let grapheme = &source[previous..start];+ if grapheme.contains(['\r', '\n']) || word_class(grapheme) != class {+ break;+ }+ start = previous;+ }+ let mut end = seed_end;+ while end < source.len() {+ let next = next_grapheme_boundary(source, end);+ let grapheme = &source[end..next];+ if grapheme.contains(['\r', '\n']) || word_class(grapheme) != class {+ break;+ }+ end = next;+ }+ start..end+}+fn word_class(grapheme: &str) -> u8 {if grapheme.chars().all(char::is_whitespace) {0@@ -658,6 +916,28 @@ mod tests {assert_eq!(session.source(), "hello 世界");}+ #[test]+ fn edits_update_line_index_without_rebuilding_the_document() {+ let (mut session, mut view) = session("one\ntwo\nthree\nfour");+ let assert_index = |session: &MarkdownDocumentSession| {+ assert_eq!(session.line_starts, line_starts(session.source()));+ };++ session.set_caret(&mut view, 5, false);+ assert!(session.insert_text(&mut view, "A\nB"));+ assert_index(&session);+ view.selection = SourceSelection {+ anchor: SourcePosition::new(2),+ focus: SourcePosition::new(12),+ };+ assert!(session.insert_text(&mut view, "joined"));+ assert_index(&session);+ assert!(session.undo(&mut view));+ assert_index(&session);+ assert!(session.redo(&mut view));+ assert_index(&session);+ }+#[test]fn vertical_navigation_preserves_grapheme_column() {let (session, mut view) = session("abcd\n你😀\nabcdef");@@ -673,11 +953,30 @@ mod tests {let (mut session, mut view) = session("a");session.set_caret(&mut view, 1, false);session.insert_text(&mut view, "b");- let (revision, _, _) = session.snapshot_for_save();+ let (revision, _, source) = session.snapshot_for_save();session.insert_text(&mut view, "c");- session.finish_save(revision, Ok(()));+ session.finish_save(revision, source, Ok(()));assert!(session.is_dirty());assert_eq!(session.save_state(), &SaveState::Dirty);+ assert_eq!(session.published_snapshot().revision, revision);+ assert_eq!(session.published_snapshot().source.as_ref(), "ab");+ assert_eq!(session.source(), "abc");+ }++ #[test]+ fn current_revision_reuses_one_immutable_snapshot() {+ let (mut session, mut view) = session("a large note");+ let first = session.current_snapshot();+ let second = session.current_snapshot();+ assert!(Arc::ptr_eq(&first.source, &second.source));++ session.set_caret(&mut view, session.source().len(), false);+ assert!(session.insert_text(&mut view, "!"));+ let edited = session.current_snapshot();+ assert!(!Arc::ptr_eq(&first.source, &edited.source));++ let (_, _, for_save) = session.snapshot_for_save();+ assert!(Arc::ptr_eq(&edited.source, &for_save));}#[test]@@ -695,6 +994,28 @@ mod tests {assert_eq!(session.source(), "**hello**");}+ #[test]+ fn unicode_word_selection_respects_words_punctuation_and_emoji() {+ let (session, _) = session("hello, 世界 😀 done");+ assert_eq!(session.word_range_at(2), 0..5);+ assert_eq!(session.word_range_at(5), 5..6);+ let cjk = "hello, ".len();+ assert_eq!(&session.source()[session.word_range_at(cjk)], "世界");+ let emoji = session.source().find('😀').unwrap();+ assert_eq!(&session.source()[session.word_range_at(emoji)], "😀");+ }++ #[test]+ fn spelling_replacement_is_revision_gated_and_undoable() {+ let (mut session, mut view) = session("a mistke here");+ assert!(!session.replace_range_at_revision(&mut view, 9, 2..8, "mistake"));+ assert_eq!(session.source(), "a mistke here");+ assert!(session.replace_range_at_revision(&mut view, 0, 2..8, "mistake"));+ assert_eq!(session.source(), "a mistake here");+ assert!(session.undo(&mut view));+ assert_eq!(session.source(), "a mistke here");+ }+#[test]fn stale_window_selection_is_clamped_after_shared_edits() {let (mut session, mut first_view) = session("shared");@@ -735,4 +1056,23 @@ mod tests {session.move_word_right(&mut view, false);assert_eq!(&session.source()[view.selection.focus.byte..], " world");}++ #[test]+ fn external_snapshot_is_last_writer_and_clears_local_history() {+ let (mut session, mut view) = session("local");+ session.set_caret(&mut view, session.source().len(), false);+ assert!(session.insert_text(&mut view, " dirty"));+ assert!(session.can_undo());++ assert!(session.apply_external_snapshot(+ &mut view,+ SystemTime::now(),+ 8,+ "external".to_string(),+ ));+ assert_eq!(session.source(), "external");+ assert!(!session.is_dirty());+ assert!(!session.can_undo());+ assert!(!session.can_redo());+ }}diff --git a/wezterm-gui/src/markdown_editor/host.rs b/wezterm-gui/src/markdown_editor/host.rsindex bcaa3cf4..a0e406dd 100644--- a/wezterm-gui/src/markdown_editor/host.rs+++ b/wezterm-gui/src/markdown_editor/host.rs@@ -1,11 +1,28 @@use super::{- build_visual_document, default_document_session, EditorViewState, MarkdownDocumentSession,- MarkdownProjection, ProjectedObject, SourcePosition, VisualDocument,+ build_visual_document, DocumentSnapshot, EditorViewState, MarkdownDocumentSession,+ MarkdownProjection, NoteSpellingIssue, ProjectedObject, SaveState, SelectionGranularity,+ SourcePosition, SourceSelection, VaultDocument, VisualDocument, VisualWrapCache,};use parking_lot::Mutex;use std::collections::{HashMap, HashSet};use std::ops::Range;use std::sync::Arc;+use std::time::SystemTime;+use std::time::{Duration, Instant};++#[derive(Debug, Clone)]+enum NoteDisplaySource {+ Published,+ Live,+ Frozen(DocumentSnapshot),+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum AutosaveWakeAction {+ Idle,+ Reschedule(Duration),+ SaveNow,+}#[derive(Debug, Clone)]pub(crate) struct NoteRunLayout {@@ -38,83 +55,339 @@ pub(crate) struct NoteCodeBlockLayout {pub max_horizontal_scroll: f32,}+#[derive(Debug, Clone, Copy)]+pub(crate) struct NoteLineGeometry {+ pub top: f32,+ pub height: f32,+ pub gap: f32,+}++type NoteWrapLayoutKey = (u64, super::EditorMode, usize, usize);++/// Identifies one exact background wrap request. `layout` describes the+/// document revision/caret/width while `visual_identity` prevents revisions+/// from different documents from colliding. `generation` makes an A -> B -> A+/// resize reject the first A even though its layout key is equal to the latest+/// request.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct NoteBackgroundWrapKey {+ layout: NoteWrapLayoutKey,+ visual_identity: usize,+ generation: u64,+}+pub(crate) struct NoteHostState {pub session: Option<Arc<Mutex<MarkdownDocumentSession>>>,+ pub document: Option<VaultDocument>,pub view: EditorViewState,pub projection: MarkdownProjection,- pub visual: VisualDocument,+ pub visual: Arc<VisualDocument>,wrapped_visual: Arc<VisualDocument>,+ pub wrap_cache: VisualWrapCache,pub projection_revision: Option<u64>,pub visual_key: Option<(u64, super::EditorMode, usize)>,wrapped_key: Option<(u64, super::EditorMode, usize, usize)>,pub line_layouts: Vec<NoteLineLayout>,+ pub line_geometry_key: Option<u64>,+ pub line_geometry: Arc<Vec<NoteLineGeometry>>,pub viewport_height: f32,pub content_height: f32,pub load_error: Option<String>,- pub save_generation: u64,+ display_source: NoteDisplaySource,+ autosave_deadline: Option<Instant>,+ autosave_timer_scheduled: bool,pub reveal_caret: bool,pub drag_selection_active: bool,+ pub selection_granularity: SelectionGranularity,+ pub drag_selection_base: Option<Range<usize>>,pub drag_autoscroll_scheduled: bool,pub collapsed_code_blocks: HashSet<usize>,pub code_horizontal_offsets: HashMap<usize, f32>,pub code_block_layouts: Vec<NoteCodeBlockLayout>,+ pub spelling_issues: Arc<Vec<NoteSpellingIssue>>,+ pub spelling_revision: Option<u64>,+ pub spelling_context: Option<Range<usize>>,+ pub spellcheck_scheduled_revision: Option<u64>,+ pub spellcheck_in_flight_revision: Option<u64>,+ pub native_text_input_snapshot_key: Option<(u64, usize, usize, u32, usize)>,+ pub native_text_input_token: u64,+ pub parse_requested_revision: Option<u64>,+ pub parse_in_flight_revision: Option<u64>,+ background_wrap_preferred: bool,+ background_wrap_requested_key: Option<NoteBackgroundWrapKey>,+ background_wrap_generation: u64,+ pub background_wrap_in_flight_key: Option<NoteBackgroundWrapKey>,}+const BACKGROUND_PARSE_THRESHOLD_BYTES: usize = 64 * 1024;+/// Seed enough parsed content for the first screen while a large document is+/// parsed in full on a worker. Keep this below the background-wrap threshold+/// so opening a multi-megabyte note can paint useful text immediately without+/// performing an exact large-note wrap on the UI thread.+const PROGRESSIVE_PREVIEW_BYTES: usize = 6 * 1024;+/// Exact font measurement and wrapping is expensive well before parsing is.+/// Keep small notes immediate, but move ordinary multi-page notes (including+/// the 40 KiB regression fixture) off the UI thread.+const BACKGROUND_WRAP_THRESHOLD_BYTES: usize = 8 * 1024;+impl Default for NoteHostState {fn default() -> Self {Self {session: None,+ document: None,view: EditorViewState::default(),projection: MarkdownProjection::default(),- visual: VisualDocument::default(),+ visual: Arc::new(VisualDocument::default()),wrapped_visual: Arc::new(VisualDocument::default()),+ wrap_cache: VisualWrapCache::default(),projection_revision: None,visual_key: None,wrapped_key: None,line_layouts: vec![],+ line_geometry_key: None,+ line_geometry: Arc::new(vec![]),viewport_height: 0.0,content_height: 0.0,load_error: None,- save_generation: 0,+ display_source: NoteDisplaySource::Published,+ autosave_deadline: None,+ autosave_timer_scheduled: false,reveal_caret: true,drag_selection_active: false,+ selection_granularity: SelectionGranularity::Character,+ drag_selection_base: None,drag_autoscroll_scheduled: false,collapsed_code_blocks: HashSet::new(),code_horizontal_offsets: HashMap::new(),code_block_layouts: vec![],+ spelling_issues: Arc::new(vec![]),+ spelling_revision: None,+ spelling_context: None,+ spellcheck_scheduled_revision: None,+ spellcheck_in_flight_revision: None,+ native_text_input_snapshot_key: None,+ native_text_input_token: 0,+ parse_requested_revision: None,+ parse_in_flight_revision: None,+ background_wrap_preferred: false,+ background_wrap_requested_key: None,+ background_wrap_generation: 0,+ background_wrap_in_flight_key: None,}}}impl NoteHostState {- pub(crate) fn ensure_loaded(&mut self) -> bool {- if self.session.is_some() {- return true;- }- match default_document_session() {- Ok(session) => {- self.view.selection = super::SourceSelection::caret(0);- self.session = Some(session);- self.load_error = None;- self.refresh_projection();- true- }- Err(err) => {- self.load_error = Some(format!("{err:#}"));- false- }+ /// Switch this host to a Vault document. The document registry guarantees+ /// that another window opening the same path supplies the same Arc.+ pub(crate) fn bind_document(&mut self, document: VaultDocument) -> bool {+ if self+ .session+ .as_ref()+ .is_some_and(|session| Arc::ptr_eq(session, &document.session))+ {+ self.document = Some(document);+ self.load_error = None;+ return false;}++ self.session = Some(Arc::clone(&document.session));+ self.document = Some(document);+ self.view = EditorViewState::default();+ self.projection = MarkdownProjection::default();+ self.visual = Arc::new(VisualDocument::default());+ self.wrapped_visual = Arc::new(VisualDocument::default());+ self.wrap_cache = VisualWrapCache::default();+ self.projection_revision = None;+ self.visual_key = None;+ self.wrapped_key = None;+ self.line_layouts.clear();+ self.line_geometry_key = None;+ self.line_geometry = Arc::new(vec![]);+ self.content_height = 0.0;+ self.load_error = None;+ self.display_source = NoteDisplaySource::Published;+ self.autosave_deadline = None;+ self.autosave_timer_scheduled = false;+ self.collapsed_code_blocks.clear();+ self.code_horizontal_offsets.clear();+ self.code_block_layouts.clear();+ self.spelling_issues = Arc::new(vec![]);+ self.spelling_revision = None;+ self.spelling_context = None;+ self.spellcheck_scheduled_revision = None;+ self.spellcheck_in_flight_revision = None;+ self.native_text_input_snapshot_key = None;+ self.parse_requested_revision = None;+ self.parse_in_flight_revision = None;+ self.background_wrap_preferred = false;+ self.background_wrap_requested_key = None;+ let snapshot = self+ .session+ .as_ref()+ .map(|session| session.lock().published_snapshot());+ if snapshot+ .as_ref()+ .is_some_and(|snapshot| snapshot.source.len() <= BACKGROUND_PARSE_THRESHOLD_BYTES)+ {+ self.refresh_projection();+ } else if let Some(snapshot) = snapshot {+ self.seed_progressive_preview(&snapshot);+ }+ true+ }++ fn seed_progressive_preview(&mut self, snapshot: &DocumentSnapshot) {+ let end = progressive_preview_end(&snapshot.source, PROGRESSIVE_PREVIEW_BYTES);+ let source = &snapshot.source[..end];+ self.projection = MarkdownProjection::parse(source);+ let active_start = self+ .projection+ .active_syntax(0)+ .map(|node| node.source.start)+ .unwrap_or(usize::MAX);+ self.visual = Arc::new(build_visual_document(+ source,+ &self.projection,+ self.view.mode,+ 0,+ ));+ self.background_wrap_preferred =+ self.visual.estimated_wrap_work_bytes() >= BACKGROUND_WRAP_THRESHOLD_BYTES;+ self.visual_key = Some((snapshot.revision, self.view.mode, active_start));+ // This is deliberately not the complete revision. The regular+ // background parse path will replace it with the full projection.+ self.projection_revision = None;+ self.parse_requested_revision = Some(snapshot.revision);+ }++ pub(crate) fn clear_document(&mut self, error: Option<String>) {+ self.session = None;+ self.document = None;+ self.load_error = error;+ self.projection_revision = None;+ self.visual_key = None;+ self.wrapped_key = None;+ self.line_layouts.clear();+ self.line_geometry_key = None;+ self.line_geometry = Arc::new(vec![]);+ self.parse_requested_revision = None;+ self.parse_in_flight_revision = None;+ self.background_wrap_preferred = false;+ self.background_wrap_requested_key = None;+ }++ pub(crate) fn apply_external_snapshot(+ &mut self,+ modified: SystemTime,+ len: u64,+ source: String,+ ) -> bool {+ let Some(session) = self.session.as_ref().cloned() else {+ return false;+ };+ if !session+ .lock()+ .apply_external_snapshot(&mut self.view, modified, len, source)+ {+ return false;+ }+ self.display_source = NoteDisplaySource::Published;+ self.autosave_deadline = None;+ self.autosave_timer_scheduled = false;+ self.projection_revision = None;+ self.visual_key = None;+ self.wrapped_key = None;+ self.wrap_cache = VisualWrapCache::default();+ self.line_geometry_key = None;+ self.line_geometry = Arc::new(vec![]);+ self.spelling_revision = None;+ self.spelling_context = None;+ self.spelling_issues = Arc::new(vec![]);+ self.refresh_projection();+ true}pub(crate) fn refresh_projection(&mut self) {- let Some(session) = self.session.as_ref() else {+ let Some(session) = self.session.as_ref().cloned() else {return;};- let session = session.lock();- let revision = session.revision();- let source = session.source();+ match self.display_source.clone() {+ NoteDisplaySource::Published => {+ let snapshot = session.lock().published_snapshot();+ self.refresh_projection_from_source(snapshot.revision, &snapshot.source);+ }+ NoteDisplaySource::Live => {+ let session = session.lock();+ self.refresh_projection_from_source(session.revision(), session.source());+ }+ NoteDisplaySource::Frozen(snapshot) => {+ self.refresh_projection_from_source(snapshot.revision, &snapshot.source);+ }+ }+ }++ fn refresh_projection_from_source(&mut self, revision: u64, source: &str) {+ let mut projection_stage = None;if self.projection_revision != Some(revision) {- self.projection = MarkdownProjection::parse(source);+ if source.len() > BACKGROUND_PARSE_THRESHOLD_BYTES {+ self.parse_requested_revision = Some(revision);+ return;+ }+ projection_stage = Some(crate::input_diagnostics::StageTimer::begin(+ "note_projection",+ ));+ let cached_links = self+ .projection+ .objects+ .iter()+ .filter_map(|object| match object {+ ProjectedObject::WikiLink {+ target,+ embed,+ resolved_path,+ ambiguous_paths,+ rendered_lines,+ ..+ } => Some((+ (target.clone(), *embed),+ (+ resolved_path.clone(),+ ambiguous_paths.clone(),+ rendered_lines.clone(),+ ),+ )),+ _ => None,+ })+ .collect::<HashMap<_, _>>();+ let mut projection = MarkdownProjection::parse(source);+ if matches!(self.display_source, NoteDisplaySource::Published) {+ if let Some(document) = self.document.as_ref() {+ projection.resolve_vault_links(&document.vault_root, &document.relative_path);+ }+ } else {+ for object in &mut projection.objects {+ let ProjectedObject::WikiLink {+ target,+ embed,+ resolved_path,+ ambiguous_paths,+ rendered_lines,+ ..+ } = object+ else {+ continue;+ };+ if let Some((cached_path, cached_ambiguous_paths, cached_lines)) =+ cached_links.get(&(target.clone(), *embed))+ {+ *resolved_path = cached_path.clone();+ *ambiguous_paths = cached_ambiguous_paths.clone();+ *rendered_lines = cached_lines.clone();+ }+ }+ }+ self.projection = projection;let code_starts = self.projection.objects@@ -129,6 +402,10 @@ impl NoteHostState {self.code_horizontal_offsets.retain(|source_start, _| code_starts.contains(source_start));self.projection_revision = Some(revision);+ if self.spelling_revision != Some(revision) {+ self.spelling_issues = Arc::new(vec![]);+ self.spelling_context = None;+ }self.visual_key = None;}let active_start = self@@ -138,15 +415,264 @@ impl NoteHostState {.unwrap_or(usize::MAX);let key = (revision, self.view.mode, active_start);if self.visual_key != Some(key) {- self.visual = build_visual_document(+ if projection_stage.is_none() {+ projection_stage = Some(crate::input_diagnostics::StageTimer::begin(+ "note_projection",+ ));+ }+ self.visual = Arc::new(build_visual_document(source,&self.projection,self.view.mode,self.view.selection.focus.byte,- );+ ));+ self.background_wrap_preferred =+ self.visual.estimated_wrap_work_bytes() >= BACKGROUND_WRAP_THRESHOLD_BYTES;self.visual_key = Some(key);self.wrapped_key = None;}+ if let Some(stage) = projection_stage {+ stage.finish(true);+ }+ }++ pub(crate) fn background_parse_request(+ &mut self,+ ) -> Option<(+ u64,+ Arc<str>,+ super::EditorMode,+ usize,+ Option<(std::path::PathBuf, String)>,+ )> {+ let session = self.session.as_ref()?.clone();+ let snapshot = session.lock().current_snapshot();+ if snapshot.source.len() <= BACKGROUND_PARSE_THRESHOLD_BYTES+ || self.projection_revision == Some(snapshot.revision)+ {+ return None;+ }+ self.parse_requested_revision = Some(snapshot.revision);+ if self.parse_in_flight_revision.is_some() {+ return None;+ }+ self.parse_in_flight_revision = Some(snapshot.revision);+ let document = self+ .document+ .as_ref()+ .map(|document| (document.vault_root.clone(), document.relative_path.clone()));+ Some((+ snapshot.revision,+ snapshot.source,+ self.view.mode,+ self.view.selection.focus.byte,+ document,+ ))+ }++ pub(crate) fn apply_background_parse(+ &mut self,+ revision: u64,+ mode: super::EditorMode,+ caret: usize,+ projection: MarkdownProjection,+ visual: VisualDocument,+ ) -> bool {+ if self.parse_in_flight_revision != Some(revision) {+ return false;+ }+ self.parse_in_flight_revision = None;+ let current_revision = self+ .session+ .as_ref()+ .map(|session| session.lock().revision());+ if current_revision != Some(revision)+ || self.view.mode != mode+ || self.view.selection.focus.byte != caret+ {+ return false;+ }+ let active_start = projection+ .active_syntax(caret)+ .map(|node| node.source.start)+ .unwrap_or(usize::MAX);+ self.projection = projection;+ self.visual = Arc::new(visual);+ self.background_wrap_preferred =+ self.visual.estimated_wrap_work_bytes() >= BACKGROUND_WRAP_THRESHOLD_BYTES;+ self.projection_revision = Some(revision);+ self.visual_key = Some((revision, mode, active_start));+ self.wrapped_key = None;+ self.spelling_revision = None;+ self.spelling_context = None;+ self.line_geometry_key = None;+ self.line_geometry = Arc::new(vec![]);+ true+ }++ pub(crate) fn background_wrap_request(+ &mut self,+ wrap_key: usize,+ ) -> Option<(NoteBackgroundWrapKey, Arc<VisualDocument>, VisualWrapCache)> {+ let (revision, mode, active_start) = self.visual_key?;+ let layout = (revision, mode, active_start, wrap_key);+ let visual_identity = Arc::as_ptr(&self.visual) as usize;+ let request_changed = self.background_wrap_requested_key.is_none_or(|requested| {+ requested.layout != layout || requested.visual_identity != visual_identity+ });+ if request_changed {+ self.background_wrap_generation = self.background_wrap_generation.wrapping_add(1);+ self.background_wrap_requested_key = Some(NoteBackgroundWrapKey {+ layout,+ visual_identity,+ generation: self.background_wrap_generation,+ });+ }+ let key = self.background_wrap_requested_key?;+ if self.wrapped_key == Some(layout) || self.background_wrap_in_flight_key.is_some() {+ return None;+ }+ if !self.background_wrap_preferred {+ return None;+ }+ self.background_wrap_in_flight_key = Some(key);+ Some((+ key,+ Arc::clone(&self.visual),+ std::mem::take(&mut self.wrap_cache),+ ))+ }++ pub(crate) fn prefers_background_wrap(&self) -> bool {+ self.background_wrap_preferred+ }++ pub(crate) fn apply_background_wrap(+ &mut self,+ key: NoteBackgroundWrapKey,+ wrapped: Arc<VisualDocument>,+ wrap_cache: VisualWrapCache,+ ) -> bool {+ if self.background_wrap_in_flight_key != Some(key) {+ return false;+ }+ self.background_wrap_in_flight_key = None;+ let current_visual_identity = Arc::as_ptr(&self.visual) as usize;+ if self.background_wrap_requested_key != Some(key)+ || self.visual_key != Some((key.layout.0, key.layout.1, key.layout.2))+ || current_visual_identity != key.visual_identity+ {+ return false;+ }+ self.wrap_cache = wrap_cache;+ self.wrapped_visual = wrapped;+ self.wrapped_key = Some(key.layout);+ self.line_geometry_key = None;+ self.line_geometry = Arc::new(vec![]);+ true+ }++ pub(crate) fn background_parse_pending(&self) -> bool {+ let current = self+ .session+ .as_ref()+ .map(|session| session.lock().revision());+ current.is_some_and(|revision| self.projection_revision != Some(revision))+ }++ pub(crate) fn begin_live_editing(&mut self) {+ if matches!(self.display_source, NoteDisplaySource::Live) {+ return;+ }+ self.display_source = NoteDisplaySource::Live;+ self.projection_revision = None;+ self.visual_key = None;+ self.wrapped_key = None;+ if let Some(session) = self.session.as_ref().cloned() {+ session.lock().clamp_view(&mut self.view);+ }+ self.refresh_projection();+ }++ pub(crate) fn freeze_live_source(&mut self) {+ if !matches!(self.display_source, NoteDisplaySource::Live) {+ return;+ }+ let Some(session) = self.session.as_ref() else {+ return;+ };+ self.display_source = NoteDisplaySource::Frozen(session.lock().current_snapshot());+ }++ pub(crate) fn apply_published_snapshot(&mut self, saved_revision: u64) -> bool {+ let can_publish = match &self.display_source {+ NoteDisplaySource::Published => true,+ NoteDisplaySource::Frozen(snapshot) => snapshot.revision <= saved_revision,+ // A successful autosave must not kick the focused editor out of+ // Live mode. That transition forced a full rebuild on the next+ // key and was visible as a brief post-save flash.+ NoteDisplaySource::Live => false,+ };+ if !can_publish {+ return false;+ }+ let changed = !matches!(self.display_source, NoteDisplaySource::Published)+ || self.projection_revision != Some(saved_revision);+ self.display_source = NoteDisplaySource::Published;+ if changed {+ self.projection_revision = None;+ self.visual_key = None;+ self.wrapped_key = None;+ }+ changed+ }++ pub(crate) fn display_save_state(&self) -> SaveState {+ let Some(session) = self.session.as_ref() else {+ return SaveState::Saved;+ };+ let session = session.lock();+ match &self.display_source {+ NoteDisplaySource::Published => SaveState::Saved,+ NoteDisplaySource::Live => session.save_state().clone(),+ NoteDisplaySource::Frozen(snapshot)+ if session.published_snapshot().revision >= snapshot.revision =>+ {+ SaveState::Saved+ }+ NoteDisplaySource::Frozen(_) => session.save_state().clone(),+ }+ }++ pub(crate) fn note_edited(&mut self, now: Instant, delay: Duration) -> bool {+ self.autosave_deadline = Some(now + delay);+ if self.autosave_timer_scheduled {+ false+ } else {+ self.autosave_timer_scheduled = true;+ true+ }+ }++ pub(crate) fn autosave_woke(&mut self, now: Instant) -> AutosaveWakeAction {+ match self.autosave_deadline {+ None => {+ self.autosave_timer_scheduled = false;+ AutosaveWakeAction::Idle+ }+ Some(deadline) if deadline > now => {+ AutosaveWakeAction::Reschedule(deadline.duration_since(now))+ }+ Some(_) => {+ self.autosave_deadline = None;+ self.autosave_timer_scheduled = false;+ AutosaveWakeAction::SaveNow+ }+ }+ }++ pub(crate) fn cancel_autosave_deadline(&mut self) {+ self.autosave_deadline = None;}pub(crate) fn cached_wrapped_visual(&self, wrap_key: usize) -> Option<Arc<VisualDocument>> {@@ -160,15 +686,19 @@ impl NoteHostState {pub(crate) fn cache_wrapped_visual(&mut self,wrap_key: usize,- visual: VisualDocument,+ visual: Arc<VisualDocument>,) -> Arc<VisualDocument> {- self.wrapped_visual = Arc::new(visual);+ self.wrapped_visual = visual;if let Some((revision, mode, active_start)) = self.visual_key {self.wrapped_key = Some((revision, mode, active_start, wrap_key));}Arc::clone(&self.wrapped_visual)}+ pub(crate) fn provisional_wrapped_visual(&self) -> Arc<VisualDocument> {+ Arc::clone(&self.wrapped_visual)+ }+pub(crate) fn source_position_for_point(&self, x: f32, y: f32) -> SourcePosition {let Some(line) = self.line_layouts@@ -207,6 +737,114 @@ impl NoteHostState {.unwrap_or_else(|| SourcePosition::new(run.source.start))}+ pub(crate) fn selection_range_for_granularity(+ &self,+ position: SourcePosition,+ granularity: SelectionGranularity,+ ) -> Range<usize> {+ let Some(session) = self.session.as_ref() else {+ return position.byte..position.byte;+ };+ let session = session.lock();+ match granularity {+ SelectionGranularity::Character => position.byte..position.byte,+ SelectionGranularity::Word => session.word_range_at(position.byte),+ SelectionGranularity::MarkdownBlock => {+ let block = self+ .projection+ .blocks+ .iter()+ .filter(|block| {+ block.source.start <= position.byte && position.byte <= block.source.end+ })+ .min_by_key(|block| {+ let priority = match block.kind {+ super::BlockKind::ListItem+ | super::BlockKind::Heading(_)+ | super::BlockKind::Quote => 0usize,+ super::BlockKind::Paragraph => 1,+ super::BlockKind::CodeBlock | super::BlockKind::Table => 2,+ super::BlockKind::List => 3,+ super::BlockKind::Properties+ | super::BlockKind::Callout+ | super::BlockKind::Embed+ | super::BlockKind::Other => 4,+ };+ (+ priority,+ block.source.end.saturating_sub(block.source.start),+ )+ });+ match block.map(|block| block.kind) {+ Some(super::BlockKind::CodeBlock | super::BlockKind::Table) | None => {+ session.source_line_selection_range(position.byte)+ }+ Some(_) => block+ .map(|block| block.source.clone())+ .unwrap_or(position.byte..position.byte),+ }+ }+ }+ }++ pub(crate) fn begin_selection(+ &mut self,+ position: SourcePosition,+ granularity: SelectionGranularity,+ extend: bool,+ ) {+ let range = self.selection_range_for_granularity(position, granularity);+ self.selection_granularity = granularity;+ if extend {+ self.view.selection.focus = SourcePosition::new(match granularity {+ SelectionGranularity::Character => position.byte,+ SelectionGranularity::Word | SelectionGranularity::MarkdownBlock => {+ if position.byte < self.view.selection.anchor.byte {+ range.start+ } else {+ range.end+ }+ }+ });+ self.drag_selection_base = Some(self.view.selection.range());+ } else {+ self.view.selection = if granularity == SelectionGranularity::Character {+ SourceSelection::caret(position.byte)+ } else {+ SourceSelection {+ anchor: SourcePosition::new(range.start),+ focus: SourcePosition::new(range.end),+ }+ };+ self.drag_selection_base = Some(range);+ }+ self.view.preferred_column = None;+ }++ pub(crate) fn extend_selection_to(&mut self, position: SourcePosition) {+ let base = self+ .drag_selection_base+ .clone()+ .unwrap_or_else(|| self.view.selection.range());+ let target = self.selection_range_for_granularity(position, self.selection_granularity);+ match self.selection_granularity {+ SelectionGranularity::Character => self.view.selection.focus = position,+ SelectionGranularity::Word | SelectionGranularity::MarkdownBlock => {+ if target.end <= base.start {+ self.view.selection.anchor = SourcePosition::new(base.end);+ self.view.selection.focus = SourcePosition::new(target.start);+ } else if target.start >= base.end {+ self.view.selection.anchor = SourcePosition::new(base.start);+ self.view.selection.focus = SourcePosition::new(target.end);+ } else {+ self.view.selection.anchor = SourcePosition::new(base.start);+ self.view.selection.focus = SourcePosition::new(base.end);+ }+ }+ }+ self.view.preferred_column = None;+ }+/// Move between painted visual rows (including soft wraps) while retaining/// the preferred horizontal pixel. The controller falls back to physical/// source-line navigation when the target row is outside the current@@ -257,6 +895,42 @@ impl NoteHostState {.map(|run| run.source.clone())}+ pub(crate) fn external_link_target_for_point(&self, x: f32, y: f32) -> Option<String> {+ let run = self+ .line_layouts+ .iter()+ .find(|line| y >= line.y && y <= line.y + line.height)?+ .runs+ .iter()+ .find(|run| x >= run.x && x <= run.x + run.width)?;+ let hit_source = run+ .boundaries+ .windows(2)+ .find_map(|pair| {+ let (left_x, left_byte) = pair[0];+ let (right_x, right_byte) = pair[1];+ let min_x = left_x.min(right_x);+ let max_x = left_x.max(right_x);+ (x >= min_x && x < max_x).then(|| {+ left_byte.min(right_byte)..left_byte.max(right_byte)+ })+ })+ .unwrap_or_else(|| run.source.clone());+ self.projection+ .text+ .iter()+ .filter_map(|span| {+ let target = span.link_target.as_ref()?;+ (span.source.start < hit_source.end && hit_source.start < span.source.end)+ .then_some(target)+ })+ .find(|target| {+ url::Url::parse(target)+ .is_ok_and(|url| matches!(url.scheme(), "http" | "https" | "mailto"))+ })+ .cloned()+ }+pub(crate) fn table_cell_target(&self, delta: isize) -> Option<usize> {let caret = self.view.selection.focus.byte;let cells: Vec<_> = self@@ -321,6 +995,350 @@ impl NoteHostState {}}+fn progressive_preview_end(source: &str, target: usize) -> usize {+ if source.len() <= target {+ return source.len();+ }+ let mut end = target.min(source.len());+ while end > 0 && !source.is_char_boundary(end) {+ end -= 1;+ }+ if let Some(newline) = source[..end].rfind('\n') {+ if newline >= target / 2 {+ return newline + 1;+ }+ }+ end+}++#[cfg(test)]+mod state_tests {+ use super::*;+ use std::path::PathBuf;++ fn host_with_source(source: &str) -> NoteHostState {+ let mut host = NoteHostState::default();+ host.session = Some(Arc::new(Mutex::new(MarkdownDocumentSession::new(+ "doc".into(),+ PathBuf::from("Inbox.md"),+ source.into(),+ ))));+ host.refresh_projection();+ host+ }++ #[test]+ fn large_document_seeds_first_screen_before_full_background_parse() {+ let paragraph = "First-screen text with **formatting** and enough words to wrap.\n\n";+ let source = paragraph.repeat(BACKGROUND_PARSE_THRESHOLD_BYTES / paragraph.len() + 8);+ let session = Arc::new(Mutex::new(MarkdownDocumentSession::new(+ "large".into(),+ PathBuf::from("Large.md"),+ source,+ )));+ let document = VaultDocument {+ vault_root: PathBuf::from("vault"),+ relative_path: "Large.md".into(),+ document_path: PathBuf::from("vault/Large.md"),+ session,+ };+ let mut host = NoteHostState::default();++ assert!(host.bind_document(document));+ assert!(!host.visual.lines.is_empty());+ assert_eq!(host.projection_revision, None);+ assert!(!host.prefers_background_wrap());+ assert!(host.background_parse_request().is_some());+ }++ #[test]+ fn published_host_ignores_unsaved_shared_revision() {+ let mut host = host_with_source("saved");+ let session = host.session.as_ref().unwrap().clone();+ let mut view = EditorViewState::default();+ session.lock().set_caret(&mut view, 5, false);+ assert!(session.lock().insert_text(&mut view, " draft"));++ host.refresh_projection();+ assert_eq!(host.projection_revision, Some(0));++ let (revision, _, source) = session.lock().snapshot_for_save();+ session.lock().finish_save(revision, source, Ok(()));+ assert!(host.apply_published_snapshot(revision));+ host.refresh_projection();+ assert_eq!(host.projection_revision, Some(revision));+ }++ #[test]+ fn newer_live_revision_is_not_replaced_by_older_publish() {+ let mut host = host_with_source("a");+ host.begin_live_editing();+ let session = host.session.as_ref().unwrap().clone();+ let mut view = EditorViewState::default();+ session.lock().set_caret(&mut view, 1, false);+ assert!(session.lock().insert_text(&mut view, "b"));+ host.refresh_projection();+ assert_eq!(host.projection_revision, Some(1));+ assert!(!host.apply_published_snapshot(0));+ assert_eq!(host.projection_revision, Some(1));+ }++ #[test]+ fn successful_autosave_keeps_the_focused_host_live() {+ let mut host = host_with_source("a");+ host.begin_live_editing();+ let session = host.session.as_ref().unwrap().clone();+ let mut view = EditorViewState::default();+ session.lock().set_caret(&mut view, 1, false);+ assert!(session.lock().insert_text(&mut view, "b"));+ host.refresh_projection();+ let (revision, _, source) = session.lock().snapshot_for_save();+ session.lock().finish_save(revision, source, Ok(()));++ assert!(!host.apply_published_snapshot(revision));+ assert!(matches!(host.display_source, NoteDisplaySource::Live));+ assert_eq!(host.projection_revision, Some(revision));+ assert_eq!(host.display_save_state(), SaveState::Saved);+ }++ #[test]+ fn autosave_uses_one_reschedulable_wakeup() {+ let mut host = NoteHostState::default();+ let start = Instant::now();+ let delay = Duration::from_millis(500);+ assert!(host.note_edited(start, delay));+ assert!(!host.note_edited(start + Duration::from_millis(100), delay));+ assert_eq!(+ host.autosave_woke(start + delay),+ AutosaveWakeAction::Reschedule(Duration::from_millis(100))+ );+ assert_eq!(+ host.autosave_woke(start + Duration::from_millis(600)),+ AutosaveWakeAction::SaveNow+ );+ assert!(host.note_edited(start + Duration::from_millis(700), delay));+ host.cancel_autosave_deadline();+ assert_eq!(+ host.autosave_woke(start + Duration::from_millis(1200)),+ AutosaveWakeAction::Idle+ );+ }++ #[test]+ fn nontrivial_note_wrap_is_single_flight_and_latest_width_wins() {+ let source = "ordinary proportional-font prose ".repeat(1_300);+ assert!(source.len() < BACKGROUND_PARSE_THRESHOLD_BYTES);+ let mut host = host_with_source(&source);+ assert!(host.prefers_background_wrap());++ let (old_key, _, old_cache) = host.background_wrap_request(7).expect("wrap request");+ assert!(host.background_wrap_request(8).is_none());+ assert!(!host.apply_background_wrap(+ old_key,+ Arc::new(VisualDocument::default()),+ old_cache,+ ));++ let (new_key, _, new_cache) = host.background_wrap_request(8).expect("latest wrap");+ assert_ne!(new_key.generation, old_key.generation);+ assert_eq!(new_key.layout.3, 8);+ assert!(host.apply_background_wrap(+ new_key,+ Arc::new(VisualDocument::default()),+ new_cache,+ ));+ }++ #[test]+ fn repeated_paint_keeps_current_wrap_request_valid() {+ let mut host = host_with_source(&"text that needs wrapping ".repeat(500));+ let (key, _, cache) = host.background_wrap_request(42).expect("wrap request");+ assert!(host.background_wrap_request(42).is_none());+ assert_eq!(host.background_wrap_requested_key, Some(key));+ assert!(host.apply_background_wrap(key, Arc::new(VisualDocument::default()), cache,));+ }++ #[test]+ fn resize_aba_rejects_the_first_matching_width() {+ let mut host = host_with_source(&"text that needs wrapping ".repeat(500));+ let (first_a, _, first_cache) = host.background_wrap_request(10).expect("first A request");+ assert!(host.background_wrap_request(11).is_none());+ assert!(host.background_wrap_request(10).is_none());+ assert_eq!(host.background_wrap_requested_key.unwrap().layout.3, 10);++ assert!(!host.apply_background_wrap(+ first_a,+ Arc::new(VisualDocument::default()),+ first_cache,+ ));+ let (latest_a, _, _) = host+ .background_wrap_request(10)+ .expect("latest A follows single flight");+ assert_ne!(latest_a.generation, first_a.generation);+ }++ #[test]+ fn word_and_markdown_block_drag_keep_semantic_boundaries() {+ let mut host = host_with_source("First paragraph.\n\n- list item\n- second item\n");+ host.begin_live_editing();+ host.begin_selection(SourcePosition::new(2), SelectionGranularity::Word, false);+ host.extend_selection_to(SourcePosition::new(10));+ assert_eq!(+ host.session+ .as_ref()+ .unwrap()+ .lock()+ .selected_text(&host.view),+ Some("First paragraph")+ );++ let list = "First paragraph.\n\n".len();+ host.begin_selection(+ SourcePosition::new(list + 3),+ SelectionGranularity::MarkdownBlock,+ false,+ );+ let selected = host+ .session+ .as_ref()+ .unwrap()+ .lock()+ .selected_text(&host.view)+ .unwrap()+ .to_string();+ assert!(selected.contains("list item"));+ assert!(!selected.contains("second item"));+ }++ #[test]+ #[ignore = "manual Note projection/wrap performance probe"]+ fn note_projection_and_wrap_performance_probe() {+ fn fixture(target_bytes: usize) -> String {+ const PARAGRAPH: &str = "## Heading\n\nA paragraph with **bold**, *italic*, and [link](https://example.com). It contains enough prose to exercise wrapping without making every block a code block.\n\n- [ ] task\n- list item\n\n";+ const CODE: &str = "```rust\nfn value(input: usize) -> usize { input + 1 }\n```\n\n";+ let mut source = String::with_capacity(target_bytes + PARAGRAPH.len() + CODE.len());+ let paragraph_target = (target_bytes / PARAGRAPH.len()).max(1);+ let code_interval = (paragraph_target / 10).max(1);+ let mut paragraph_index = 0usize;+ while source.len() < target_bytes {+ source.push_str(PARAGRAPH);+ if paragraph_index % code_interval == 0 {+ source.push_str(CODE);+ }+ paragraph_index += 1;+ }+ source+ }++ fn p95(mut durations: Vec<Duration>) -> Duration {+ durations.sort_unstable();+ durations[(durations.len() * 95 / 100).min(durations.len() - 1)]+ }++ for target in [250 * 1024, 1024 * 1024, 5 * 1024 * 1024] {+ let source = fixture(target);+ let mut parse_times = Vec::new();+ let mut visual_times = Vec::new();+ let mut wrap_times = Vec::new();+ for _ in 0..12 {+ let started = Instant::now();+ let projection = MarkdownProjection::parse(&source);+ parse_times.push(started.elapsed());+ let started = Instant::now();+ let visual = build_visual_document(+ &source,+ &projection,+ super::super::EditorMode::LivePreview,+ source.len(),+ );+ visual_times.push(started.elapsed());++ let started = Instant::now();+ let wrapped =+ super::super::wrap_visual_document_by_width(&visual, 640.0, |_, _, text| {+ Ok::<f32, ()>(text.chars().count() as f32 * 8.0)+ })+ .unwrap();+ wrap_times.push(started.elapsed());+ assert!(!wrapped.lines.is_empty());+ }+ eprintln!(+ "note_probe bytes={} parse_p95={:?} visual_p95={:?} wrap_p95={:?} total_p95={:?}",+ source.len(),+ p95(parse_times.clone()),+ p95(visual_times.clone()),+ p95(wrap_times.clone()),+ p95(parse_times+ .into_iter()+ .zip(visual_times)+ .zip(wrap_times)+ .map(|((parse, visual), wrap)| parse + visual + wrap)+ .collect())+ );++ let projection = MarkdownProjection::parse(&source);+ let visual = build_visual_document(+ &source,+ &projection,+ super::super::EditorMode::LivePreview,+ source.len(),+ );+ let mut wrap_cache = super::super::VisualWrapCache::default();+ super::super::wrap_visual_document_by_width_cached(+ &visual,+ 640.0,+ 1,+ &mut wrap_cache,+ |_, _, text| Ok::<f32, ()>(text.chars().count() as f32 * 8.0),+ )+ .unwrap();+ let mut edited_source = source;+ let edit_at = edited_source.len() / 2;+ let mut incremental_parse = Vec::new();+ let mut incremental_visual = Vec::new();+ let mut incremental_wrap = Vec::new();+ for _ in 0..12 {+ edited_source.insert(edit_at, 'x');+ let started = Instant::now();+ let projection = MarkdownProjection::parse(&edited_source);+ incremental_parse.push(started.elapsed());+ let started = Instant::now();+ let visual = build_visual_document(+ &edited_source,+ &projection,+ super::super::EditorMode::LivePreview,+ edit_at + 1,+ );+ incremental_visual.push(started.elapsed());+ let started = Instant::now();+ let wrapped = super::super::wrap_visual_document_by_width_cached(+ &visual,+ 640.0,+ 1,+ &mut wrap_cache,+ |_, _, text| Ok::<f32, ()>(text.chars().count() as f32 * 8.0),+ )+ .unwrap();+ incremental_wrap.push(started.elapsed());+ assert!(!wrapped.lines.is_empty());+ }+ eprintln!(+ "note_probe_incremental bytes={} parse_p95={:?} visual_p95={:?} wrap_p95={:?} total_p95={:?}",+ edited_source.len(),+ p95(incremental_parse.clone()),+ p95(incremental_visual.clone()),+ p95(incremental_wrap.clone()),+ p95(incremental_parse+ .into_iter()+ .zip(incremental_visual)+ .zip(incremental_wrap)+ .map(|((parse, visual), wrap)| parse + visual + wrap)+ .collect())+ );+ }+ }+}+fn distance_to_line(line: &NoteLineLayout, y: f32) -> f32 {if y < line.y {line.y - y@@ -394,6 +1412,49 @@ mod tests {assert_eq!(host.source_position_for_point(0.0, 65.0).byte, 2);}+ #[test]+ fn external_link_hit_testing_uses_painted_run_bounds() {+ let source = "Read [docs](https://example.test/guide).";+ let projection = MarkdownProjection::parse(source);+ let link_source = projection+ .text+ .iter()+ .find(|span| span.link_target.is_some())+ .unwrap()+ .source+ .clone();+ let mut host = NoteHostState {+ projection,+ ..NoteHostState::default()+ };+ host.line_layouts.push(NoteLineLayout {+ source: 0..source.len(),+ y: 10.0,+ height: 20.0,+ runs: vec![NoteRunLayout {+ source: 0..source.len(),+ x: 30.0,+ width: 40.0,+ hit_x: 30.0,+ hit_width: 40.0,+ boundaries: vec![+ (30.0, 0),+ (40.0, link_source.start),+ (60.0, link_source.end),+ (70.0, source.len()),+ ],+ atomic: false,+ }],+ });++ assert_eq!(+ host.external_link_target_for_point(50.0, 20.0).as_deref(),+ Some("https://example.test/guide")+ );+ assert_eq!(host.external_link_target_for_point(31.0, 20.0), None);+ assert_eq!(host.external_link_target_for_point(80.0, 20.0), None);+ }+#[test]fn code_block_view_state_is_per_block_and_bounded() {let mut host = NoteHostState::default();diff --git a/wezterm-gui/src/markdown_editor/mod.rs b/wezterm-gui/src/markdown_editor/mod.rsindex 68349d4d..a40a861d 100644--- a/wezterm-gui/src/markdown_editor/mod.rs+++ b/wezterm-gui/src/markdown_editor/mod.rs@@ -7,22 +7,33 @@mod document;mod host;mod projection;+#[allow(dead_code)] // Removed once the Note paint host starts scheduling loads.+mod remote_image;+mod spellcheck;mod store;mod surface;pub(crate) use document::{- Affinity, EditorMode, EditorViewState, MarkdownDocumentSession, SaveState, SourcePosition,- SourceSelection,+ Affinity, DocumentSnapshot, EditorMode, EditorViewState, MarkdownDocumentSession, SaveState,+ SelectionGranularity, SourcePosition, SourceSelection,+};+pub(crate) use host::{+ AutosaveWakeAction, NoteCodeBlockLayout, NoteHostState, NoteLineGeometry, NoteLineLayout,+ NoteRunLayout,};-pub(crate) use host::{NoteCodeBlockLayout, NoteHostState, NoteLineLayout, NoteRunLayout};pub(crate) use projection::{BlockKind, InlineStyle, MarkdownProjection, ProjectedCodeBlock, ProjectedObject, TableAlignment,};+#[allow(unused_imports)] // Standalone API for the pending Note host integration.+pub(crate) use remote_image::{load_remote_image, RemoteImage};+pub(crate) use spellcheck::{build_spell_check_chunks_in_range, NoteSpellingIssue};pub(crate) use store::{- default_document_session, default_notebook, import_attachment, resolve_local_image,- save_document_revision,+ import_attachment, open_vault_document, resolve_local_image, save_document_revision,+ vault_file_paths, vault_markdown_paths, VaultDocument,};+#[cfg(test)]+pub(crate) use surface::wrap_visual_document_by_width;pub(crate) use surface::{- build_visual_document, fit_table_columns, wrap_visual_document_by_width, VisualDocument,- VisualLineKind,+ build_visual_document, fit_table_columns, wrap_visual_document_by_width_cached, VisualDocument,+ VisualLineKind, VisualWrapCache,};diff --git a/wezterm-gui/src/markdown_editor/projection.rs b/wezterm-gui/src/markdown_editor/projection.rsindex 3634564e..6c5f362d 100644--- a/wezterm-gui/src/markdown_editor/projection.rs+++ b/wezterm-gui/src/markdown_editor/projection.rs@@ -1,7 +1,9 @@use pulldown_cmark::{Alignment, CodeBlockKind, Event, Options, Parser, Tag, TagEnd};+use std::collections::{HashMap, HashSet};use std::ops::Range;+use std::path::Path;-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub(crate) enum BlockKind {Paragraph,Heading(u8),@@ -10,10 +12,13 @@ pub(crate) enum BlockKind {ListItem,CodeBlock,Table,+ Properties,+ Callout,+ Embed,Other,}-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]pub(crate) struct InlineStyle {pub strong: bool,pub emphasis: bool,@@ -36,6 +41,10 @@ pub(crate) enum MarkdownSyntaxKind {Quote,CodeBlock,Table,+ WikiLink,+ Frontmatter,+ Callout,+ BlockId,}#[derive(Debug, Clone, PartialEq, Eq)]@@ -96,6 +105,15 @@ pub(crate) struct ProjectedCodeBlock {pub language: Option<String>,}+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct ProjectedProperty {+ pub source: Range<usize>,+ pub key_source: Range<usize>,+ pub value_source: Range<usize>,+ pub key: String,+ pub value: String,+}+#[derive(Debug, Clone, PartialEq, Eq)]pub(crate) enum ProjectedObject {Rule {@@ -117,6 +135,29 @@ pub(crate) enum ProjectedObject {},CodeBlock(ProjectedCodeBlock),Table(ProjectedTable),+ Frontmatter {+ source: Range<usize>,+ fields: Vec<ProjectedProperty>,+ },+ WikiLink {+ source: Range<usize>,+ target: String,+ label: String,+ embed: bool,+ resolved_path: Option<String>,+ ambiguous_paths: Vec<String>,+ rendered_lines: Vec<String>,+ },+ Callout {+ source: Range<usize>,+ kind: String,+ title: String,+ body: Vec<(Range<usize>, String)>,+ },+ BlockId {+ source: Range<usize>,+ id: String,+ },}impl ProjectedObject {@@ -125,7 +166,11 @@ impl ProjectedObject {Self::Rule { source }| Self::TaskCheckbox { source, .. }| Self::ListMarker { source, .. }- | Self::Image { source, .. } => source.clone(),+ | Self::Image { source, .. }+ | Self::Frontmatter { source, .. }+ | Self::WikiLink { source, .. }+ | Self::Callout { source, .. }+ | Self::BlockId { source, .. } => source.clone(),Self::CodeBlock(code) => code.source.clone(),Self::Table(table) => table.source.clone(),}@@ -195,8 +240,10 @@ struct TableBuilder {impl MarkdownProjection {pub(crate) fn parse(source: &str) -> Self {- let options =- Options::ENABLE_STRIKETHROUGH | Options::ENABLE_TABLES | Options::ENABLE_TASKLISTS;+ let options = Options::ENABLE_STRIKETHROUGH+ | Options::ENABLE_TABLES+ | Options::ENABLE_TASKLISTS+ | Options::ENABLE_FOOTNOTES;let mut projection = Self::default();let mut styles = StyleState::default();let mut block_stack = vec![BlockKind::Paragraph];@@ -460,6 +507,7 @@ impl MarkdownProjection {}}}+ projection.apply_obsidian_extensions(source);projection.blocks.sort_by_key(|block| (block.source.start, block.source.end));@@ -476,6 +524,109 @@ impl MarkdownProjection {projection}+ fn apply_obsidian_extensions(&mut self, source: &str) {+ if let Some((range, fields)) = parse_frontmatter(source) {+ self.text+ .retain(|span| !ranges_overlap(&span.source, &range));+ self.objects+ .retain(|object| !ranges_overlap(&object.source(), &range));+ self.blocks+ .retain(|block| !ranges_overlap(&block.source, &range));+ self.syntax+ .retain(|node| !ranges_overlap(&node.source, &range));+ self.syntax.push(MarkdownSyntaxNode {+ kind: MarkdownSyntaxKind::Frontmatter,+ source: range.clone(),+ });+ self.objects.push(ProjectedObject::Frontmatter {+ source: range,+ fields,+ });+ }++ for (range, target, label, embed) in parse_wiki_links(source, &self.syntax) {+ self.syntax.push(MarkdownSyntaxNode {+ kind: MarkdownSyntaxKind::WikiLink,+ source: range.clone(),+ });+ self.objects.push(ProjectedObject::WikiLink {+ source: range,+ target,+ label,+ embed,+ resolved_path: None,+ ambiguous_paths: vec![],+ rendered_lines: vec![],+ });+ }+ for (range, kind, title, body) in parse_callouts(source, &self.syntax) {+ self.syntax.push(MarkdownSyntaxNode {+ kind: MarkdownSyntaxKind::Callout,+ source: range.clone(),+ });+ self.objects.push(ProjectedObject::Callout {+ source: range,+ kind,+ title,+ body,+ });+ }+ for (range, id) in parse_block_ids(source, &self.syntax) {+ self.syntax.push(MarkdownSyntaxNode {+ kind: MarkdownSyntaxKind::BlockId,+ source: range.clone(),+ });+ self.objects+ .push(ProjectedObject::BlockId { source: range, id });+ }+ self.text = project_tags(project_plain_urls(std::mem::take(&mut self.text)));+ }++ pub(crate) fn resolve_vault_links(&mut self, vault_root: &Path, current_note: &str) {+ if !self+ .objects+ .iter()+ .any(|object| matches!(object, ProjectedObject::WikiLink { .. }))+ {+ return;+ }+ let paths = match crate::markdown_editor::vault_file_paths(vault_root) {+ Ok(paths) => paths,+ Err(err) => {+ log::debug!("unable to index Vault links: {err:#}");+ return;+ }+ };+ let index = VaultLinkIndex::new(paths);+ let current_directory = Path::new(current_note)+ .parent()+ .unwrap_or_else(|| Path::new(""));+ for object in &mut self.objects {+ let ProjectedObject::WikiLink {+ target,+ embed,+ resolved_path,+ ambiguous_paths,+ rendered_lines,+ ..+ } = object+ else {+ continue;+ };+ let resolution = index.resolve(current_directory, target);+ *resolved_path = resolution.path;+ *ambiguous_paths = resolution.ambiguous_paths;+ rendered_lines.clear();+ if *embed {+ if let Some(path) = resolved_path.as_deref() {+ let mut visiting = HashSet::new();+ *rendered_lines =+ render_embedded_note(vault_root, path, &index, 0, &mut visiting);+ }+ }+ }+ }+pub(crate) fn active_syntax(&self, byte: usize) -> Option<&MarkdownSyntaxNode> {self.syntax.iter()@@ -483,6 +634,19 @@ impl MarkdownProjection {.min_by_key(|node| node.source.end.saturating_sub(node.source.start))}+ pub(crate) fn active_block_range(&self, byte: usize) -> Option<Range<usize>> {+ let end = self+ .blocks+ .partition_point(|block| block.source.start <= byte);+ self.blocks[..end]+ .iter()+ .rev()+ .take(64)+ .filter(|block| byte <= block.source.end)+ .min_by_key(|block| block.source.end.saturating_sub(block.source.start))+ .map(|block| block.source.clone())+ }+pub(crate) fn visible_source_ranges(&self,source: &str,@@ -507,6 +671,653 @@ impl MarkdownProjection {}}+fn ranges_overlap(left: &Range<usize>, right: &Range<usize>) -> bool {+ left.start < right.end && right.start < left.end+}++fn range_is_literal_code_or_frontmatter(+ range: &Range<usize>,+ syntax: &[MarkdownSyntaxNode],+) -> bool {+ syntax.iter().any(|node| {+ matches!(+ node.kind,+ MarkdownSyntaxKind::InlineCode+ | MarkdownSyntaxKind::CodeBlock+ | MarkdownSyntaxKind::Frontmatter+ ) && ranges_overlap(&node.source, range)+ })+}++fn parse_frontmatter(source: &str) -> Option<(Range<usize>, Vec<ProjectedProperty>)> {+ let opening_end = source+ .strip_prefix("---\n")+ .map(|_| 4)+ .or_else(|| source.strip_prefix("---\r\n").map(|_| 5))?;+ let mut cursor = opening_end;+ let mut closing_end = None;+ while cursor <= source.len() {+ let line_end = source[cursor..]+ .find('\n')+ .map(|offset| cursor + offset)+ .unwrap_or(source.len());+ if source[cursor..line_end].trim_end_matches('\r').trim() == "---" {+ closing_end = Some(if line_end < source.len() {+ line_end + 1+ } else {+ line_end+ });+ break;+ }+ if line_end == source.len() {+ break;+ }+ cursor = line_end + 1;+ }+ let closing_end = closing_end?;+ let closing_start = source[..closing_end].rfind("---").unwrap_or(closing_end);+ let body = &source[opening_end..closing_start];+ let mut fields: Vec<ProjectedProperty> = Vec::new();+ let mut source_offset = opening_end;+ for chunk in body.split_inclusive('\n') {+ let raw_line = chunk.trim_end_matches(['\r', '\n']);+ let line = raw_line.trim();+ if line.is_empty() || line.starts_with('#') {+ source_offset += chunk.len();+ continue;+ }+ if raw_line.len() > line.len() {+ if let Some(item) = line.strip_prefix("- ") {+ if let Some(field) = fields.last_mut() {+ if !field.value.is_empty() {+ field.value.push_str(", ");+ }+ field.value.push_str(item.trim().trim_matches(['\'', '"']));+ field.source.end = source_offset + raw_line.len();+ field.value_source.end = field.source.end;+ }+ source_offset += chunk.len();+ continue;+ }+ }+ let Some((key, value)) = line.split_once(':') else {+ source_offset += chunk.len();+ continue;+ };+ let key = key.trim();+ if key.is_empty() {+ source_offset += chunk.len();+ continue;+ }+ let leading = raw_line.len().saturating_sub(raw_line.trim_start().len());+ let key_start = source_offset + leading;+ let colon = line.find(':').unwrap_or(key.len());+ let key_end = key_start + colon;+ let raw_value_start = key_end + 1;+ let value_leading = source[raw_value_start..source_offset + raw_line.len()]+ .len()+ .saturating_sub(+ source[raw_value_start..source_offset + raw_line.len()]+ .trim_start()+ .len(),+ );+ let value_start = raw_value_start + value_leading;+ fields.push(ProjectedProperty {+ source: key_start..source_offset + raw_line.len(),+ key_source: key_start..key_end,+ value_source: value_start..source_offset + raw_line.len(),+ key: key.to_string(),+ value: value.trim().trim_matches(['\'', '"']).to_string(),+ });+ source_offset += chunk.len();+ }+ Some((0..closing_end, fields))+}++fn parse_wiki_links(+ source: &str,+ syntax: &[MarkdownSyntaxNode],+) -> Vec<(Range<usize>, String, String, bool)> {+ let mut result = Vec::new();+ let mut cursor = 0usize;+ while let Some(relative_start) = source[cursor..].find("[[") {+ let brackets_start = cursor + relative_start;+ let start = brackets_start.saturating_sub(+ (brackets_start > 0 && source.as_bytes()[brackets_start - 1] == b'!') as usize,+ );+ let Some(relative_end) = source[brackets_start + 2..].find("]]") else {+ break;+ };+ let end = brackets_start + 2 + relative_end + 2;+ let range = start..end;+ cursor = end;+ if range_is_literal_code_or_frontmatter(&range, syntax) {+ continue;+ }+ let inner = source[brackets_start + 2..end - 2].trim();+ let (target, alias) = inner+ .split_once('|')+ .map(|(target, alias)| (target.trim(), Some(alias.trim())))+ .unwrap_or((inner, None));+ if target.is_empty() {+ continue;+ }+ let label = alias+ .filter(|alias| !alias.is_empty())+ .unwrap_or(target)+ .to_string();+ result.push((range, target.to_string(), label, start < brackets_start));+ }+ result+}++fn parse_callouts(+ source: &str,+ syntax: &[MarkdownSyntaxNode],+) -> Vec<(Range<usize>, String, String, Vec<(Range<usize>, String)>)> {+ let mut result = Vec::new();+ let mut lines = Vec::new();+ let mut line_start = 0;+ for line in source.split_inclusive('\n') {+ lines.push((line_start, line));+ line_start += line.len();+ }+ let mut index = 0usize;+ while index < lines.len() {+ let (line_start, line) = lines[index];+ let line_without_newline = line.trim_end_matches(['\r', '\n']);+ let Some(quote_offset) = line_without_newline.find('>') else {+ index += 1;+ continue;+ };+ if !line_without_newline[..quote_offset].trim().is_empty() {+ index += 1;+ continue;+ }+ let after_quote = &line_without_newline[quote_offset + 1..];+ let whitespace = after_quote.len() - after_quote.trim_start().len();+ let marker_start = line_start + quote_offset + 1 + whitespace;+ let marker = &line_without_newline[quote_offset + 1 + whitespace..];+ if !marker.starts_with("[!") {+ index += 1;+ continue;+ }+ let Some(close) = marker.find(']') else {+ index += 1;+ continue;+ };+ let kind = marker[2..close].trim();+ if kind.is_empty() {+ index += 1;+ continue;+ }+ let title = marker[close + 1..].trim_start_matches(['+', '-']).trim();+ let mut body = Vec::new();+ let mut next = index + 1;+ while let Some((body_start, body_line)) = lines.get(next).copied() {+ let body_without_newline = body_line.trim_end_matches(['\r', '\n']);+ let leading = body_without_newline.len() - body_without_newline.trim_start().len();+ let Some(after_quote) = body_without_newline[leading..].strip_prefix('>') else {+ break;+ };+ let whitespace = after_quote.len() - after_quote.trim_start().len();+ let text_start = body_start + leading + 1 + whitespace;+ let text = after_quote.trim_start();+ // A second callout header starts a new card even when the author+ // does not put a blank line between the two quote blocks.+ if text.starts_with("[!") {+ break;+ }+ body.push((+ text_start..body_start + body_without_newline.len(),+ clean_embedded_markdown_line(text),+ ));+ next += 1;+ }+ let block_end = lines+ .get(next.saturating_sub(1))+ .map(|(start, line)| start + line.len())+ .unwrap_or_else(|| line_start + line.len());+ let range = marker_start..block_end;+ if !range_is_literal_code_or_frontmatter(&range, syntax) {+ result.push((+ range,+ kind.to_ascii_uppercase(),+ if title.is_empty() {+ kind.to_string()+ } else {+ title.to_string()+ },+ body,+ ));+ }+ index = next.max(index + 1);+ }+ result+}++fn parse_block_ids(source: &str, syntax: &[MarkdownSyntaxNode]) -> Vec<(Range<usize>, String)> {+ let mut result = Vec::new();+ let mut line_start = 0usize;+ for line in source.split_inclusive('\n') {+ let content = line.trim_end_matches(['\r', '\n']);+ let trimmed = content.trim_end();+ let token_start = trimmed+ .rfind(char::is_whitespace)+ .map(|index| index + 1)+ .unwrap_or(0);+ let token = &trimmed[token_start..];+ if let Some(id) = token.strip_prefix('^').filter(|id| {+ !id.is_empty()+ && id+ .chars()+ .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_'))+ }) {+ let range = line_start + token_start..line_start + trimmed.len();+ if !range_is_literal_code_or_frontmatter(&range, syntax) {+ result.push((range, id.to_string()));+ }+ }+ line_start += line.len();+ }+ result+}++fn project_tags(spans: Vec<ProjectedText>) -> Vec<ProjectedText> {+ let mut projected = Vec::with_capacity(spans.len());+ for span in spans {+ if span.style.code || span.source.end.saturating_sub(span.source.start) != span.text.len() {+ projected.push(span);+ continue;+ }+ let bytes = span.text.as_bytes();+ let mut cursor = 0usize;+ let mut found = false;+ while cursor < bytes.len() {+ let Some(relative) = span.text[cursor..].find('#') else {+ break;+ };+ let start = cursor + relative;+ let boundary = start == 0+ || span.text[..start]+ .chars()+ .next_back()+ .is_some_and(|ch| ch.is_whitespace() || matches!(ch, '(' | '[' | '{'));+ let mut end = start + 1;+ while end < bytes.len() {+ let ch = span.text[end..].chars().next().expect("tag char boundary");+ if ch.is_alphanumeric() || matches!(ch, '_' | '-' | '/') {+ end += ch.len_utf8();+ } else {+ break;+ }+ }+ if !boundary || end == start + 1 {+ cursor = start + 1;+ continue;+ }+ found = true;+ if cursor < start {+ projected.push(ProjectedText {+ source: span.source.start + cursor..span.source.start + start,+ text: span.text[cursor..start].to_string(),+ ..span.clone()+ });+ }+ let mut style = span.style;+ style.link = true;+ projected.push(ProjectedText {+ source: span.source.start + start..span.source.start + end,+ text: span.text[start..end].to_string(),+ style,+ block: span.block,+ link_target: Some(span.text[start..end].to_string()),+ });+ cursor = end;+ }+ if found {+ if cursor < span.text.len() {+ projected.push(ProjectedText {+ source: span.source.start + cursor..span.source.end,+ text: span.text[cursor..].to_string(),+ ..span+ });+ }+ } else {+ projected.push(span);+ }+ }+ projected+}++fn project_plain_urls(spans: Vec<ProjectedText>) -> Vec<ProjectedText> {+ let mut projected = Vec::with_capacity(spans.len());+ for span in spans {+ if span.style.code+ || span.link_target.is_some()+ || span.source.end.saturating_sub(span.source.start) != span.text.len()+ {+ projected.push(span);+ continue;+ }++ let mut cursor = 0usize;+ let mut emitted_url = false;+ while cursor < span.text.len() {+ let remaining = &span.text[cursor..];+ let Some(relative_start) = remaining.find("http") else {+ break;+ };+ let start = cursor + relative_start;+ if !span.text[start..].starts_with("http://")+ && !span.text[start..].starts_with("https://")+ {+ cursor = start + "http".len();+ continue;+ }+ let boundary_ok = start == 0+ || span.text[..start]+ .chars()+ .next_back()+ .is_some_and(|ch| ch.is_whitespace() || matches!(ch, '(' | '[' | '{' | '<'));+ if !boundary_ok {+ cursor = start + 1;+ continue;+ }++ let mut end = span.text.len();+ for (relative, ch) in span.text[start..].char_indices() {+ if relative > 0+ && (ch.is_whitespace() || matches!(ch, '<' | '>' | '"' | '\'' | '`'))+ {+ end = start + relative;+ break;+ }+ }+ while end > start {+ let Some(ch) = span.text[start..end].chars().next_back() else {+ break;+ };+ if matches!(ch, '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '}') {+ end -= ch.len_utf8();+ } else {+ break;+ }+ }+ if end <= start+ || url::Url::parse(&span.text[start..end]).is_err()+ || !span.text[start..end]+ .split_once(':')+ .is_some_and(|(scheme, _)| matches!(scheme, "http" | "https"))+ {+ cursor = start + 1;+ continue;+ }++ emitted_url = true;+ if cursor < start {+ projected.push(ProjectedText {+ source: span.source.start + cursor..span.source.start + start,+ text: span.text[cursor..start].to_string(),+ ..span.clone()+ });+ }+ let mut style = span.style;+ style.link = true;+ projected.push(ProjectedText {+ source: span.source.start + start..span.source.start + end,+ text: span.text[start..end].to_string(),+ style,+ block: span.block,+ link_target: Some(span.text[start..end].to_string()),+ });+ cursor = end;+ }++ if emitted_url {+ if cursor < span.text.len() {+ projected.push(ProjectedText {+ source: span.source.start + cursor..span.source.end,+ text: span.text[cursor..].to_string(),+ ..span+ });+ }+ } else {+ projected.push(span);+ }+ }+ projected+}++struct VaultLinkIndex {+ exact: HashMap<String, String>,+ names: HashMap<String, Vec<String>>,+}++#[derive(Default)]+struct VaultLinkResolution {+ path: Option<String>,+ ambiguous_paths: Vec<String>,+}++impl VaultLinkIndex {+ fn new(paths: Vec<String>) -> Self {+ let mut exact = HashMap::new();+ let mut names: HashMap<String, Vec<String>> = HashMap::new();+ for path in &paths {+ exact.insert(path.to_ascii_lowercase(), path.clone());+ let is_markdown = Path::new(path)+ .extension()+ .and_then(|extension| extension.to_str())+ .is_some_and(|extension| extension.eq_ignore_ascii_case("md"));+ if is_markdown {+ // Only notes receive Obsidian's extension-less aliases. An+ // attachment must use its real filename so that `Plan.md` and+ // `Plan.png` cannot shadow each other.+ let without_extension = Path::new(path).with_extension("");+ exact.insert(+ without_extension+ .to_string_lossy()+ .replace('\\', "/")+ .to_ascii_lowercase(),+ path.clone(),+ );+ let Some(stem) = Path::new(path).file_stem().and_then(|stem| stem.to_str()) else {+ continue;+ };+ names+ .entry(stem.to_ascii_lowercase())+ .or_default()+ .push(path.clone());+ }+ }+ Self { exact, names }+ }++ fn resolve(&self, current_directory: &Path, target: &str) -> VaultLinkResolution {+ let target = target+ .split(['#', '^'])+ .next()+ .unwrap_or(target)+ .trim()+ .replace('\\', "/");+ if target.is_empty() {+ return VaultLinkResolution::default();+ }+ let target_path = Path::new(&target);+ let local = current_directory+ .join(target_path)+ .to_string_lossy()+ .replace('\\', "/");+ for candidate in [local.as_str(), target.as_str()] {+ let key = candidate.to_ascii_lowercase();+ if let Some(path) = self.exact.get(&key) {+ return VaultLinkResolution {+ path: Some(path.clone()),+ ambiguous_paths: vec![],+ };+ }+ if !key.ends_with(".md") {+ if let Some(path) = self.exact.get(&format!("{key}.md")) {+ return VaultLinkResolution {+ path: Some(path.clone()),+ ambiguous_paths: vec![],+ };+ }+ }+ }+ let name = target_path+ .file_stem()+ .and_then(|stem| stem.to_str())+ .unwrap_or(&target)+ .to_ascii_lowercase();+ let Some(candidates) = self.names.get(&name) else {+ return VaultLinkResolution::default();+ };+ if candidates.len() == 1 {+ VaultLinkResolution {+ path: Some(candidates[0].clone()),+ ambiguous_paths: vec![],+ }+ } else {+ let mut ambiguous_paths = candidates.clone();+ ambiguous_paths.sort();+ VaultLinkResolution {+ path: None,+ ambiguous_paths,+ }+ }+ }+}++fn render_embedded_note(+ vault_root: &Path,+ relative_path: &str,+ index: &VaultLinkIndex,+ depth: usize,+ visiting: &mut HashSet<String>,+) -> Vec<String> {+ if Path::new(relative_path)+ .extension()+ .and_then(|extension| extension.to_str())+ .is_some_and(|extension| !extension.eq_ignore_ascii_case("md"))+ {+ return vec![format!("Attachment: {relative_path}")];+ }+ if depth >= 3 {+ return vec!["…".to_string()];+ }+ if !visiting.insert(relative_path.to_ascii_lowercase()) {+ return vec![format!("↻ {relative_path} (cycle)")];+ }+ let result = std::fs::read_to_string(vault_root.join(relative_path))+ .map(|source| {+ let frontmatter = parse_frontmatter(&source).map(|(range, _)| range);+ let current_directory = Path::new(relative_path)+ .parent()+ .unwrap_or_else(|| Path::new(""));+ let mut lines = Vec::new();+ let mut source_offset = 0usize;+ let mut in_fence = false;+ for line in source.split_inclusive('\n') {+ if lines.len() >= 200 {+ lines.push("…".to_string());+ break;+ }+ let line_end = source_offset + line.len();+ if frontmatter+ .as_ref()+ .is_some_and(|range| source_offset < range.end && range.start < line_end)+ {+ source_offset = line_end;+ continue;+ }+ let trimmed = line.trim_end_matches(['\r', '\n']).trim();+ if trimmed.starts_with("```") || trimmed.starts_with("~~~") {+ in_fence = !in_fence;+ source_offset = line_end;+ continue;+ }+ if let Some(target) = trimmed+ .strip_prefix("![[")+ .and_then(|value| value.strip_suffix("]]"))+ {+ if let Some(path) = index.resolve(current_directory, target).path {+ lines.extend(render_embedded_note(+ vault_root,+ &path,+ index,+ depth + 1,+ visiting,+ ));+ } else {+ lines.push(format!("▧ {target}"));+ }+ } else if in_fence {+ lines.push(line.trim_end_matches(['\r', '\n']).to_string());+ } else {+ lines.push(clean_embedded_markdown_line(trimmed));+ }+ source_offset = line_end;+ }+ while lines.last().is_some_and(|line| line.is_empty()) {+ lines.pop();+ }+ lines+ })+ .unwrap_or_else(|_| vec![format!("Missing embed: {relative_path}")]);+ visiting.remove(&relative_path.to_ascii_lowercase());+ result+}++fn clean_embedded_markdown_line(line: &str) -> String {+ let mut text = line.trim_start();+ if text.starts_with('#') {+ text = text.trim_start_matches('#').trim_start();+ }+ if text.starts_with('>') {+ text = text.trim_start_matches('>').trim_start();+ }+ if let Some(marker) = text.strip_prefix("[!") {+ if let Some(end) = marker.find(']') {+ let kind = &marker[..end];+ let title = marker[end + 1..].trim_start_matches(['+', '-']).trim();+ return if title.is_empty() {+ kind.to_ascii_uppercase()+ } else {+ format!("{} {title}", kind.to_ascii_uppercase())+ };+ }+ }++ let mut output = String::with_capacity(text.len());+ let mut cursor = 0usize;+ while let Some(start_relative) = text[cursor..].find("[[") {+ let start = cursor + start_relative;+ output.push_str(&text[cursor..start]);+ let Some(end_relative) = text[start + 2..].find("]]") else {+ output.push_str(&text[start..]);+ cursor = text.len();+ break;+ };+ let end = start + 2 + end_relative;+ let inner = &text[start + 2..end];+ let label = inner+ .split_once('|')+ .map(|(_, alias)| alias)+ .unwrap_or(inner);+ output.push_str(label);+ cursor = end + 2;+ }+ if cursor < text.len() {+ output.push_str(&text[cursor..]);+ }+ for marker in ["**", "__", "~~", "`"] {+ output = output.replace(marker, "");+ }+ output+}+fn list_marker(source: &str, item: &Range<usize>) -> Option<ProjectedObject> {let start = item.start.min(source.len());let end = item.end.min(source.len()).max(start);@@ -683,6 +1494,22 @@ mod tests {}}+ #[test]+ fn projects_plain_http_urls_as_clickable_links_without_trailing_punctuation() {+ let source = "Open https://example.test/path/file_name.zip, then continue.";+ let projection = MarkdownProjection::parse(source);+ let link = projection+ .text+ .iter()+ .find(|span| span.link_target.is_some())+ .expect("plain URL should be projected as a link");++ assert_eq!(link.text, "https://example.test/path/file_name.zip");+ assert_eq!(link.link_target.as_deref(), Some(link.text.as_str()));+ assert!(link.style.link);+ assert_eq!(&source[link.source.clone()], link.text);+ }+#[test]fn projects_unordered_and_ordered_list_markers() {let source = "- one\n2. two\n";@@ -755,4 +1582,140 @@ mod tests {.iter().any(|range| range.start <= source.find("**").unwrap() && range.end >= caret));}++ #[test]+ fn captures_obsidian_properties_links_callouts_tags_and_block_ids() {+ let source = "---\ntags: [rust, notes]\nstatus: draft\n---\n\n[[Plan|Release plan]] and #shipping\n\n> [!warning] Check this\n> Body\n\nParagraph ^stable-id\n\n[^1]: footnote\nRef [^1]\n";+ let projection = MarkdownProjection::parse(source);+ assert!(projection.objects.iter().any(|object| matches!(+ object,+ ProjectedObject::Frontmatter { fields, .. }+ if fields.iter().any(|field| field.key == "status" && field.value == "draft")+ )));+ assert!(projection.objects.iter().any(|object| matches!(+ object,+ ProjectedObject::WikiLink { target, label, embed: false, .. }+ if target == "Plan" && label == "Release plan"+ )));+ assert!(projection.objects.iter().any(|object| matches!(+ object,+ ProjectedObject::Callout { kind, title, body, .. }+ if kind == "WARNING" && title == "Check this"+ && body.iter().any(|(_, line)| line == "Body")+ )));+ assert!(projection.objects.iter().any(|object| matches!(+ object,+ ProjectedObject::BlockId { id, .. } if id == "stable-id"+ )));+ assert!(projection.text.iter().any(|span| {+ span.text == "#shipping"+ && span.style.link+ && span.link_target.as_deref() == Some("#shipping")+ }));+ assert!(projection+ .text+ .iter()+ .any(|span| span.text.contains("footnote") || span.text == "1"));+ }++ #[test]+ fn frontmatter_projects_indented_sequence_values() {+ let source = "---\ntitle: Example\ntags:\n - clippings\n - android\n---\n\nBody\n";+ let projection = MarkdownProjection::parse(source);+ assert!(projection.objects.iter().any(|object| matches!(+ object,+ ProjectedObject::Frontmatter { fields, .. }+ if fields.iter().any(|field| field.key == "tags" && field.value == "clippings, android")+ )));+ }++ #[test]+ fn resolves_and_renders_embeds_with_cycle_detection() {+ let temp = tempfile::tempdir().unwrap();+ std::fs::write(temp.path().join("A.md"), "# A\n\n![[B]]\n").unwrap();+ std::fs::write(temp.path().join("B.md"), "## B\n\n![[A]]\n").unwrap();+ let mut projection = MarkdownProjection::parse("![[A]]");+ projection.resolve_vault_links(temp.path(), "Home.md");+ let embed = projection.objects.iter().find_map(|object| match object {+ ProjectedObject::WikiLink {+ resolved_path,+ rendered_lines,+ ..+ } => Some((resolved_path, rendered_lines)),+ _ => None,+ });+ let (resolved, lines) = embed.expect("embed");+ assert_eq!(resolved.as_deref(), Some("A.md"));+ assert!(lines.iter().any(|line| line == "A"));+ assert!(lines.iter().any(|line| line.contains("cycle")));+ }++ #[test]+ fn resolves_attachment_embeds_by_explicit_filename() {+ let temp = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(temp.path().join("assets")).unwrap();+ std::fs::write(temp.path().join("assets/cover.png"), b"not decoded here").unwrap();+ std::fs::write(temp.path().join("cover.md"), "note").unwrap();++ let mut projection = MarkdownProjection::parse("![[assets/cover.png]]");+ projection.resolve_vault_links(temp.path(), "Home.md");+ let attachment = projection.objects.iter().find_map(|object| match object {+ ProjectedObject::WikiLink {+ resolved_path,+ rendered_lines,+ ..+ } => Some((resolved_path, rendered_lines)),+ _ => None,+ });+ let (resolved, lines) = attachment.expect("attachment embed");+ assert_eq!(resolved.as_deref(), Some("assets/cover.png"));+ assert_eq!(lines, &["Attachment: assets/cover.png".to_string()]);+ }++ #[test]+ fn adjacent_callouts_remain_separate_cards() {+ let projection = MarkdownProjection::parse(+ "> [!note] First\n> first body\n> [!warning] Second\n> second body\n",+ );+ let callouts = projection+ .objects+ .iter()+ .filter_map(|object| match object {+ ProjectedObject::Callout {+ kind, title, body, ..+ } => Some((kind, title, body)),+ _ => None,+ })+ .collect::<Vec<_>>();+ assert_eq!(callouts.len(), 2);+ assert_eq!(callouts[0].0, "NOTE");+ assert_eq!(callouts[0].2[0].1, "first body");+ assert_eq!(callouts[1].0, "WARNING");+ assert_eq!(callouts[1].2[0].1, "second body");+ }++ #[test]+ fn reports_ambiguous_wiki_links_instead_of_picking_or_creating_one() {+ let temp = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(temp.path().join("A")).unwrap();+ std::fs::create_dir_all(temp.path().join("B")).unwrap();+ std::fs::write(temp.path().join("A/Plan.md"), "A").unwrap();+ std::fs::write(temp.path().join("B/Plan.md"), "B").unwrap();+ let mut projection = MarkdownProjection::parse("[[Plan]]");+ projection.resolve_vault_links(temp.path(), "Home.md");+ let resolution = projection.objects.iter().find_map(|object| match object {+ ProjectedObject::WikiLink {+ resolved_path,+ ambiguous_paths,+ ..+ } => Some((resolved_path, ambiguous_paths)),+ _ => None,+ });+ let (resolved, ambiguous) = resolution.expect("wiki link");+ assert!(resolved.is_none());+ assert_eq!(+ ambiguous,+ &vec!["A/Plan.md".to_string(), "B/Plan.md".to_string()]+ );+ }}diff --git a/wezterm-gui/src/markdown_editor/remote_image.rs b/wezterm-gui/src/markdown_editor/remote_image.rsnew file mode 100644index 00000000..2a0a22d7--- /dev/null+++ b/wezterm-gui/src/markdown_editor/remote_image.rs@@ -0,0 +1,367 @@+//! Bounded, worker-thread-friendly loading for remote Markdown images.+//!+//! This module intentionally exposes a blocking API. Callers must invoke it+//! from a worker thread rather than the UI thread. Redirects are handled here+//! so that every destination can be resolved and checked before connecting.++use anyhow::{bail, Context};+use reqwest::blocking::{Client, Response};+use reqwest::header::{ACCEPT, ACCEPT_ENCODING, LOCATION};+use std::io::Read;+use std::net::{IpAddr, SocketAddr, ToSocketAddrs};+use std::time::{Duration, Instant};+use termwiz::image::ImageDataType;+use url::{Host, Url};++pub(crate) const REMOTE_IMAGE_MAX_ENCODED_BYTES: usize = 16 * 1024 * 1024;+pub(crate) const REMOTE_IMAGE_MAX_PIXELS: u64 = 16_000_000;+pub(crate) const REMOTE_IMAGE_MAX_REDIRECTS: usize = 5;+pub(crate) const REMOTE_IMAGE_TIMEOUT: Duration = Duration::from_secs(10);++/// Encoded image bytes plus header dimensions. Keeping the original encoding+/// allows `ImageDataType` to retain animated image data and defer full decode+/// until the renderer actually needs it.+#[derive(Debug)]+pub(crate) struct RemoteImage {+ pub(crate) bytes: Vec<u8>,+ pub(crate) width: u32,+ pub(crate) height: u32,+}++impl RemoteImage {+ pub(crate) fn into_image_data(self) -> ImageDataType {+ ImageDataType::EncodedFile(self.bytes)+ }+}++/// Fetch a remote image under strict network, byte-size and decoded-pixel+/// limits. This function blocks and is intended to be called by a worker.+pub(crate) fn load_remote_image(source: &str) -> anyhow::Result<RemoteImage> {+ let started = Instant::now();+ let mut current = parse_remote_url(source)?;++ for redirects_followed in 0..=REMOTE_IMAGE_MAX_REDIRECTS {+ let destination = resolve_public_destination(¤t)+ .with_context(|| format!("resolve remote image host for {current}"))?;+ // Account for DNS time before starting the network request. The+ // platform resolver itself is synchronous, but a slow lookup must not+ // leave a fresh ten-second HTTP budget afterward.+ let remaining = REMOTE_IMAGE_TIMEOUT+ .checked_sub(started.elapsed())+ .context("remote image request timed out")?;+ let client = build_client(¤t, &destination, remaining)?;+ let mut response = client+ .get(current.clone())+ .header(ACCEPT, "image/*")+ .header(ACCEPT_ENCODING, "identity")+ .send()+ .with_context(|| format!("request remote image {current}"))?;++ if let Some(remote) = response.remote_addr() {+ ensure_public_ip(remote.ip()).context("remote image connected to a blocked address")?;+ }++ if response.status().is_redirection() {+ if redirects_followed == REMOTE_IMAGE_MAX_REDIRECTS {+ bail!(+ "remote image exceeded the limit of {} redirects",+ REMOTE_IMAGE_MAX_REDIRECTS+ );+ }+ current = redirect_target(¤t, &response)?;+ continue;+ }++ if !response.status().is_success() {+ bail!("remote image request returned HTTP {}", response.status());+ }++ if response+ .content_length()+ .is_some_and(|len| len > REMOTE_IMAGE_MAX_ENCODED_BYTES as u64)+ {+ bail!(+ "remote image is larger than the {} MiB encoded-data limit",+ REMOTE_IMAGE_MAX_ENCODED_BYTES / 1024 / 1024+ );+ }++ // The client's request timeout covers both receiving the headers and+ // reading the response body. It was set to the budget remaining at+ // the start of this redirect hop.+ let bytes = read_bounded(&mut response, REMOTE_IMAGE_MAX_ENCODED_BYTES)?;+ return validate_encoded_image(bytes);+ }++ unreachable!("redirect loop always returns or fails")+}++fn build_client(+ url: &Url,+ destinations: &[SocketAddr],+ timeout: Duration,+) -> anyhow::Result<Client> {+ let host = url.host_str().context("remote image URL has no host")?;+ let mut builder = Client::builder()+ .redirect(reqwest::redirect::Policy::none())+ .no_proxy()+ .timeout(timeout)+ .connect_timeout(timeout);++ // Pin DNS names to the addresses that passed the public-address policy.+ // IP literals need no resolver override.+ if matches!(url.host(), Some(Host::Domain(_))) {+ builder = builder.resolve_to_addrs(host, destinations);+ }++ builder.build().context("build remote image HTTP client")+}++fn parse_remote_url(source: &str) -> anyhow::Result<Url> {+ let url = Url::parse(source).context("parse remote image URL")?;+ validate_remote_url(&url)?;+ Ok(url)+}++fn validate_remote_url(url: &Url) -> anyhow::Result<()> {+ if !matches!(url.scheme(), "http" | "https") {+ bail!("remote images require an HTTP or HTTPS URL");+ }+ if url.host().is_none() {+ bail!("remote image URL has no host");+ }+ if !url.username().is_empty() || url.password().is_some() {+ bail!("remote image URL must not contain credentials");+ }+ Ok(())+}++fn redirect_target(base: &Url, response: &Response) -> anyhow::Result<Url> {+ let location = response+ .headers()+ .get(LOCATION)+ .context("remote image redirect has no Location header")?+ .to_str()+ .context("remote image redirect Location is not valid text")?;+ let target = base+ .join(location)+ .context("resolve remote image redirect URL")?;+ validate_remote_url(&target)?;+ Ok(target)+}++fn resolve_public_destination(url: &Url) -> anyhow::Result<Vec<SocketAddr>> {+ validate_remote_url(url)?;+ let port = url+ .port_or_known_default()+ .context("remote image URL has no usable port")?;++ let addresses: Vec<SocketAddr> = match url.host().context("remote image URL has no host")? {+ Host::Ipv4(ip) => vec![SocketAddr::new(IpAddr::V4(ip), port)],+ Host::Ipv6(ip) => vec![SocketAddr::new(IpAddr::V6(ip), port)],+ Host::Domain(host) => {+ if host.eq_ignore_ascii_case("localhost") || host.ends_with(".localhost") {+ bail!("remote image host is local");+ }+ (host, port)+ .to_socket_addrs()+ .with_context(|| format!("DNS lookup failed for {host}"))?+ .collect()+ }+ };++ if addresses.is_empty() {+ bail!("remote image host resolved to no addresses");+ }+ for address in &addresses {+ ensure_public_ip(address.ip())?;+ }+ Ok(addresses)+}++fn ensure_public_ip(ip: IpAddr) -> anyhow::Result<()> {+ if is_public_ip(ip) {+ Ok(())+ } else {+ bail!("remote image target address {ip} is not public")+ }+}++fn is_public_ip(ip: IpAddr) -> bool {+ match ip {+ IpAddr::V4(ip) => {+ let [a, b, c, _] = ip.octets();+ !(a == 0+ || a == 10+ || a == 127+ || (a == 100 && (64..=127).contains(&b))+ || (a == 169 && b == 254)+ || (a == 172 && (16..=31).contains(&b))+ || (a == 192 && b == 0 && c == 0)+ || (a == 192 && b == 0 && c == 2)+ || (a == 192 && b == 168)+ || (a == 198 && (b == 18 || b == 19))+ || (a == 198 && b == 51 && c == 100)+ || (a == 203 && b == 0 && c == 113)+ || a >= 224)+ }+ IpAddr::V6(ip) => {+ // Cover both IPv4-mapped (::ffff:a.b.c.d) and the historic+ // IPv4-compatible (::a.b.c.d) representation.+ if let Some(embedded) = ip.to_ipv4() {+ return is_public_ip(IpAddr::V4(embedded));+ }+ let segments = ip.segments();+ !(ip.is_unspecified()+ || ip.is_loopback()+ || ip.is_multicast()+ || (segments[0] & 0xfe00) == 0xfc00 // unique-local fc00::/7+ || (segments[0] & 0xffc0) == 0xfe80 // link-local fe80::/10+ || (segments[0] & 0xffc0) == 0xfec0 // historic site-local fec0::/10+ || (segments[0] == 0x2001 && segments[1] == 0x0db8))+ }+ }+}++fn read_bounded(reader: &mut impl Read, max_bytes: usize) -> anyhow::Result<Vec<u8>> {+ let mut bytes = Vec::new();+ let mut buffer = [0u8; 16 * 1024];+ loop {+ let read = reader+ .read(&mut buffer)+ .context("read remote image response")?;+ if read == 0 {+ break;+ }+ if bytes.len().saturating_add(read) > max_bytes {+ bail!(+ "remote image is larger than the {} MiB encoded-data limit",+ max_bytes / 1024 / 1024+ );+ }+ bytes.extend_from_slice(&buffer[..read]);+ }+ Ok(bytes)+}++fn validate_encoded_image(bytes: Vec<u8>) -> anyhow::Result<RemoteImage> {+ if bytes.len() > REMOTE_IMAGE_MAX_ENCODED_BYTES {+ bail!("remote image exceeds the encoded-data limit");+ }+ let encoded = ImageDataType::EncodedFile(bytes);+ let (width, height) = encoded+ .dimensions()+ .context("decode remote image dimensions")?;+ validate_dimensions(width, height)?;+ let ImageDataType::EncodedFile(bytes) = encoded else {+ unreachable!();+ };+ Ok(RemoteImage {+ bytes,+ width,+ height,+ })+}++fn validate_dimensions(width: u32, height: u32) -> anyhow::Result<()> {+ let pixels = u64::from(width) * u64::from(height);+ if width == 0 || height == 0 {+ bail!("remote image has zero width or height");+ }+ if pixels > REMOTE_IMAGE_MAX_PIXELS {+ bail!(+ "remote image is too large to decode ({width}x{height}, over {} megapixels)",+ REMOTE_IMAGE_MAX_PIXELS / 1_000_000+ );+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Cursor;++ #[test]+ fn url_policy_allows_only_credential_free_http_urls() {+ assert!(validate_remote_url(&Url::parse("https://example.com/image.png").unwrap()).is_ok());+ assert!(validate_remote_url(&Url::parse("http://example.com/image.png").unwrap()).is_ok());+ assert!(validate_remote_url(&Url::parse("file:///tmp/image.png").unwrap()).is_err());+ assert!(validate_remote_url(&Url::parse("ftp://example.com/image.png").unwrap()).is_err());+ assert!(+ validate_remote_url(&Url::parse("https://user:[email protected]/a").unwrap()).is_err()+ );+ }++ #[test]+ fn address_policy_rejects_non_public_ranges() {+ for address in [+ "0.0.0.0",+ "10.1.2.3",+ "100.64.0.1",+ "127.0.0.1",+ "169.254.4.2",+ "172.16.0.1",+ "192.168.1.1",+ "198.18.0.1",+ "224.0.0.1",+ "::",+ "::1",+ "::127.0.0.1",+ "::ffff:127.0.0.1",+ "fc00::1",+ "fe80::1",+ "2001:db8::1",+ ] {+ let ip: IpAddr = address.parse().unwrap();+ assert!(!is_public_ip(ip), "unexpectedly allowed {}", address);+ }+ for address in ["1.1.1.1", "8.8.8.8", "2606:4700:4700::1111"] {+ let ip: IpAddr = address.parse().unwrap();+ assert!(is_public_ip(ip), "unexpectedly blocked {}", address);+ }+ }++ #[test]+ fn literal_private_destination_is_rejected_without_network() {+ for url in [+ "http://127.0.0.1/image.png",+ "http://[::1]/image.png",+ "http://192.168.1.1/image.png",+ "http://localhost/image.png",+ ] {+ let url = Url::parse(url).unwrap();+ assert!(resolve_public_destination(&url).is_err(), "allowed {}", url);+ }+ }++ #[test]+ fn byte_guard_stops_after_limit() {+ let data = vec![0u8; 33];+ let error = read_bounded(&mut Cursor::new(data), 32).unwrap_err();+ assert!(error.to_string().contains("encoded-data limit"));+ }++ #[test]+ fn pixel_guard_is_overflow_safe_and_rejects_oversized_images() {+ assert!(validate_dimensions(4_000, 4_000).is_ok());+ assert!(validate_dimensions(4_001, 4_000).is_err());+ assert!(validate_dimensions(u32::MAX, u32::MAX).is_err());+ assert!(validate_dimensions(0, 100).is_err());+ }++ #[test]+ fn valid_png_retains_encoded_bytes_and_dimensions() {+ // Header-only dimensions are sufficient; this tiny valid PNG is 1x1.+ let bytes = vec![+ 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1,+ 8, 6, 0, 0, 0, 31, 21, 196, 137, 0, 0, 0, 13, 73, 68, 65, 84, 8, 215, 99, 248, 207,+ 192, 240, 31, 0, 5, 0, 1, 255, 137, 153, 61, 29, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66,+ 96, 130,+ ];+ let expected = bytes.clone();+ let image = validate_encoded_image(bytes).unwrap();+ assert_eq!((image.width, image.height), (1, 1));+ assert_eq!(image.bytes, expected);+ }+}diff --git a/wezterm-gui/src/markdown_editor/spellcheck.rs b/wezterm-gui/src/markdown_editor/spellcheck.rsnew file mode 100644index 00000000..81594dcc--- /dev/null+++ b/wezterm-gui/src/markdown_editor/spellcheck.rs@@ -0,0 +1,278 @@+use super::{BlockKind, MarkdownProjection, ProjectedObject};+use std::collections::HashSet;+use std::ops::Range;++const MAX_CHECK_CHUNK_BYTES: usize = 8 * 1024;++#[derive(Debug, Clone)]+pub(crate) struct SpellCheckSegment {+ pub check: Range<usize>,+ pub source: Range<usize>,+}++#[derive(Debug, Clone)]+pub(crate) struct SpellCheckChunk {+ pub text: String,+ pub segments: Vec<SpellCheckSegment>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) struct NoteSpellingIssue {+ pub source: Range<usize>,+ pub word: String,+ pub suggestions: Vec<String>,+}++impl SpellCheckChunk {+ pub(crate) fn source_range_for_issue(&self, issue: Range<usize>) -> Option<Range<usize>> {+ let segment = self+ .segments+ .iter()+ .find(|segment| issue.start >= segment.check.start && issue.end <= segment.check.end)?;+ let start = segment.source.start + issue.start.saturating_sub(segment.check.start);+ let end = segment.source.start + issue.end.saturating_sub(segment.check.start);+ Some(start..end)+ }+}++#[cfg(test)]+pub(crate) fn build_spell_check_chunks(+ source: &str,+ projection: &MarkdownProjection,+) -> Vec<SpellCheckChunk> {+ build_spell_check_chunks_in_range(source, projection, 0..source.len())+}++pub(crate) fn build_spell_check_chunks_in_range(+ source: &str,+ projection: &MarkdownProjection,+ check_range: Range<usize>,+) -> Vec<SpellCheckChunk> {+ let front_matter = front_matter_range(source);+ let mut candidates = Vec::new();+ let mut seen = HashSet::new();++ let text_start = projection+ .text+ .partition_point(|text| text.source.end <= check_range.start);+ for text in projection.text[text_start..]+ .iter()+ .take_while(|text| text.source.start < check_range.end)+ {+ if text.style.code || matches!(text.block, BlockKind::CodeBlock) {+ continue;+ }+ let mut source_range = text.source.clone();+ let mut projected = text.text.as_str();+ if source_range.start < check_range.start || source_range.end > check_range.end {+ if source_range.end.saturating_sub(source_range.start) != projected.len() {+ continue;+ }+ let clipped_start = source_range.start.max(check_range.start);+ let clipped_end = source_range.end.min(check_range.end);+ let relative_start = clipped_start - source_range.start;+ let relative_end = clipped_end - source_range.start;+ let Some(clipped) = projected.get(relative_start..relative_end) else {+ continue;+ };+ source_range = clipped_start..clipped_end;+ projected = clipped;+ }+ push_candidate(+ source,+ source_range,+ projected,+ front_matter.as_ref(),+ &mut seen,+ &mut candidates,+ );+ }++ for object in &projection.objects {+ if !ranges_intersect(&object.source(), &check_range) {+ continue;+ }+ if let ProjectedObject::Table(table) = object {+ for cell in table.rows.iter().flatten() {+ push_candidate(+ source,+ cell.source.clone(),+ &cell.text,+ front_matter.as_ref(),+ &mut seen,+ &mut candidates,+ );+ }+ }+ }++ candidates.sort_by_key(|(range, _)| range.start);+ let mut chunks = Vec::new();+ let mut current = SpellCheckChunk {+ text: String::new(),+ segments: Vec::new(),+ };+ for (source_range, text) in candidates {+ let separator = usize::from(!current.text.is_empty());+ if !current.text.is_empty()+ && current.text.len() + separator + text.len() > MAX_CHECK_CHUNK_BYTES+ {+ chunks.push(current);+ current = SpellCheckChunk {+ text: String::new(),+ segments: Vec::new(),+ };+ }+ if !current.text.is_empty() {+ current.text.push('\n');+ }+ let start = current.text.len();+ current.text.push_str(&text);+ current.segments.push(SpellCheckSegment {+ check: start..start + text.len(),+ source: source_range,+ });+ }+ if !current.text.is_empty() {+ chunks.push(current);+ }+ chunks+}++fn push_candidate(+ source: &str,+ range: Range<usize>,+ projected: &str,+ front_matter: Option<&Range<usize>>,+ seen: &mut HashSet<(usize, usize)>,+ candidates: &mut Vec<(Range<usize>, String)>,+) {+ if range.is_empty()+ || range.end > source.len()+ || front_matter.is_some_and(|front| ranges_intersect(front, &range))+ {+ return;+ }+ let original = &source[range.clone()];+ if original != projected {+ return;+ }+ let excluded = excluded_token_ranges(projected);+ if !excluded.is_empty() {+ let mut kept_start = 0usize;+ for excluded in excluded {+ push_plain_candidate(+ range.start + kept_start..range.start + excluded.start,+ &projected[kept_start..excluded.start],+ seen,+ candidates,+ );+ kept_start = excluded.end;+ }+ push_plain_candidate(+ range.start + kept_start..range.end,+ &projected[kept_start..],+ seen,+ candidates,+ );+ return;+ }+ push_plain_candidate(range, projected, seen, candidates);+}++fn push_plain_candidate(+ range: Range<usize>,+ projected: &str,+ seen: &mut HashSet<(usize, usize)>,+ candidates: &mut Vec<(Range<usize>, String)>,+) {+ let trimmed = projected.trim();+ if trimmed.is_empty() || trimmed.starts_with('<') || !seen.insert((range.start, range.end)) {+ return;+ }+ candidates.push((range, projected.to_string()));+}++fn excluded_token_ranges(text: &str) -> Vec<Range<usize>> {+ let mut ranges = Vec::new();+ let mut search_from = 0usize;+ for token in text.split_whitespace() {+ let Some(relative) = text[search_from..].find(token) else {+ continue;+ };+ let start = search_from + relative;+ let end = start + token.len();+ let normalized = token.trim_matches(|ch: char| {+ matches!(ch, '(' | ')' | '[' | ']' | '<' | '>' | ',' | '.' | ';')+ });+ if normalized.starts_with("http://")+ || normalized.starts_with("https://")+ || normalized.starts_with("www.")+ || normalized.contains('@')+ {+ ranges.push(start..end);+ }+ search_from = end;+ }+ ranges+}++fn ranges_intersect(a: &Range<usize>, b: &Range<usize>) -> bool {+ a.start < b.end && b.start < a.end+}++fn front_matter_range(source: &str) -> Option<Range<usize>> {+ if !source.starts_with("---\n") {+ return None;+ }+ let end = source[4..].find("\n---").map(|offset| 4 + offset + 4)?;+ Some(0..end.min(source.len()))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn excludes_code_urls_and_front_matter() {+ let source = "---\ntitle: Helo\n---\n\nProse mistke https://example.com `codde`\n\n```rs\nlet mistke = 1;\n```";+ let projection = MarkdownProjection::parse(source);+ let text = build_spell_check_chunks(source, &projection)+ .into_iter()+ .map(|chunk| chunk.text)+ .collect::<Vec<_>>()+ .join("\n");+ assert!(text.contains("Prose mistke"));+ assert!(!text.contains("Helo"));+ assert!(!text.contains("https://example.com"));+ assert!(!text.contains("codde"));+ assert!(!text.contains("let mistke"));+ }++ #[test]+ fn maps_check_ranges_back_to_markdown_source() {+ let source = "A **mistke** here";+ let projection = MarkdownProjection::parse(source);+ let chunks = build_spell_check_chunks(source, &projection);+ let chunk = chunks+ .iter()+ .find(|chunk| chunk.text.contains("mistke"))+ .unwrap();+ let start = chunk.text.find("mistke").unwrap();+ assert_eq!(chunk.source_range_for_issue(start..start + 6), Some(4..10));+ }++ #[test]+ fn scoped_check_only_builds_chunks_for_the_active_region() {+ let source = "First mistke.\n\nSecond eror.\n";+ let projection = MarkdownProjection::parse(source);+ let second = source.find("Second").unwrap();+ let text = build_spell_check_chunks_in_range(source, &projection, second..source.len())+ .into_iter()+ .map(|chunk| chunk.text)+ .collect::<Vec<_>>()+ .join("\n");+ assert!(!text.contains("First"));+ assert!(text.contains("Second eror"));+ }+}diff --git a/wezterm-gui/src/markdown_editor/store.rs b/wezterm-gui/src/markdown_editor/store.rsindex e12241ce..7375a12f 100644--- a/wezterm-gui/src/markdown_editor/store.rs+++ b/wezterm-gui/src/markdown_editor/store.rs@@ -1,147 +1,147 @@use super::MarkdownDocumentSession;-use anyhow::{bail, Context, Result};+use anyhow::{bail, ensure, Context, Result};use parking_lot::Mutex;-use serde::{Deserialize, Serialize};+use std::collections::HashMap;use std::fs;-use std::io::{Read, Write};+use std::io::Write;use std::path::{Component, Path, PathBuf};-use std::sync::Arc;+use std::sync::{Arc, Weak};use tempfile::NamedTempFile;-use uuid::Uuid;-pub(crate) type NotebookId = String;-pub(crate) type DocumentId = String;--const STORE_VERSION: u32 = 1;-const MAX_IMPORTED_IMAGE_BYTES: u64 = 25 * 1024 * 1024;-const SUPPORTED_IMAGE_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "gif", "webp"];--#[derive(Debug, Clone, Serialize, Deserialize)]-struct Registry {- version: u32,- default_notebook_id: NotebookId,+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) struct SaveDocumentOutcome {+ pub saved_revision: u64,+ pub current_revision: u64,}-#[derive(Debug, Clone, Serialize, Deserialize)]-struct DocumentRecord {- id: DocumentId,- path: String,-}--#[derive(Debug, Clone, Serialize, Deserialize)]-struct NotebookMetadata {- version: u32,- id: NotebookId,- name: String,- active_document_id: DocumentId,- documents: Vec<DocumentRecord>,-}+const MAX_IMPORTED_IMAGE_BYTES: u64 = 25 * 1024 * 1024;+const SUPPORTED_IMAGE_EXTENSIONS: &[&str] = &[+ "png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "tif", "tiff",+];#[derive(Clone)]-#[allow(dead_code)]-pub(crate) struct DefaultNotebook {- pub notebook_id: NotebookId,- pub document_id: DocumentId,- pub root: PathBuf,- pub content_root: PathBuf,+pub(crate) struct VaultDocument {+ pub vault_root: PathBuf,+ pub relative_path: String,pub document_path: PathBuf,pub session: Arc<Mutex<MarkdownDocumentSession>>,}lazy_static::lazy_static! {- static ref DEFAULT_NOTEBOOK: Mutex<Option<DefaultNotebook>> = Mutex::new(None);+ /// A document opened in two ThinkTerm windows must share one session, or+ /// two independent autosave loops can silently overwrite each other. Weak+ /// values let closed documents fall out without a separate eviction pass.+ static ref DOCUMENT_SESSIONS: Mutex<HashMap<(PathBuf, String), Weak<Mutex<MarkdownDocumentSession>>>> =+ Mutex::new(HashMap::new());static ref ATTACHMENT_IMPORT_LOCK: Mutex<()> = Mutex::new(());}-pub(crate) fn default_notebook() -> Result<DefaultNotebook> {- let mut slot = DEFAULT_NOTEBOOK.lock();- if let Some(notebook) = slot.as_ref() {- return Ok(notebook.clone());+pub(crate) fn open_vault_document(+ vault_root: &Path,+ relative_path: &str,+ create: bool,+) -> Result<VaultDocument> {+ ensure!(+ vault_root.is_dir(),+ "Vault is not a directory: {}",+ vault_root.display()+ );+ let vault_root = vault_root+ .canonicalize()+ .with_context(|| format!("resolve Vault {}", vault_root.display()))?;+ let relative_path = crate::workspace_threads::normalize_vault_markdown_path(relative_path)?;+ let document_path = safe_content_path(&vault_root, Path::new(&relative_path))?;+ if !document_path.exists() {+ ensure!(create, "note does not exist: {relative_path}");+ write_bytes_atomic(&document_path, b"")?;}- let notebook = ensure_default_notebook_at(&crate::native_paths::data_dir().join("notes/v1"))?;- *slot = Some(notebook.clone());- Ok(notebook)-}--pub(crate) fn default_document_session() -> Result<Arc<Mutex<MarkdownDocumentSession>>> {- Ok(default_notebook()?.session)-}--fn ensure_default_notebook_at(base: &Path) -> Result<DefaultNotebook> {- fs::create_dir_all(base).with_context(|| format!("create {}", base.display()))?;- let registry_path = base.join("registry.json");- let registry = if registry_path.exists() {- read_json::<Registry>(®istry_path)?- } else {- let registry = Registry {- version: STORE_VERSION,- default_notebook_id: new_id(),- };- write_json_atomic(®istry_path, ®istry)?;- registry+ ensure!(+ document_path.is_file(),+ "note is not a file: {}",+ document_path.display()+ );++ let key = (vault_root.clone(), relative_path.clone());+ let existing = {+ let mut sessions = DOCUMENT_SESSIONS.lock();+ sessions.retain(|_, session| session.strong_count() > 0);+ sessions.get(&key).and_then(Weak::upgrade)};-- if registry.version != STORE_VERSION {- bail!("unsupported Note registry version {}", registry.version);- }-- let root = base.join("notebooks").join(®istry.default_notebook_id);- let content_root = root.join("content");- let attachments = content_root.join("attachments");- fs::create_dir_all(&attachments)- .with_context(|| format!("create {}", attachments.display()))?;- ensure_canonical_descendant(&content_root, &attachments)?;-- let metadata_path = root.join("notebook.json");- let metadata = if metadata_path.exists() {- read_json::<NotebookMetadata>(&metadata_path)?+ let session = if let Some(session) = existing {+ session} else {- let document_id = new_id();- let metadata = NotebookMetadata {- version: STORE_VERSION,- id: registry.default_notebook_id.clone(),- name: "Notes".to_string(),- active_document_id: document_id.clone(),- documents: vec![DocumentRecord {- id: document_id,- path: "Inbox.md".to_string(),- }],- };- write_json_atomic(&metadata_path, &metadata)?;- metadata+ // Reading a multi-megabyte Note and constructing its line index must not+ // hold the process-wide document registry lock. Two windows may race+ // here; the second registry check below selects one canonical session+ // and lets the unused candidate fall out normally.+ let source = fs::read_to_string(&document_path)+ .with_context(|| format!("read {}", document_path.display()))?;+ let candidate = Arc::new(Mutex::new(MarkdownDocumentSession::new(+ format!("{}::{relative_path}", vault_root.display()),+ document_path.clone(),+ source,+ )));+ let mut sessions = DOCUMENT_SESSIONS.lock();+ sessions.retain(|_, session| session.strong_count() > 0);+ if let Some(session) = sessions.get(&key).and_then(Weak::upgrade) {+ session+ } else {+ sessions.insert(key, Arc::downgrade(&candidate));+ candidate+ }};- if metadata.version != STORE_VERSION || metadata.id != registry.default_notebook_id {- bail!("invalid default Notebook metadata");- }- let document = metadata- .documents- .iter()- .find(|document| document.id == metadata.active_document_id)- .or_else(|| metadata.documents.first())- .context("default Notebook has no document")?;- let document_path = safe_content_path(&content_root, Path::new(&document.path))?;- if !document_path.exists() {- write_bytes_atomic(&document_path, b"")?;- }- let source = fs::read_to_string(&document_path)- .with_context(|| format!("read {}", document_path.display()))?;- let session = Arc::new(Mutex::new(MarkdownDocumentSession::new(- document.id.clone(),- document_path.clone(),- source,- )));- Ok(DefaultNotebook {- notebook_id: registry.default_notebook_id,- document_id: document.id.clone(),- root,- content_root,+ Ok(VaultDocument {+ vault_root,+ relative_path,document_path,session,})}-pub(crate) fn save_document_revision(session: &Arc<Mutex<MarkdownDocumentSession>>) -> Result<u64> {+pub(crate) fn vault_markdown_paths(vault_root: &Path) -> Result<Vec<String>> {+ Ok(vault_file_paths(vault_root)?+ .into_iter()+ .filter(|path| {+ Path::new(path)+ .extension()+ .and_then(|extension| extension.to_str())+ .is_some_and(|extension| extension.eq_ignore_ascii_case("md"))+ })+ .collect())+}++pub(crate) fn vault_file_paths(vault_root: &Path) -> Result<Vec<String>> {+ let canonical_root = vault_root+ .canonicalize()+ .with_context(|| format!("resolve Vault {}", vault_root.display()))?;+ let mut paths = walkdir::WalkDir::new(&canonical_root)+ .follow_links(false)+ .into_iter()+ .filter_entry(|entry| {+ entry.depth() == 0+ || entry+ .file_name()+ .to_str()+ .is_none_or(|name| !name.starts_with('.'))+ })+ .filter_map(|entry| entry.ok())+ .filter(|entry| entry.file_type().is_file())+ .filter_map(|entry| {+ entry+ .path()+ .strip_prefix(&canonical_root)+ .ok()+ .map(|path| path.to_string_lossy().replace('\\', "/"))+ })+ .collect::<Vec<_>>();+ paths.sort_by_key(|path| path.to_ascii_lowercase());+ Ok(paths)+}++pub(crate) fn save_document_revision(+ session: &Arc<Mutex<MarkdownDocumentSession>>,+) -> Result<SaveDocumentOutcome> {let save_lock = session.lock().save_lock();let _save_guard = save_lock.lock();let (revision, path, source) = session.lock().snapshot_for_save();@@ -150,11 +150,18 @@ pub(crate) fn save_document_revision(session: &Arc<Mutex<MarkdownDocumentSession.as_ref().map(|_| ()).map_err(|err| anyhow::anyhow!("{err:#}"));- session.lock().finish_save(revision, finish_result);- result.map(|_| revision)+ let current_revision = {+ let mut session = session.lock();+ session.finish_save(revision, source, finish_result);+ session.revision()+ };+ result.map(|_| SaveDocumentOutcome {+ saved_revision: revision,+ current_revision,+ })}-pub(crate) fn import_attachment(notebook: &DefaultNotebook, source: &Path) -> Result<String> {+pub(crate) fn import_attachment(document: &VaultDocument, source: &Path) -> Result<String> {let _operation_guard = ATTACHMENT_IMPORT_LOCK.lock();let metadata = fs::metadata(source).with_context(|| format!("stat {}", source.display()))?;if !metadata.is_file() {@@ -178,10 +185,14 @@ pub(crate) fn import_attachment(notebook: &DefaultNotebook, source: &Path) -> Re.map(sanitize_file_stem).filter(|value| !value.is_empty()).unwrap_or_else(|| "image".to_string());- let attachment_dir = notebook.content_root.join("attachments");+ let document_parent = document+ .document_path+ .parent()+ .context("Note document has no parent")?;+ let attachment_dir = document_parent.join("attachments");fs::create_dir_all(&attachment_dir).with_context(|| format!("create {}", attachment_dir.display()))?;- ensure_canonical_descendant(¬ebook.content_root, &attachment_dir)?;+ ensure_canonical_descendant(&document.vault_root, &attachment_dir)?;let mut sequence = 1usize;let destination = loop {let name = if sequence == 1 {@@ -210,11 +221,11 @@ pub(crate) fn import_attachment(notebook: &DefaultNotebook, source: &Path) -> Retemporary.persist(&destination).with_context(|| format!("persist {}", destination.display()))?;- set_private_permissions(&destination);+ set_user_document_permissions(&destination, None);let relative = destination- .strip_prefix(¬ebook.content_root)- .context("attachment escaped Notebook content")?;+ .strip_prefix(document_parent)+ .context("attachment escaped Note directory")?;Ok(relative.to_string_lossy().replace('\\', "/"))}@@ -254,7 +265,7 @@ fn safe_content_path(root: &Path, relative: &Path) -> Result<PathBuf> {)}){- bail!("invalid Notebook document path {}", relative.display());+ bail!("invalid Vault document path {}", relative.display());}let candidate = root.join(relative);let canonical_root = root@@ -264,13 +275,13 @@ fn safe_content_path(root: &Path, relative: &Path) -> Result<PathBuf> {while !existing.exists() {existing = existing.parent()- .context("Notebook document path has no existing parent")?;+ .context("Vault document path has no existing parent")?;}let canonical_existing = existing.canonicalize().with_context(|| format!("resolve {}", existing.display()))?;if !canonical_existing.starts_with(&canonical_root) {- bail!("Notebook document path escapes content root");+ bail!("Vault document path escapes root");}Ok(candidate)}@@ -283,15 +294,11 @@ fn ensure_canonical_descendant(root: &Path, path: &Path) -> Result<()> {.canonicalize().with_context(|| format!("resolve {}", path.display()))?;if !canonical_path.starts_with(canonical_root) {- bail!("{} escapes Notebook content root", path.display());+ bail!("{} escapes Vault root", path.display());}Ok(())}-fn new_id() -> String {- Uuid::new_v4().simple().to_string()-}-fn sanitize_file_stem(stem: &str) -> String {let mut result = String::new();let mut previous_dash = false;@@ -307,22 +314,12 @@ fn sanitize_file_stem(stem: &str) -> String {result.trim_matches('-').chars().take(80).collect()}-fn read_json<T: for<'de> Deserialize<'de>>(path: &Path) -> Result<T> {- let mut file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;- let mut bytes = Vec::new();- file.read_to_end(&mut bytes)- .with_context(|| format!("read {}", path.display()))?;- serde_json::from_slice(&bytes).with_context(|| format!("parse {}", path.display()))-}--fn write_json_atomic<T: Serialize>(path: &Path, value: &T) -> Result<()> {- let bytes = serde_json::to_vec_pretty(value).context("serialize Note metadata")?;- write_bytes_atomic(path, &bytes)-}-fn write_bytes_atomic(path: &Path, bytes: &[u8]) -> Result<()> {let parent = path.parent().context("Note path has no parent")?;fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;+ let existing_permissions = fs::metadata(path)+ .ok()+ .map(|metadata| metadata.permissions());let mut temporary = NamedTempFile::new_in(parent).with_context(|| format!("create temporary file in {}", parent.display()))?;temporary@@ -338,37 +335,74 @@ fn write_bytes_atomic(path: &Path, bytes: &[u8]) -> Result<()> {temporary.persist(path).with_context(|| format!("replace {}", path.display()))?;- set_private_permissions(path);+ set_user_document_permissions(path, existing_permissions);Ok(())}#[cfg(unix)]-fn set_private_permissions(path: &Path) {+fn set_user_document_permissions(path: &Path, permissions: Option<fs::Permissions>) {use std::os::unix::fs::PermissionsExt;- if let Err(err) = fs::set_permissions(path, fs::Permissions::from_mode(0o600)) {+ let permissions = permissions.unwrap_or_else(|| fs::Permissions::from_mode(0o644));+ if let Err(err) = fs::set_permissions(path, permissions) {log::warn!(- "failed to set private Note permissions on {}: {err:#}",+ "failed to preserve Note permissions on {}: {err:#}",path.display());}}#[cfg(not(unix))]-fn set_private_permissions(_path: &Path) {}+fn set_user_document_permissions(_path: &Path, _permissions: Option<fs::Permissions>) {}#[cfg(test)]mod tests {use super::*;#[test]- fn creates_and_reopens_stable_default_notebook() {+ fn creates_and_reuses_a_vault_document_session() {+ let temp = tempfile::tempdir().unwrap();+ let first = open_vault_document(temp.path(), "Design/Overview.md", true).unwrap();+ let second = open_vault_document(temp.path(), "Design/Overview.md", false).unwrap();+ assert!(Arc::ptr_eq(&first.session, &second.session));+ assert_eq!(second.relative_path, "Design/Overview.md");+ assert!(second.document_path.ends_with("Design/Overview.md"));+ }++ #[test]+ fn concurrent_open_keeps_one_canonical_document_session() {+ let temp = tempfile::tempdir().unwrap();+ fs::write(+ temp.path().join("Large.md"),+ "paragraph\n".repeat(64 * 1024),+ )+ .unwrap();+ let root = Arc::new(temp.path().to_path_buf());+ let barrier = Arc::new(std::sync::Barrier::new(3));+ let open = |root: Arc<PathBuf>, barrier: Arc<std::sync::Barrier>| {+ std::thread::spawn(move || {+ barrier.wait();+ open_vault_document(&root, "Large.md", false).unwrap()+ })+ };+ let first = open(Arc::clone(&root), Arc::clone(&barrier));+ let second = open(root, Arc::clone(&barrier));+ barrier.wait();+ let first = first.join().unwrap();+ let second = second.join().unwrap();+ assert!(Arc::ptr_eq(&first.session, &second.session));+ }++ #[test]+ fn vault_file_index_includes_attachments_but_markdown_index_does_not() {let temp = tempfile::tempdir().unwrap();- let first = ensure_default_notebook_at(temp.path()).unwrap();- first.session.lock().source();- let second = ensure_default_notebook_at(temp.path()).unwrap();- assert_eq!(first.notebook_id, second.notebook_id);- assert_eq!(first.document_id, second.document_id);- assert!(second.document_path.ends_with("Inbox.md"));+ fs::create_dir_all(temp.path().join("assets")).unwrap();+ fs::write(temp.path().join("Note.md"), "# Note").unwrap();+ fs::write(temp.path().join("assets/manual.pdf"), b"pdf").unwrap();+ assert_eq!(+ vault_file_paths(temp.path()).unwrap(),+ vec!["assets/manual.pdf", "Note.md"]+ );+ assert_eq!(vault_markdown_paths(temp.path()).unwrap(), vec!["Note.md"]);}#[test]@@ -376,14 +410,13 @@ mod tests {let temp = tempfile::tempdir().unwrap();let source = temp.path().join("My image.PNG");fs::write(&source, b"not decoded by the store").unwrap();- let store_root = temp.path().join("store");- let notebook = ensure_default_notebook_at(&store_root).unwrap();+ let document = open_vault_document(temp.path(), "Notes/Today.md", true).unwrap();assert_eq!(- import_attachment(¬ebook, &source).unwrap(),+ import_attachment(&document, &source).unwrap(),"attachments/my-image.png");assert_eq!(- import_attachment(¬ebook, &source).unwrap(),+ import_attachment(&document, &source).unwrap(),"attachments/my-image-2.png");}@@ -391,13 +424,12 @@ mod tests {#[test]fn local_image_resolution_rejects_escape() {let temp = tempfile::tempdir().unwrap();- let store_root = temp.path().join("store");- let notebook = ensure_default_notebook_at(&store_root).unwrap();+ let document = open_vault_document(temp.path(), "Today.md", true).unwrap();let outside = temp.path().join("outside.png");fs::write(&outside, b"x").unwrap();assert!(resolve_local_image(- ¬ebook.content_root,- ¬ebook.document_path,+ &document.vault_root,+ &document.document_path,"../../../outside.png").is_err());diff --git a/wezterm-gui/src/markdown_editor/surface.rs b/wezterm-gui/src/markdown_editor/surface.rsindex 7454c3ed..b1e99c0e 100644--- a/wezterm-gui/src/markdown_editor/surface.rs+++ b/wezterm-gui/src/markdown_editor/surface.rs@@ -1,11 +1,15 @@-use super::projection::ProjectedText;use super::{BlockKind, EditorMode, InlineStyle, MarkdownProjection, ProjectedObject};+use std::collections::HashMap;+use std::hash::{DefaultHasher, Hash, Hasher};use std::ops::Range;+use std::path::Path;+use std::sync::Arc;+use unicode_linebreak::linebreaks;use unicode_segmentation::UnicodeSegmentation;#[cfg(test)]use unicode_width::UnicodeWidthStr;-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]pub(crate) enum VisualLineKind {Text,Rule,@@ -17,7 +21,7 @@ pub(crate) enum VisualLineKind {#[derive(Debug, Clone, PartialEq, Eq)]pub(crate) struct VisualRun {pub source: Range<usize>,- pub text: String,+ pub text: Arc<String>,pub style: InlineStyle,pub atomic: bool,}@@ -27,10 +31,17 @@ pub(crate) struct VisualLine {pub source: Range<usize>,pub block: BlockKind,pub kind: VisualLineKind,+ /// Pixel indent applied by the host to wrapped continuation rows. Stored+ /// as bits so visual documents retain exact Eq/cache semantics.+ pub continuation_indent_bits: u32,pub runs: Vec<VisualRun>,}impl VisualLine {+ pub(crate) fn continuation_indent(&self) -> f32 {+ f32::from_bits(self.continuation_indent_bits)+ }+#[cfg(test)]pub(crate) fn text(&self) -> String {self.runs.iter().map(|run| run.text.as_str()).collect()@@ -85,7 +96,7 @@ pub(crate) fn wrap_visual_document(VisualRun {source: run.source.start + relative..run.source.start + relative + grapheme.len(),- text: grapheme.to_string(),+ text: Arc::new(grapheme.to_string()),style: run.style,atomic: false,},@@ -102,68 +113,197 @@ pub(crate) fn wrap_visual_document(/// Soft-wrap using the actual rendered width supplied by the host. Keeping/// measurement outside this module lets each host use its own font stack while/// every resulting run retains exact Markdown source byte ranges.+#[cfg(test)]pub(crate) fn wrap_visual_document_by_width<E, F>(document: &VisualDocument,max_width: f32,mut measure: F,) -> Result<VisualDocument, E>where- F: FnMut(BlockKind, &VisualRun) -> Result<f32, E>,+ F: FnMut(BlockKind, InlineStyle, &str) -> Result<f32, E>,{let max_width = max_width.max(1.0);let mut lines = Vec::with_capacity(document.lines.len());for line in &document.lines {- if line.runs.is_empty()- || matches!(line.block, BlockKind::CodeBlock | BlockKind::Table)- || matches!(line.kind, VisualLineKind::Rule | VisualLineKind::Image)- {- lines.push(line.clone());- continue;+ wrap_visual_line_by_width(line, max_width, &mut measure, &mut lines)?;+ }+ Ok(VisualDocument { lines })+}++/// Reuse the wrapped output of unchanged visual lines across document+/// revisions. Compact, line-relative hashes avoid retaining another copy of a+/// large note while still allowing edits above a line to shift its byte ranges+/// without forcing its text to be measured and wrapped again.+pub(crate) fn wrap_visual_document_by_width_cached<E, F>(+ document: &VisualDocument,+ max_width: f32,+ wrap_key: usize,+ cache: &mut VisualWrapCache,+ mut measure: F,+) -> Result<Arc<VisualDocument>, E>+where+ F: FnMut(BlockKind, InlineStyle, &str) -> Result<f32, E>,+{+ if cache.wrap_key != Some(wrap_key) {+ *cache = VisualWrapCache {+ wrap_key: Some(wrap_key),+ ..VisualWrapCache::default()+ };+ }++ let max_width = max_width.max(1.0);+ let mut lines = Vec::with_capacity(document.lines.len());+ let mut wrapped_line_ranges = Vec::with_capacity(document.lines.len());+ let mut source_line_hashes = Vec::with_capacity(document.lines.len());+ for (line_index, line) in document.lines.iter().enumerate() {+ let wrapped_start = lines.len();+ let hash = normalized_visual_line_hash(line);+ source_line_hashes.push(hash);+ // Ordinary typing does not add/remove physical rows. Try the same+ // index first and avoid hashing the entire document on every key.+ let reused_index = cache+ .source_line_hashes+ .get(line_index)+ .filter(|old_hash| **old_hash == hash)+ .map(|_| line_index)+ .or_else(|| {+ cache+ .source_line_lookup+ .get(&hash)+ .and_then(|indices| indices.first().copied())+ });+ let reused = reused_index.and_then(|index| {+ let old_source_start = *cache.source_line_starts.get(index)?;+ let wrapped = cache.wrapped_line_ranges.get(index)?.clone();+ Some((old_source_start, wrapped))+ });++ if let Some((old_source_start, wrapped_range)) = reused {+ for wrapped in &cache.wrapped.lines[wrapped_range] {+ lines.push(shift_visual_line(+ wrapped,+ old_source_start,+ line.source.start,+ ));+ }+ } else {+ wrap_visual_line_by_width(line, max_width, &mut measure, &mut lines)?;}+ wrapped_line_ranges.push(wrapped_start..lines.len());+ }- let mut current = empty_visual_line(line, line.source.start);- let mut width = 0.0f32;- for run in &line.runs {- let source_matches_text =- !run.atomic && run.source.end.saturating_sub(run.source.start) == run.text.len();- let pieces = if source_matches_text {- run.text- .split_word_bound_indices()- .map(|(relative, text)| VisualRun {- source: run.source.start + relative- ..run.source.start + relative + text.len(),- text: text.to_string(),- style: run.style,- atomic: false,- })- .collect::<Vec<_>>()- } else {- vec![run.clone()]- };-- for piece in pieces {- let piece_width = measure(line.block, &piece)?.max(0.0);- let whitespace = piece.text.chars().all(char::is_whitespace);- if !piece.atomic && !whitespace && piece_width > max_width {- for (relative, grapheme) in piece.text.grapheme_indices(true) {- let grapheme_run = VisualRun {- source: piece.source.start + relative- ..piece.source.start + relative + grapheme.len(),- text: grapheme.to_string(),- style: piece.style,- atomic: false,- };- let grapheme_width = measure(line.block, &grapheme_run)?.max(0.0);- if visual_line_has_non_whitespace(¤t)+ let wrapped = Arc::new(VisualDocument { lines });+ let source_line_starts = document+ .lines+ .iter()+ .map(|line| line.source.start)+ .collect::<Vec<_>>();+ let estimated_bytes = source_line_hashes+ .capacity()+ .saturating_mul(std::mem::size_of::<u64>())+ .saturating_add(+ source_line_starts+ .capacity()+ .saturating_mul(std::mem::size_of::<usize>()),+ )+ .saturating_add(+ wrapped_line_ranges+ .capacity()+ .saturating_mul(std::mem::size_of::<Range<usize>>()),+ )+ .saturating_add(+ source_line_hashes+ .len()+ .saturating_mul(std::mem::size_of::<(u64, usize)>()),+ );+ const WRAP_CACHE_MAX_BYTES: usize = 32 * 1024 * 1024;+ if estimated_bytes <= WRAP_CACHE_MAX_BYTES {+ cache.source_line_hashes = source_line_hashes;+ cache.source_line_starts = source_line_starts;+ cache.wrapped = Arc::clone(&wrapped);+ cache.wrapped_line_ranges = wrapped_line_ranges;+ cache.source_line_lookup.clear();+ for (index, hash) in cache.source_line_hashes.iter().copied().enumerate() {+ cache+ .source_line_lookup+ .entry(hash)+ .or_default()+ .push(index);+ }+ } else {+ // Keep the current wrapped document in the host, but bound the+ // cross-revision metadata retained solely for reuse.+ cache.source_line_hashes.clear();+ cache.source_line_starts.clear();+ cache.wrapped = Arc::new(VisualDocument::default());+ cache.wrapped_line_ranges.clear();+ cache.source_line_lookup.clear();+ }+ Ok(wrapped)+}++fn wrap_visual_line_by_width<E, F>(+ line: &VisualLine,+ max_width: f32,+ measure: &mut F,+ lines: &mut Vec<VisualLine>,+) -> Result<(), E>+where+ F: FnMut(BlockKind, InlineStyle, &str) -> Result<f32, E>,+{+ if line.runs.is_empty()+ || matches!(line.block, BlockKind::CodeBlock | BlockKind::Table)+ || matches!(line.kind, VisualLineKind::Rule | VisualLineKind::Image)+ {+ lines.push(line.clone());+ return Ok(());+ }++ let hanging_indent = if let Some(prefix) = continuation_prefix(line) {+ Some(measure(line.block, InlineStyle::default(), &prefix)?.max(0.0))+ } else {+ None+ };+ let mut current = empty_visual_line(line, line.source.start);+ let mut width = 0.0f32;+ for run in &line.runs {+ let break_anywhere = run.style.link && looks_like_external_url(&run.text);+ let source_matches_text =+ !run.atomic && run.source.end.saturating_sub(run.source.start) == run.text.len();+ if source_matches_text {+ let mut relative = 0usize;+ for (piece_end, _) in linebreaks(&run.text) {+ let piece = &run.text[relative..piece_end];+ let piece_source =+ run.source.start + relative..run.source.start + relative + piece.len();+ let piece_width = measure(line.block, run.style, piece)?.max(0.0);+ let whitespace = piece.chars().all(char::is_whitespace);+ if !whitespace+ && (piece_width > max_width+ || (break_anywhere+ && visual_line_has_non_whitespace(¤t)+ && width + piece_width > max_width))+ {+ for (grapheme_relative, grapheme) in piece.grapheme_indices(true) {+ let grapheme_source = piece_source.start + grapheme_relative+ ..piece_source.start + grapheme_relative + grapheme.len();+ let grapheme_width = measure(line.block, run.style, grapheme)?.max(0.0);+ let grapheme_is_whitespace = grapheme.chars().all(char::is_whitespace);+ if !grapheme_is_whitespace+ && visual_line_has_non_whitespace(¤t)&& width + grapheme_width > max_width{lines.push(current);- current = empty_visual_line(line, grapheme_run.source.start);- width = 0.0;+ (current, width) = continuation_visual_line(+ line,+ grapheme_source.start,+ hanging_indent.as_ref(),+ );}- append_run(&mut current, grapheme_run);+ append_text_run(&mut current, grapheme_source, grapheme, run.style, false);width += grapheme_width;}+ relative = piece_end;continue;}@@ -172,17 +312,175 @@ where&& width + piece_width > max_width{lines.push(current);- current = empty_visual_line(line, piece.source.start);- width = 0.0;+ (current, width) =+ continuation_visual_line(line, piece_source.start, hanging_indent.as_ref());}- append_run(&mut current, piece);+ append_text_run(&mut current, piece_source, piece, run.style, false);width += piece_width;+ relative = piece_end;}+ continue;}- current.source.end = current.source.end.max(line.source.end);- lines.push(current);++ let piece_width = measure(line.block, run.style, &run.text)?.max(0.0);+ let whitespace = run.text.chars().all(char::is_whitespace);+ if !whitespace+ && (piece_width > max_width+ || (break_anywhere+ && visual_line_has_non_whitespace(¤t)+ && width + piece_width > max_width))+ {+ for (relative, grapheme) in run.text.grapheme_indices(true) {+ let grapheme_source = if run.atomic {+ run.source.clone()+ } else {+ run.source.start + relative..run.source.start + relative + grapheme.len()+ };+ let grapheme_width = measure(line.block, run.style, grapheme)?.max(0.0);+ let grapheme_is_whitespace = grapheme.chars().all(char::is_whitespace);+ if !grapheme_is_whitespace+ && visual_line_has_non_whitespace(¤t)+ && width + grapheme_width > max_width+ {+ lines.push(current);+ (current, width) = continuation_visual_line(+ line,+ grapheme_source.start,+ hanging_indent.as_ref(),+ );+ }+ append_text_run(+ &mut current,+ grapheme_source,+ grapheme,+ run.style,+ run.atomic,+ );+ width += grapheme_width;+ }+ continue;+ }++ if !whitespace+ && visual_line_has_non_whitespace(¤t)+ && width + piece_width > max_width+ {+ lines.push(current);+ (current, width) =+ continuation_visual_line(line, run.source.start, hanging_indent.as_ref());+ }+ append_text_run(+ &mut current,+ run.source.clone(),+ &run.text,+ run.style,+ run.atomic,+ );+ width += piece_width;+ }+ current.source.end = current.source.end.max(line.source.end);+ lines.push(current);+ Ok(())+}++fn looks_like_external_url(text: &str) -> bool {+ let text = text.trim_start();+ text.starts_with("https://") || text.starts_with("http://")+}++fn continuation_prefix(line: &VisualLine) -> Option<String> {+ if line.block == BlockKind::Properties {+ return line+ .runs+ .first()+ .filter(|run| run.atomic && run.style.strong)+ .map(|run| run.text.as_str().to_string());+ }++ let mut prefix = String::new();+ for run in &line.runs {+ let text = run.text.as_str();+ let trimmed = text.trim_end();+ let is_task = matches!(trimmed, "☐" | "☑");+ let is_bullet = trimmed == "•";+ let is_ordered = trimmed+ .strip_suffix('.')+ .or_else(|| trimmed.strip_suffix(')'))+ .is_some_and(|digits| {+ !digits.is_empty() && digits.chars().all(|ch| ch.is_ascii_digit())+ });+ if !run.atomic || !(is_task || is_bullet || is_ordered) || !text.ends_with(' ') {+ break;+ }+ prefix.push_str(text);+ }+ (!prefix.is_empty()).then_some(prefix)+}++fn continuation_visual_line(+ template: &VisualLine,+ source_start: usize,+ hanging_indent: Option<&f32>,+) -> (VisualLine, f32) {+ let mut line = empty_visual_line(template, source_start);+ let Some(width) = hanging_indent else {+ return (line, 0.0);+ };+ line.continuation_indent_bits = width.to_bits();+ (line, *width)+}++fn normalized_visual_line_hash(line: &VisualLine) -> u64 {+ let mut hasher = DefaultHasher::new();+ line.block.hash(&mut hasher);+ line.kind.hash(&mut hasher);+ line.continuation_indent_bits.hash(&mut hasher);+ line.source+ .end+ .saturating_sub(line.source.start)+ .hash(&mut hasher);+ for run in &line.runs {+ run.source+ .start+ .saturating_sub(line.source.start)+ .hash(&mut hasher);+ run.source+ .end+ .saturating_sub(line.source.start)+ .hash(&mut hasher);+ run.text.hash(&mut hasher);+ run.style.hash(&mut hasher);+ run.atomic.hash(&mut hasher);+ }+ hasher.finish()+}++fn shift_visual_line(line: &VisualLine, old_start: usize, new_start: usize) -> VisualLine {+ let shift = |range: &Range<usize>| {+ if new_start >= old_start {+ let delta = new_start - old_start;+ range.start.saturating_add(delta)..range.end.saturating_add(delta)+ } else {+ let delta = old_start - new_start;+ range.start.saturating_sub(delta)..range.end.saturating_sub(delta)+ }+ };+ VisualLine {+ source: shift(&line.source),+ block: line.block,+ kind: line.kind,+ continuation_indent_bits: line.continuation_indent_bits,+ runs: line+ .runs+ .iter()+ .map(|run| VisualRun {+ source: shift(&run.source),+ text: run.text.clone(),+ style: run.style,+ atomic: run.atomic,+ })+ .collect(),}- Ok(VisualDocument { lines })}fn visual_line_has_non_whitespace(line: &VisualLine) -> bool {@@ -239,6 +537,7 @@ fn empty_visual_line(template: &VisualLine, source_start: usize) -> VisualLine {source: source_start..source_start,block: template.block,kind: template.kind,+ continuation_indent_bits: 0.0f32.to_bits(),runs: vec![],}}@@ -248,6 +547,32 @@ pub(crate) struct VisualDocument {pub lines: Vec<VisualLine>,}+impl VisualDocument {+ /// Approximate the amount of text that needs soft wrapping. Code, tables,+ /// rules, and images are laid out by their component painters and do not+ /// contribute to the expensive proportional-font wrap pass.+ pub(crate) fn estimated_wrap_work_bytes(&self) -> usize {+ self.lines+ .iter()+ .filter(|line| {+ !matches!(line.block, BlockKind::CodeBlock | BlockKind::Table)+ && !matches!(line.kind, VisualLineKind::Rule | VisualLineKind::Image)+ })+ .flat_map(|line| &line.runs)+ .fold(0usize, |total, run| total.saturating_add(run.text.len()))+ }+}++#[derive(Debug, Default)]+pub(crate) struct VisualWrapCache {+ wrap_key: Option<usize>,+ source_line_hashes: Vec<u64>,+ source_line_starts: Vec<usize>,+ wrapped: Arc<VisualDocument>,+ wrapped_line_ranges: Vec<Range<usize>>,+ source_line_lookup: HashMap<u64, Vec<usize>>,+}+pub(crate) fn build_visual_document(source: &str,projection: &MarkdownProjection,@@ -265,11 +590,14 @@ pub(crate) fn build_visual_document((range.start, range.end)});let mut object_index = 0usize;+ let mut visible_index = 0usize;+ let mut projected_index = 0usize;let mut lines = vec![];let mut line = VisualLine {source: 0..0,block: BlockKind::Paragraph,kind: VisualLineKind::Text,+ continuation_indent_bits: 0.0f32.to_bits(),runs: vec![],};let mut idx = 0usize;@@ -281,6 +609,26 @@ pub(crate) fn build_visual_document(if let Some(object) = objects.get(object_index) {let range = object.source();if range.start == idx && range.end > range.start {+ if range.start <= caret+ && caret <= range.end+ && matches!(+ object,+ ProjectedObject::WikiLink { .. }+ | ProjectedObject::Callout { .. }+ | ProjectedObject::BlockId { .. }+ )+ {+ append_revealed_source_range(+ &mut lines,+ &mut line,+ source,+ &range,+ BlockKind::Paragraph,+ );+ idx = range.end.min(source.len());+ object_index += 1;+ continue;+ }match object {ProjectedObject::TaskCheckbox {source: object_source,@@ -290,7 +638,7 @@ pub(crate) fn build_visual_document(&mut line,VisualRun {source: object_source.clone(),- text: if *checked { "☑ " } else { "☐ " }.to_string(),+ text: Arc::new(if *checked { "☑ " } else { "☐ " }.to_string()),style: InlineStyle::default(),atomic: true,},@@ -304,7 +652,7 @@ pub(crate) fn build_visual_document(&mut line,VisualRun {source: object_source.clone(),- text: text.clone(),+ text: Arc::new(text.clone()),style: InlineStyle::default(),atomic: true,},@@ -318,6 +666,7 @@ pub(crate) fn build_visual_document(source: object_source.clone(),block: BlockKind::Other,kind: VisualLineKind::Rule,+ continuation_indent_bits: 0.0f32.to_bits(),runs: vec![],});}@@ -333,9 +682,10 @@ pub(crate) fn build_visual_document(source: object_source.clone(),block: BlockKind::Paragraph,kind: VisualLineKind::Image,+ continuation_indent_bits: 0.0f32.to_bits(),runs: vec![VisualRun {source: object_source.clone(),- text: format!("▧ {label}"),+ text: Arc::new(format!("▧ {label}")),style: InlineStyle::default(),atomic: true,}],@@ -356,12 +706,13 @@ pub(crate) fn build_visual_document(source: content_start..text_end,block: BlockKind::CodeBlock,kind: VisualLineKind::Text,+ continuation_indent_bits: 0.0f32.to_bits(),runs: if text.is_empty() {vec![]} else {vec![VisualRun {source: content_start..text_end,- text: text.to_string(),+ text: Arc::new(text.to_string()),style: InlineStyle {code: true,..InlineStyle::default()@@ -380,7 +731,7 @@ pub(crate) fn build_visual_document(for cell in row {runs.push(VisualRun {source: cell.source.clone(),- text: cell.text.clone(),+ text: Arc::new(cell.text.clone()),style: InlineStyle {strong: row_index == 0,..InlineStyle::default()@@ -403,10 +754,168 @@ pub(crate) fn build_visual_document(} else {VisualLineKind::TableRow},+ continuation_indent_bits: 0.0f32.to_bits(),runs,});}}+ ProjectedObject::Frontmatter {+ source: object_source,+ fields,+ } => {+ flush_line_if_content(&mut lines, &mut line, idx);+ if fields.is_empty() {+ lines.push(VisualLine {+ source: object_source.clone(),+ block: BlockKind::Properties,+ kind: VisualLineKind::Text,+ continuation_indent_bits: 0.0f32.to_bits(),+ runs: vec![VisualRun {+ source: object_source.clone(),+ text: Arc::new("Properties".to_string()),+ style: InlineStyle {+ strong: true,+ ..InlineStyle::default()+ },+ atomic: true,+ }],+ });+ } else {+ for field in fields {+ lines.push(VisualLine {+ source: field.source.clone(),+ block: BlockKind::Properties,+ kind: VisualLineKind::Text,+ continuation_indent_bits: 0.0f32.to_bits(),+ runs: vec![+ VisualRun {+ source: field.key_source.clone(),+ text: Arc::new(format!("{}: ", field.key)),+ style: InlineStyle {+ strong: true,+ ..InlineStyle::default()+ },+ atomic: true,+ },+ VisualRun {+ source: field.value_source.clone(),+ text: Arc::new(field.value.clone()),+ style: InlineStyle::default(),+ atomic: true,+ },+ ],+ });+ }+ }+ }+ ProjectedObject::WikiLink {+ source: object_source,+ label,+ embed,+ resolved_path,+ rendered_lines,+ ..+ } => {+ if *embed {+ flush_line_if_content(&mut lines, &mut line, idx);+ let is_image = resolved_path.as_deref().is_some_and(|path| {+ Path::new(path)+ .extension()+ .and_then(|extension| extension.to_str())+ .is_some_and(|extension| {+ matches!(+ extension.to_ascii_lowercase().as_str(),+ "png"+ | "jpg"+ | "jpeg"+ | "gif"+ | "webp"+ | "bmp"+ | "ico"+ | "tif"+ | "tiff"+ )+ })+ });+ let embedded = if rendered_lines.is_empty() {+ vec![format!("▧ {label}")]+ } else {+ rendered_lines.clone()+ };+ for text in embedded {+ lines.push(VisualLine {+ source: object_source.clone(),+ block: BlockKind::Embed,+ kind: if is_image {+ VisualLineKind::Image+ } else {+ VisualLineKind::Text+ },+ continuation_indent_bits: 0.0f32.to_bits(),+ runs: vec![VisualRun {+ source: object_source.clone(),+ text: Arc::new(text),+ style: InlineStyle::default(),+ atomic: true,+ }],+ });+ }+ } else {+ append_run(+ &mut line,+ VisualRun {+ source: object_source.clone(),+ text: Arc::new(label.clone()),+ style: InlineStyle {+ link: true,+ ..InlineStyle::default()+ },+ atomic: true,+ },+ );+ }+ }+ ProjectedObject::Callout {+ source: object_source,+ kind,+ title,+ body,+ } => {+ flush_line_if_content(&mut lines, &mut line, idx);+ lines.push(VisualLine {+ source: object_source.clone(),+ block: BlockKind::Callout,+ kind: VisualLineKind::Text,+ continuation_indent_bits: 0.0f32.to_bits(),+ runs: vec![VisualRun {+ source: object_source.clone(),+ text: Arc::new(format!("◆ {kind} {title}")),+ style: InlineStyle {+ strong: true,+ ..InlineStyle::default()+ },+ atomic: true,+ }],+ });+ for (body_source, text) in body {+ lines.push(VisualLine {+ source: body_source.clone(),+ block: BlockKind::Callout,+ kind: VisualLineKind::Text,+ continuation_indent_bits: 0.0f32.to_bits(),+ runs: vec![VisualRun {+ source: body_source.clone(),+ text: Arc::new(text.clone()),+ style: InlineStyle::default(),+ atomic: true,+ }],+ });+ }+ }+ ProjectedObject::BlockId { .. } => {+ // Obsidian block IDs are anchors, not prose. Live+ // Preview hides them until the caret enters the token.+ }}idx = range.end.min(source.len());if matches!(object, ProjectedObject::CodeBlock(_))@@ -419,28 +928,75 @@ pub(crate) fn build_visual_document(}}- let ch = source[idx..].chars().next().expect("valid source char");- let next = idx + ch.len_utf8();- if ch == '\n' {+ if source.as_bytes()[idx] == b'\n' {+ let next = idx + 1;flush_line(&mut lines, &mut line, next);idx = next;continue;}- if range_contains(&visible, idx) {- let projected = projected_text_at(projection, idx);- let style = projected.map(|span| span.style).unwrap_or_default();- line.block = projected.map(|span| span.block).unwrap_or(line.block);- append_run(- &mut line,- VisualRun {- source: idx..next,- text: ch.to_string(),- style,- atomic: false,- },- );++ while visible_index < visible.len() && visible[visible_index].end <= idx {+ visible_index += 1;+ }+ let Some(visible_range) = visible.get(visible_index) else {+ // There can still be line breaks after the final rendered range;+ // preserve them so source positions and empty lines stay exact.+ idx = next_visual_boundary(source, idx, source.len(), objects.get(object_index));+ continue;+ };+ if idx < visible_range.start {+ idx = next_visual_boundary(source, idx, visible_range.start, objects.get(object_index));+ continue;+ }++ while projected_index < projection.text.len()+ && projection.text[projected_index].source.end <= idx+ {+ projected_index += 1;+ }+ let projected = projection+ .text+ .get(projected_index)+ .filter(|span| span.source.start <= idx && idx < span.source.end);+ let style = projected.map(|span| span.style).unwrap_or_default();+ line.block = projected.map(|span| span.block).unwrap_or(line.block);++ // Append a whole contiguous source slice with the same visibility and+ // style. The previous implementation allocated one String and ran two+ // binary searches for every Unicode scalar, which made large Notes+ // visibly rebuild on each edit.+ let mut end = visible_range.end.min(source.len());+ if let Some(span) = projected {+ end = end.min(span.source.end);+ } else if let Some(span) = projection.text.get(projected_index) {+ if span.source.start > idx {+ end = end.min(span.source.start);+ }+ }+ if let Some(object) = objects.get(object_index) {+ let object_start = object.source().start;+ if object_start > idx {+ end = end.min(object_start);+ }+ }+ if let Some(relative) = source[idx..end].find('\n') {+ end = idx + relative;}- idx = next;+ if end == idx {+ // Zero-length parser events must never stall the visual scanner.+ let ch = source[idx..].chars().next().expect("valid source char");+ end = idx + ch.len_utf8();+ }+ append_run(+ &mut line,+ VisualRun {+ source: idx..end,+ text: Arc::new(source[idx..end].to_string()),+ style,+ atomic: false,+ },+ );+ idx = end;}flush_line(&mut lines, &mut line, source.len());if lines.is_empty() {@@ -448,20 +1004,36 @@ pub(crate) fn build_visual_document(source: 0..0,block: BlockKind::Paragraph,kind: VisualLineKind::Text,+ continuation_indent_bits: 0.0f32.to_bits(),runs: vec![],});}VisualDocument { lines }}-fn projected_text_at(projection: &MarkdownProjection, byte: usize) -> Option<&ProjectedText> {- let index = projection- .text- .partition_point(|span| span.source.end <= byte);- projection- .text- .get(index)- .filter(|span| span.source.start <= byte && byte < span.source.end)+fn next_visual_boundary(+ source: &str,+ idx: usize,+ limit: usize,+ object: Option<&&ProjectedObject>,+) -> usize {+ let mut end = limit.min(source.len());+ if let Some(object) = object {+ let object_start = object.source().start;+ if object_start > idx {+ end = end.min(object_start);+ }+ }+ if let Some(relative) = source[idx..end].find('\n') {+ return idx + relative;+ }+ end.max(+ idx + source[idx..]+ .chars()+ .next()+ .map(char::len_utf8)+ .unwrap_or(0),+ )}fn source_document(source: &str) -> VisualDocument {@@ -474,12 +1046,13 @@ fn source_document(source: &str) -> VisualDocument {source: start..end,block: BlockKind::Paragraph,kind: VisualLineKind::Text,+ continuation_indent_bits: 0.0f32.to_bits(),runs: if text.is_empty() {vec![]} else {vec![VisualRun {source: start..end,- text: text.to_string(),+ text: Arc::new(text.to_string()),style: InlineStyle::default(),atomic: false,}]@@ -492,6 +1065,7 @@ fn source_document(source: &str) -> VisualDocument {source: source.len()..source.len(),block: BlockKind::Paragraph,kind: VisualLineKind::Text,+ continuation_indent_bits: 0.0f32.to_bits(),runs: vec![],});}@@ -506,7 +1080,7 @@ fn append_run(line: &mut VisualLine, run: VisualRun) {&& last.source.end == run.source.start{last.source.end = run.source.end;- last.text.push_str(&run.text);+ Arc::make_mut(&mut last.text).push_str(&run.text);line.source.end = line.source.end.max(run.source.end);return;}@@ -518,6 +1092,60 @@ fn append_run(line: &mut VisualLine, run: VisualRun) {line.runs.push(run);}+fn append_text_run(+ line: &mut VisualLine,+ source: Range<usize>,+ text: &str,+ style: InlineStyle,+ atomic: bool,+) {+ if let Some(last) = line.runs.last_mut() {+ if last.atomic && atomic && last.style == style && last.source == source {+ Arc::make_mut(&mut last.text).push_str(text);+ line.source.end = line.source.end.max(source.end);+ return;+ }+ if !last.atomic && !atomic && last.style == style && last.source.end == source.start {+ last.source.end = source.end;+ Arc::make_mut(&mut last.text).push_str(text);+ line.source.end = line.source.end.max(source.end);+ return;+ }+ }+ if line.runs.is_empty() {+ line.source.start = source.start;+ }+ line.source.end = line.source.end.max(source.end);+ line.runs.push(VisualRun {+ source,+ text: Arc::new(text.to_string()),+ style,+ atomic,+ });+}++fn append_revealed_source_range(+ lines: &mut Vec<VisualLine>,+ line: &mut VisualLine,+ source: &str,+ range: &Range<usize>,+ block: BlockKind,+) {+ let mut cursor = range.start;+ for chunk in source[range.clone()].split_inclusive('\n') {+ let text = chunk.strip_suffix('\n').unwrap_or(chunk);+ let end = cursor + text.len();+ line.block = block;+ if !text.is_empty() {+ append_text_run(line, cursor..end, text, InlineStyle::default(), false);+ }+ cursor += chunk.len();+ if chunk.ends_with('\n') {+ flush_line(lines, line, cursor);+ }+ }+}+fn flush_line(lines: &mut Vec<VisualLine>, line: &mut VisualLine, source_end: usize) {if line.runs.is_empty() && line.source.start == line.source.end {line.source = source_end..source_end;@@ -529,6 +1157,7 @@ fn flush_line(lines: &mut Vec<VisualLine>, line: &mut VisualLine, source_end: ussource: source_end..source_end,block: BlockKind::Paragraph,kind: VisualLineKind::Text,+ continuation_indent_bits: 0.0f32.to_bits(),runs: vec![],};}@@ -541,20 +1170,6 @@ fn flush_line_if_content(lines: &mut Vec<VisualLine>, line: &mut VisualLine, sou}}-fn range_contains(ranges: &[Range<usize>], byte: usize) -> bool {- ranges- .binary_search_by(|range| {- if byte < range.start {- std::cmp::Ordering::Greater- } else if byte >= range.end {- std::cmp::Ordering::Less- } else {- std::cmp::Ordering::Equal- }- })- .is_ok()-}-#[cfg(test)]mod tests {use super::*;@@ -583,6 +1198,24 @@ mod tests {assert_eq!(active.lines[0].text(), "**bold** plain");}+ #[test]+ fn live_preview_keeps_frontmatter_projected_when_caret_is_inside_it() {+ let source = "---\ntitle: Example\ntags:\n - notes\n---\n\n# Body\n";+ let projection = MarkdownProjection::parse(source);+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, 0);+ let text = doc+ .lines+ .iter()+ .map(VisualLine::text)+ .collect::<Vec<_>>()+ .join("\n");++ assert!(!text.contains("---"));+ assert!(!text.contains(" - notes"));+ assert!(text.contains("title: Example"));+ assert!(text.contains("tags:"));+ }+#[test]fn live_preview_projects_table_and_task_object() {let source = "- [x] done\n\n| A | B |\n| - | - |\n| 1 | 2 |\n";@@ -599,8 +1232,8 @@ mod tests {.find(|line| line.kind == VisualLineKind::TableRow).expect("table body row");assert_eq!(row.runs.len(), 2);- assert_eq!(row.runs[0].text, "1");- assert_eq!(row.runs[1].text, "2");+ assert_eq!(row.runs[0].text.as_str(), "1");+ assert_eq!(row.runs[1].text.as_str(), "2");}#[test]@@ -623,6 +1256,31 @@ mod tests {assert_eq!(source_mode.lines[2].text(), "```");}+ #[test]+ fn obsidian_image_embed_projects_as_an_image_component() {+ let temp = tempfile::tempdir().unwrap();+ std::fs::create_dir_all(temp.path().join("assets")).unwrap();+ std::fs::write(+ temp.path().join("assets/diagram.bmp"),+ b"decoded by the painter",+ )+ .unwrap();+ let source = "![[assets/diagram.bmp]]\n\nOutside";+ let mut projection = MarkdownProjection::parse(source);+ projection.resolve_vault_links(temp.path(), "Home.md");++ let doc = build_visual_document(+ source,+ &projection,+ EditorMode::LivePreview,+ source.find("Outside").unwrap(),+ );+ assert!(doc+ .lines+ .iter()+ .any(|line| line.kind == VisualLineKind::Image));+ }+#[test]fn soft_wrap_preserves_unicode_source_ranges() {let source = "ab你好cd";@@ -640,10 +1298,9 @@ mod tests {let source = "wide words fit";let projection = MarkdownProjection::parse(source);let doc = build_visual_document(source, &projection, EditorMode::LivePreview, 0);- let wrapped = wrap_visual_document_by_width(&doc, 8.0, |_, run| {+ let wrapped = wrap_visual_document_by_width(&doc, 8.0, |_, _, text| {Ok::<_, ()>(- run.text- .chars()+ text.chars().map(|ch| if ch == 'w' { 4.0 } else { 1.0 }).sum(),)@@ -656,6 +1313,152 @@ mod tests {assert_eq!(wrapped.lines.last().unwrap().source.end, source.len());}+ #[test]+ fn pixel_wrap_uses_hanging_indent_for_list_continuations() {+ let source = "- Alpha beta gamma";+ let projection = MarkdownProjection::parse(source);+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, source.len());+ let wrapped = wrap_visual_document_by_width(&doc, 9.0, |_, _, text| {+ Ok::<_, ()>(text.graphemes(true).count() as f32)+ })+ .unwrap();+ let lines = wrapped+ .lines+ .iter()+ .map(VisualLine::text)+ .collect::<Vec<_>>();++ assert_eq!(lines, ["• Alpha ", "beta ", "gamma"]);+ assert_eq!(wrapped.lines[0].continuation_indent(), 0.0);+ assert_eq!(wrapped.lines[1].continuation_indent(), 2.0);+ assert_eq!(wrapped.lines[2].continuation_indent(), 2.0);+ }++ #[test]+ fn pixel_wrap_uses_remaining_row_width_for_long_urls() {+ let source = "- https://example.test/a/long_resource_name.zip";+ let projection = MarkdownProjection::parse(source);+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, source.len());+ let wrapped = wrap_visual_document_by_width(&doc, 18.0, |_, _, text| {+ Ok::<_, ()>(text.graphemes(true).count() as f32)+ })+ .unwrap();++ let rows = wrapped+ .lines+ .iter()+ .map(VisualLine::text)+ .collect::<Vec<_>>();+ assert!(rows.len() > 1);+ assert_eq!(rows[0].graphemes(true).count(), 18);+ assert!(rows.iter().skip(1).all(|row| !row.starts_with('•')));+ }++ #[test]+ fn pixel_wrap_obeys_unicode_cjk_line_break_opportunities() {+ let source = "你好,世界。测试(括号)继续";+ let projection = MarkdownProjection::parse(source);+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, source.len());+ let wrapped = wrap_visual_document_by_width(&doc, 4.0, |_, _, text| {+ Ok::<_, ()>(text.graphemes(true).count() as f32)+ })+ .unwrap();+ let lines = wrapped+ .lines+ .iter()+ .map(VisualLine::text)+ .collect::<Vec<_>>();++ assert_eq!(lines.concat(), source);+ assert!(lines.iter().skip(1).all(|line| !line.starts_with(',')+ && !line.starts_with('。')+ && !line.starts_with(')')));+ assert!(lines+ .iter()+ .take(lines.len().saturating_sub(1))+ .all(|line| !line.ends_with('(')));+ }++ #[test]+ fn pixel_wrap_breaks_long_atomic_property_values() {+ let source = "---\nsource: https://example.com/a/very/long/path\n---\n";+ let projection = MarkdownProjection::parse(source);+ let doc = build_visual_document(source, &projection, EditorMode::LivePreview, 0);+ let wrapped = wrap_visual_document_by_width(&doc, 12.0, |_, _, text| {+ Ok::<_, ()>(text.graphemes(true).count() as f32)+ })+ .unwrap();++ assert!(wrapped.lines.len() > doc.lines.len());+ assert!(wrapped+ .lines+ .iter()+ .all(|line| line.text().graphemes(true).count() <= 12));+ assert!(wrapped+ .lines+ .iter()+ .filter(|line| line.block == BlockKind::Properties)+ .skip(1)+ .all(|line| line.continuation_indent() > 0.0));+ }++ #[test]+ fn cached_pixel_wrap_reuses_shifted_unchanged_lines() {+ let source = "alpha words need wrapping\nbeta content stays stable\n";+ let projection = MarkdownProjection::parse(source);+ let visual = build_visual_document(source, &projection, EditorMode::LivePreview, 0);+ let mut cache = VisualWrapCache::default();+ let mut initial_measurements = 0usize;+ wrap_visual_document_by_width_cached(&visual, 9.0, 1, &mut cache, |_, _, text| {+ initial_measurements += 1;+ Ok::<_, ()>(text.chars().count() as f32)+ })+ .unwrap();+ assert!(initial_measurements > 0);++ let shifted_source = format!("new prefix line\n{source}");+ let shifted_projection = MarkdownProjection::parse(&shifted_source);+ let shifted_visual = build_visual_document(+ &shifted_source,+ &shifted_projection,+ EditorMode::LivePreview,+ 0,+ );+ let mut cached_measurements = 0usize;+ let cached = wrap_visual_document_by_width_cached(+ &shifted_visual,+ 9.0,+ 1,+ &mut cache,+ |_, _, text| {+ cached_measurements += 1;+ Ok::<_, ()>(text.chars().count() as f32)+ },+ )+ .unwrap();+ let mut full_measurements = 0usize;+ let full = wrap_visual_document_by_width(&shifted_visual, 9.0, |_, _, text| {+ full_measurements += 1;+ Ok::<_, ()>(text.chars().count() as f32)+ })+ .unwrap();++ assert_eq!(*cached, full);+ assert!(cached_measurements < full_measurements);+ }++ #[test]+ fn wrap_work_estimate_ignores_component_layout_text() {+ let prose = "visible prose ".repeat(700);+ let source = format!("{prose}\n\n```text\n{}\n```\n", "code ".repeat(2_000));+ let projection = MarkdownProjection::parse(&source);+ let visual = build_visual_document(&source, &projection, EditorMode::LivePreview, 0);++ let estimated = visual.estimated_wrap_work_bytes();+ assert!(estimated >= prose.trim_end().len());+ assert!(estimated < source.len() / 2);+ }+#[test]fn table_column_fitting_fills_and_bounds_the_grid() {assert_eq!(fit_table_columns(&[], 100.0, 20.0), Vec::<f32>::new());diff --git a/wezterm-gui/src/shapecache.rs b/wezterm-gui/src/shapecache.rsindex 134239e7..67b3037f 100644--- a/wezterm-gui/src/shapecache.rs+++ b/wezterm-gui/src/shapecache.rs@@ -209,6 +209,7 @@ mod test {});let infos = vec![GlyphInfo {+ #[cfg(debug_assertions)]text: "a".to_string(),only_char: Some('a'),is_space: false,@@ -222,6 +223,7 @@ mod test {y_offset: PixelLength::new(0.0),},GlyphInfo {+ #[cfg(debug_assertions)]text: "你".to_string(),only_char: Some('你'),is_space: false,diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex af58ec27..e1b7f621 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -58,7 +58,7 @@ use smol::channel::Sender;use smol::Timer;use std::cell::{RefCell, RefMut};use std::collections::{HashMap, HashSet, LinkedList, VecDeque};-use std::ops::Add;+use std::ops::{Add, Range};use std::path::{Path, PathBuf};use std::rc::Rc;use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};@@ -247,6 +247,48 @@ pub enum TermWindowNotif {},}+#[derive(Clone, Debug)]+pub(crate) enum NoteEditorCommand {+ Undo,+ Redo,+ Cut,+ Copy,+ Paste,+ Delete,+ SelectAll,+ ReplaceSpelling {+ revision: u64,+ range: Range<usize>,+ replacement: String,+ },+ IgnoreSpelling {+ word: String,+ },+ LearnSpelling {+ word: String,+ },+ LookUp {+ text: String,+ anchor: Rect,+ },+ ToggleSourceMode,+ Save,+ ChooseVault {+ managed: bool,+ },+ NewNote,+ OpenNote {+ relative_path: String,+ },+ RevealVault,+ ToggleVaultTree,+}++#[derive(Clone, Debug)]+pub(crate) enum ContextMenuApplicationAction {+ Note(NoteEditorCommand),+}+#[derive(Clone, Debug, PartialEq, Eq)]pub enum UIItemType {TabBar(TabBarItem),@@ -295,8 +337,12 @@ pub enum UIItemType {RightSidebarSnippetDelete(String),RightSidebarSnippetScrollTrack,RightSidebarSnippetScrollThumb,- RightSidebarNoteModeToggle,- RightSidebarNoteSave,+ RightSidebarNoteMenu,+ RightSidebarNoteChooseVault,+ RightSidebarNoteCreateVault,+ RightSidebarNoteTreeToggle,+ RightSidebarNoteTreeBack,+ RightSidebarNoteTreeRow(String),RightSidebarNoteCodeToggle(usize),RightSidebarNoteCodeCopy(usize),RightSidebarNoteBody,@@ -330,6 +376,12 @@ pub enum RightSidebarMode {Snippets,}+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum RightSidebarNoteView {+ Tree,+ Editor,+}+#[derive(Clone, Debug, PartialEq, Eq)]pub enum RightSidebarSnippetView {List,@@ -459,6 +511,23 @@ pub(crate) struct RightSidebarFilePreviewImage {pub data: Arc<ImageData>,pub width: u32,pub height: u32,+ pub encoded_bytes: usize,+}++#[derive(Clone, Debug, PartialEq, Eq, Hash)]+pub(crate) enum RightSidebarNoteImageSource {+ Local(PathBuf),+ Remote(String),+}++#[derive(Clone, Copy, Debug)]+pub(crate) struct RightSidebarNoteTableLayout {+ pub source_start: usize,+ pub x: f32,+ pub y: f32,+ pub width: f32,+ pub height: f32,+ pub max_horizontal_scroll: f32,}#[derive(Clone, Debug)]@@ -968,6 +1037,8 @@ pub struct TermWindow {ui_items: Vec<UIItem>,context_menu: Option<ui::context_menu::ContextMenuState>,+ context_menu_application_actions: HashMap<u64, ContextMenuApplicationAction>,+ next_context_menu_application_action_id: u64,context_menu_suppressed_release: Option<MousePress>,dragging: Option<(UIItem, MouseEvent)>,// In-flight drag of a Files-panel row toward the terminal; becomes@@ -1013,15 +1084,28 @@ pub struct TermWindow {right_sidebar_snippet_scroll_offset: f32,right_sidebar_snippet_scrollbar_visible_until: Option<Instant>,right_sidebar_note: crate::markdown_editor::NoteHostState,- right_sidebar_note_images: HashMap<PathBuf, RightSidebarFilePreviewImage>,- right_sidebar_note_images_loading: HashSet<PathBuf>,- right_sidebar_note_image_order: VecDeque<PathBuf>,- right_sidebar_note_code_highlights:- HashMap<(u64, usize, bool), Arc<Vec<Vec<::window::color::LinearRgba>>>>,- right_sidebar_note_code_highlight_order: VecDeque<(u64, usize, bool)>,- right_sidebar_note_code_highlights_pending: HashSet<(u64, usize)>,- right_sidebar_note_code_highlight_revision: u64,- right_sidebar_note_code_highlight_cancel: Arc<AtomicUsize>,+ right_sidebar_note_view: RightSidebarNoteView,+ right_sidebar_note_vault_index_root: Option<PathBuf>,+ right_sidebar_note_vault_paths: Arc<Vec<String>>,+ right_sidebar_note_vault_index_generation: u64,+ right_sidebar_note_vault_indexing: bool,+ right_sidebar_note_vault_last_scan: Option<Instant>,+ right_sidebar_note_open_generation: u64,+ right_sidebar_note_opening: Option<(PathBuf, String)>,+ right_sidebar_note_open_failure: Option<((PathBuf, String), String)>,+ right_sidebar_note_tree_scroll_offset: f32,+ right_sidebar_note_tree_expanded: HashSet<String>,+ right_sidebar_note_vault_tree_collapsed: bool,+ right_sidebar_note_wide_layout: bool,+ right_sidebar_note_table_horizontal_offsets: HashMap<usize, f32>,+ right_sidebar_note_table_layouts: Vec<RightSidebarNoteTableLayout>,+ right_sidebar_note_images: HashMap<RightSidebarNoteImageSource, RightSidebarFilePreviewImage>,+ right_sidebar_note_images_loading: HashSet<RightSidebarNoteImageSource>,+ right_sidebar_note_image_order: VecDeque<RightSidebarNoteImageSource>,+ right_sidebar_note_image_failures: HashMap<RightSidebarNoteImageSource, Instant>,+ right_sidebar_note_code_highlight: ui::right_sidebar::NoteCodeHighlightState,+ right_sidebar_note_paint_cache: ui::right_sidebar::NotePaintCache,+ right_sidebar_note_memory_release_token: u64,right_sidebar_file_view: RightSidebarFileView,right_sidebar_file_focus: Option<RightSidebarFileField>,right_sidebar_file_filter: TextInputState,@@ -1269,6 +1353,9 @@ impl TermWindow {}if self.focused.is_none() {+ self.right_sidebar_note.native_text_input_snapshot_key = None;+ window.set_native_text_input_snapshot(None);+ self.right_sidebar_note.freeze_live_source();self.save_right_sidebar_note_now();self.last_mouse_click = None;self.current_mouse_buttons.clear();@@ -1605,6 +1692,8 @@ impl TermWindow {semantic_zones: HashMap::new(),ui_items: vec![],context_menu: None,+ context_menu_application_actions: HashMap::new(),+ next_context_menu_application_action_id: 1,context_menu_suppressed_release: None,dragging: None,right_sidebar_file_drag: None,@@ -1638,14 +1727,28 @@ impl TermWindow {right_sidebar_snippet_scroll_offset: 0.0,right_sidebar_snippet_scrollbar_visible_until: None,right_sidebar_note: crate::markdown_editor::NoteHostState::default(),+ right_sidebar_note_view: RightSidebarNoteView::Editor,+ right_sidebar_note_vault_index_root: None,+ right_sidebar_note_vault_paths: Arc::new(Vec::new()),+ right_sidebar_note_vault_index_generation: 0,+ right_sidebar_note_vault_indexing: false,+ right_sidebar_note_vault_last_scan: None,+ right_sidebar_note_open_generation: 0,+ right_sidebar_note_opening: None,+ right_sidebar_note_open_failure: None,+ right_sidebar_note_tree_scroll_offset: 0.0,+ right_sidebar_note_tree_expanded: HashSet::new(),+ right_sidebar_note_vault_tree_collapsed: false,+ right_sidebar_note_wide_layout: false,+ right_sidebar_note_table_horizontal_offsets: HashMap::new(),+ right_sidebar_note_table_layouts: Vec::new(),right_sidebar_note_images: HashMap::new(),right_sidebar_note_images_loading: HashSet::new(),right_sidebar_note_image_order: VecDeque::new(),- right_sidebar_note_code_highlights: HashMap::new(),- right_sidebar_note_code_highlight_order: VecDeque::new(),- right_sidebar_note_code_highlights_pending: HashSet::new(),- right_sidebar_note_code_highlight_revision: 0,- right_sidebar_note_code_highlight_cancel: Arc::new(AtomicUsize::new(0)),+ right_sidebar_note_image_failures: HashMap::new(),+ right_sidebar_note_code_highlight: ui::right_sidebar::NoteCodeHighlightState::default(),+ right_sidebar_note_paint_cache: ui::right_sidebar::NotePaintCache::default(),+ right_sidebar_note_memory_release_token: 0,right_sidebar_file_view: RightSidebarFileView::Tree,right_sidebar_file_focus: None,right_sidebar_file_filter: TextInputState::new(),@@ -1899,6 +2002,11 @@ impl TermWindow {}Ok(true)}+ WindowEvent::PerformContextMenuAction(action_id) => {+ self.perform_context_menu_application_action(action_id);+ window.invalidate();+ Ok(true)+ }WindowEvent::FocusChanged(focused) => {self.focus_changed(focused, window);Ok(true)@@ -1966,6 +2074,29 @@ impl TermWindow {window.invalidate();Ok(true)}+ WindowEvent::NativeTextInputReplace {+ token,+ revision,+ source_range,+ text,+ } => {+ if self.right_sidebar_note.view.focused+ && self.right_sidebar_note.native_text_input_token == token+ {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ if session.lock().replace_range_at_revision(+ &mut self.right_sidebar_note.view,+ revision,+ source_range,+ &text,+ ) {+ self.note_did_edit();+ }+ }+ }+ window.invalidate();+ Ok(true)+ }WindowEvent::NeedRepaint => {if self.resizes_pending > 0 {self.is_repaint_pending = true;@@ -2009,12 +2140,11 @@ impl TermWindow {if self.right_sidebar_mode == RightSidebarMode::Tasks&& self.right_sidebar_note.view.focused{- let notebook = match crate::markdown_editor::default_notebook() {- Ok(notebook) => notebook,- Err(err) => {- log::error!("failed to open Note attachment store: {err:#}");- return Ok(true);- }+ let Some(document) = self.right_sidebar_note.document.clone() else {+ log::warn!(+ "cannot import a Note attachment before a Vault document is open"+ );+ return Ok(true);};let paths = paths.clone();let notify_window = window.clone();@@ -2022,7 +2152,7 @@ impl TermWindow {let markdown = promise::spawn::spawn_into_new_thread(move || {let mut inserted = Vec::new();for path in paths {- match crate::markdown_editor::import_attachment(¬ebook, &path) {+ match crate::markdown_editor::import_attachment(&document, &path) {Ok(relative) => {let alt = path.file_stem()diff --git a/wezterm-gui/src/termwindow/mouseevent.rs b/wezterm-gui/src/termwindow/mouseevent.rsindex 0d71137a..0112cc9c 100644--- a/wezterm-gui/src/termwindow/mouseevent.rs+++ b/wezterm-gui/src/termwindow/mouseevent.rs@@ -12,8 +12,8 @@ use crate::termwindow::{TermWindowNotif, UIItem, UIItemType, TMB,};use ::window::{- ContextMenuItem, IntegratedTitleButtonStyle, MouseButtons as WMB, MouseCursor, MouseEvent,- MouseEventKind as WMEK, MousePress, WindowDecorations, WindowOps, WindowState,+ ContextMenuIcon, ContextMenuItem, IntegratedTitleButtonStyle, MouseButtons as WMB, MouseCursor,+ MouseEvent, MouseEventKind as WMEK, MousePress, WindowDecorations, WindowOps, WindowState,};use config::keyassignment::{ClipboardCopyDestination, ClipboardPasteSource, KeyAssignment, MouseEventTrigger,@@ -60,6 +60,10 @@ fn note_drag_scroll_delta(}}+fn note_horizontal_scroll_offset(current: f32, delta: f32, maximum: f32) -> f32 {+ (current + delta).clamp(0.0, maximum.max(0.0))+}+fn trailing_action_reserved_width(fixed_clearance: usize,action_button_count: usize,@@ -85,7 +89,9 @@ fn trailing_action_reserved_width(#[cfg(test)]mod window_tab_layout_tests {- use super::{note_drag_scroll_delta, trailing_action_reserved_width};+ use super::{+ note_drag_scroll_delta, note_horizontal_scroll_offset, trailing_action_reserved_width,+ };#[test]fn trailing_actions_keep_tabs_before_the_new_tab_button() {@@ -113,6 +119,14 @@ mod window_tab_layout_tests {note_drag_scroll_delta(30.0, 0.0, 200.0, 40.0, 28.0).expect("top edge delta") < 0.0);}++ #[test]+ fn note_horizontal_scroll_is_clamped_to_table_extent() {+ assert_eq!(note_horizontal_scroll_offset(20.0, 15.0, 100.0), 35.0);+ assert_eq!(note_horizontal_scroll_offset(95.0, 15.0, 100.0), 100.0);+ assert_eq!(note_horizontal_scroll_offset(5.0, -15.0, 100.0), 0.0);+ assert_eq!(note_horizontal_scroll_offset(5.0, 15.0, 0.0), 0.0);+ }}/// Overall ceiling on the "Connecting…" phase, as a backstop for the case where@@ -148,6 +162,40 @@ impl super::TermWindow {}}+ fn sidebar_vertical_scroll_delta(event: &MouseEvent) -> Option<f32> {+ if !matches!(event.kind, WMEK::VertWheel(_)) {+ return None;+ }+ if let Some(delta) = event.precise_scroll_delta {+ if delta.y.abs() > f32::EPSILON {+ return Some(-delta.y);+ }+ }+ match event.kind {+ WMEK::VertWheel(amount) if amount != 0 => Some(Self::sidebar_scroll_pixels(amount)),+ WMEK::VertWheel(_) => Some(0.0),+ _ => None,+ }+ }++ fn sidebar_horizontal_scroll_delta(event: &MouseEvent) -> Option<f32> {+ if !matches!(event.kind, WMEK::HorzWheel(_)) {+ return None;+ }+ if let Some(delta) = event.precise_scroll_delta {+ if delta.x.abs() > f32::EPSILON {+ return Some(-delta.x);+ }+ }+ match event.kind {+ WMEK::HorzWheel(amount) if amount != 0 => {+ Some(Self::sidebar_scroll_pixels(amount) * 2.0)+ }+ WMEK::HorzWheel(_) => Some(0.0),+ _ => None,+ }+ }+pub(super) fn window_tab_width_pixels(&self) -> f32 {let cell_width = self.render_metrics.cell_size.width.max(1) as f32;(self.config.tab_max_width as f32 * cell_width)@@ -620,15 +668,15 @@ impl super::TermWindow {return false;}- let amount = match event.kind {- WMEK::VertWheel(amount) => amount,+ let delta = match event.kind {+ WMEK::VertWheel(_) => Self::sidebar_vertical_scroll_delta(event).unwrap_or(0.0),// Trackpads often emit a little horizontal inertia while the user is// vertically scrolling. Consume it inside the sidebar so it doesn't// leak to tab or terminal wheel handlers at the scroll bounds.WMEK::HorzWheel(_) => return true,_ => return false,};- if amount == 0 {+ if delta.abs() <= f32::EPSILON {return true;}@@ -638,8 +686,7 @@ impl super::TermWindow {}self.show_workspace_sidebar_scrollbar();- let offset = (self.workspace_sidebar_scroll_offset + Self::sidebar_scroll_pixels(amount))- .clamp(0.0, max_offset);+ let offset = (self.workspace_sidebar_scroll_offset + delta).clamp(0.0, max_offset);if (offset - self.workspace_sidebar_scroll_offset).abs() > f32::EPSILON {self.workspace_sidebar_scroll_offset = offset;context.invalidate();@@ -649,6 +696,34 @@ impl super::TermWindow {true}+ fn scroll_right_sidebar_note_table_at(&mut self, x: f32, y: f32, delta: f32) -> bool {+ let Some(layout) = self+ .right_sidebar_note_table_layouts+ .iter()+ .rev()+ .find(|layout| {+ x >= layout.x+ && x < layout.x + layout.width+ && y >= layout.y+ && y < layout.y + layout.height+ })+ .copied()+ else {+ return false;+ };+ if layout.max_horizontal_scroll <= 0.0 {+ return false;+ }+ let offset = self+ .right_sidebar_note_table_horizontal_offsets+ .entry(layout.source_start)+ .or_default();+ let next = note_horizontal_scroll_offset(*offset, delta, layout.max_horizontal_scroll);+ let changed = (next - *offset).abs() > f32::EPSILON;+ *offset = next;+ changed+ }+fn mouse_wheel_right_sidebar(&mut self, event: &MouseEvent, context: &dyn WindowOps) -> bool {if self.right_sidebar_mode == super::RightSidebarMode::Chat {if let Some(rect) = self.right_sidebar_file_preview_rect() {@@ -660,13 +735,13 @@ impl super::TermWindow {&& y < rect.y.saturating_add(rect.height) as isize{let changed = match event.kind {- WMEK::VertWheel(amount) if amount != 0 => {- self.scroll_right_sidebar_file_preview(amount)- }+ WMEK::VertWheel(_) => self.scroll_right_sidebar_file_preview_by(+ Self::sidebar_vertical_scroll_delta(event).unwrap_or(0.0),+ ),WMEK::HorzWheel(amount) if amount != 0 => {self.scroll_right_sidebar_file_preview_horizontal(amount)}- WMEK::VertWheel(_) | WMEK::HorzWheel(_) => false,+ WMEK::HorzWheel(_) => false,_ => return false,};if changed {@@ -692,47 +767,75 @@ impl super::TermWindow {}if self.right_sidebar_mode == super::RightSidebarMode::Tasks {- if let WMEK::HorzWheel(amount) = event.kind {- if amount != 0- && self.right_sidebar_note.scroll_code_block_at(+ let shift_vertical = matches!(event.kind, WMEK::VertWheel(_))+ && event.modifiers.contains(::window::Modifiers::SHIFT);+ if matches!(event.kind, WMEK::HorzWheel(_)) || shift_vertical {+ let delta = if shift_vertical {+ Self::sidebar_vertical_scroll_delta(event).unwrap_or(0.0)+ } else {+ Self::sidebar_horizontal_scroll_delta(event).unwrap_or(0.0)+ };+ if delta.abs() > f32::EPSILON {+ let changed = self.scroll_right_sidebar_note_table_at(event.coords.x as f32,event.coords.y as f32,- Self::sidebar_scroll_pixels(amount) * 2.0,- )- {- context.invalidate();+ delta,+ ) || self.right_sidebar_note.scroll_code_block_at(+ event.coords.x as f32,+ event.coords.y as f32,+ delta,+ );+ if changed {+ context.invalidate();+ }}return true;}}- let amount = match event.kind {- WMEK::VertWheel(amount) => amount,+ let delta = match event.kind {+ WMEK::VertWheel(_) => Self::sidebar_vertical_scroll_delta(event).unwrap_or(0.0),WMEK::HorzWheel(_) => return true,_ => return false,};- if amount == 0 {+ if delta.abs() <= f32::EPSILON {return true;}match self.right_sidebar_mode {super::RightSidebarMode::Chat => {- if self.scroll_right_sidebar_files(amount) {+ if self.scroll_right_sidebar_files_by(delta) {context.invalidate();}}super::RightSidebarMode::Tasks => {- self.right_sidebar_note.reveal_caret = false;- if self- .right_sidebar_note- .scroll_by(Self::sidebar_scroll_pixels(amount))- {+ let over_tree = matches!(+ self.resolve_ui_item(event).map(|item| item.item_type),+ Some(UIItemType::RightSidebarNoteTreeRow(_))+ | Some(UIItemType::RightSidebarNoteTreeBack)+ | Some(UIItemType::RightSidebarNoteTreeToggle)+ ) || self.right_sidebar_note_view+ == crate::termwindow::RightSidebarNoteView::Tree;+ let changed = if over_tree {+ let old = self.right_sidebar_note_tree_scroll_offset;+ self.right_sidebar_note_tree_scroll_offset =+ (self.right_sidebar_note_tree_scroll_offset + delta).max(0.0);+ (old - self.right_sidebar_note_tree_scroll_offset).abs() > f32::EPSILON+ } else {+ self.right_sidebar_note.reveal_caret = false;+ self.right_sidebar_note.scroll_by(delta)+ };+ if changed {context.invalidate();}}super::RightSidebarMode::Snippets => {let was_visible = self.right_sidebar_snippet_scrollbar_visible_until;self.show_right_sidebar_snippet_scrollbar();+ let amount = match event.kind {+ WMEK::VertWheel(amount) => amount,+ _ => 0,+ };if self.scroll_right_sidebar_snippets(amount)|| was_visible != self.right_sidebar_snippet_scrollbar_visible_until{@@ -796,8 +899,12 @@ impl super::TermWindow {| UIItemType::RightSidebarSnippetDelete(_)| UIItemType::RightSidebarSnippetScrollTrack| UIItemType::RightSidebarSnippetScrollThumb- | UIItemType::RightSidebarNoteModeToggle- | UIItemType::RightSidebarNoteSave+ | UIItemType::RightSidebarNoteMenu+ | UIItemType::RightSidebarNoteChooseVault+ | UIItemType::RightSidebarNoteCreateVault+ | UIItemType::RightSidebarNoteTreeToggle+ | UIItemType::RightSidebarNoteTreeBack+ | UIItemType::RightSidebarNoteTreeRow(_)| UIItemType::RightSidebarNoteCodeToggle(_)| UIItemType::RightSidebarNoteCodeCopy(_)| UIItemType::RightSidebarNoteBody@@ -865,8 +972,12 @@ impl super::TermWindow {| UIItemType::RightSidebarSnippetDelete(_)| UIItemType::RightSidebarSnippetScrollTrack| UIItemType::RightSidebarSnippetScrollThumb- | UIItemType::RightSidebarNoteModeToggle- | UIItemType::RightSidebarNoteSave+ | UIItemType::RightSidebarNoteMenu+ | UIItemType::RightSidebarNoteChooseVault+ | UIItemType::RightSidebarNoteCreateVault+ | UIItemType::RightSidebarNoteTreeToggle+ | UIItemType::RightSidebarNoteTreeBack+ | UIItemType::RightSidebarNoteTreeRow(_)| UIItemType::RightSidebarNoteCodeToggle(_)| UIItemType::RightSidebarNoteCodeCopy(_)| UIItemType::RightSidebarNoteBody@@ -1111,6 +1222,7 @@ impl super::TermWindow {);}self.right_sidebar_note.drag_selection_active = false;+ self.right_sidebar_note.drag_selection_base = None;context.invalidate();}if completed_drag.as_ref().is_some_and(|(item, _)| {@@ -1569,8 +1681,7 @@ impl super::TermWindow {let position = self.right_sidebar_note.source_position_for_point(x as f32, y as f32);- self.right_sidebar_note.view.selection.focus = position;- self.right_sidebar_note.view.preferred_column = None;+ self.right_sidebar_note.extend_selection_to(position);self.right_sidebar_note.reveal_caret = false;self.right_sidebar_note.refresh_projection();}@@ -1984,8 +2095,12 @@ impl super::TermWindow {| UIItemType::RightSidebarSnippetDelete(_) => {self.mouse_event_right_sidebar_snippet(item.clone(), event, context);}- UIItemType::RightSidebarNoteModeToggle- | UIItemType::RightSidebarNoteSave+ UIItemType::RightSidebarNoteMenu+ | UIItemType::RightSidebarNoteChooseVault+ | UIItemType::RightSidebarNoteCreateVault+ | UIItemType::RightSidebarNoteTreeToggle+ | UIItemType::RightSidebarNoteTreeBack+ | UIItemType::RightSidebarNoteTreeRow(_)| UIItemType::RightSidebarNoteCodeToggle(_)| UIItemType::RightSidebarNoteCodeCopy(_)| UIItemType::RightSidebarNoteBody => {@@ -2038,17 +2153,48 @@ impl super::TermWindow {context: &dyn WindowOps,) {match item.item_type.clone() {- UIItemType::RightSidebarNoteModeToggle => {+ UIItemType::RightSidebarNoteMenu => {context.set_cursor(Some(MouseCursor::Hand));if event.kind == WMEK::Press(MousePress::Left) {- self.toggle_right_sidebar_note_mode();+ self.show_right_sidebar_note_menu(context, event.coords);context.invalidate();}}- UIItemType::RightSidebarNoteSave => {+ UIItemType::RightSidebarNoteChooseVault => {context.set_cursor(Some(MouseCursor::Hand));if event.kind == WMEK::Press(MousePress::Left) {- self.save_right_sidebar_note_now();+ self.perform_right_sidebar_note_command(+ crate::termwindow::NoteEditorCommand::ChooseVault { managed: false },+ );+ }+ }+ UIItemType::RightSidebarNoteCreateVault => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.perform_right_sidebar_note_command(+ crate::termwindow::NoteEditorCommand::ChooseVault { managed: true },+ );+ }+ }+ UIItemType::RightSidebarNoteTreeToggle => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.toggle_right_sidebar_note_vault_tree();+ self.right_sidebar_note.view.focused = false;+ context.invalidate();+ }+ }+ UIItemType::RightSidebarNoteTreeBack => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.right_sidebar_note_view = crate::termwindow::RightSidebarNoteView::Editor;+ context.invalidate();+ }+ }+ UIItemType::RightSidebarNoteTreeRow(relative_path) => {+ context.set_cursor(Some(MouseCursor::Hand));+ if event.kind == WMEK::Press(MousePress::Left) {+ self.activate_right_sidebar_note_tree_path(&relative_path);context.invalidate();}}@@ -2121,12 +2267,93 @@ impl super::TermWindow {}}UIItemType::RightSidebarNoteBody => {- context.set_cursor(Some(MouseCursor::Text));- if event.kind == WMEK::Press(MousePress::Left) {- if let Some(range) = self+ let external_link_target = self+ .right_sidebar_note+ .external_link_target_for_point(event.coords.x as f32, event.coords.y as f32);+ context.set_cursor(Some(if external_link_target.is_some() {+ MouseCursor::Hand+ } else {+ MouseCursor::Text+ }));+ if event.kind == WMEK::Press(MousePress::Right) {+ self.right_sidebar_note.begin_live_editing();+ let position = self.right_sidebar_note- .atomic_source_for_point(event.coords.x as f32, event.coords.y as f32)+ .source_position_for_point(event.coords.x as f32, event.coords.y as f32);+ self.right_sidebar_note.view.focused = true;+ let selected = self.right_sidebar_note.view.selection.range();+ if selected.is_empty()+ || position.byte < selected.start+ || position.byte >= selected.end{+ self.right_sidebar_note.begin_selection(+ position,+ crate::markdown_editor::SelectionGranularity::Word,+ false,+ );+ }+ self.right_sidebar_note.reveal_caret = true;+ self.right_sidebar_note.refresh_projection();+ let items = self.right_sidebar_note_context_menu_items(event.coords);+ self.show_term_context_menu(context, event.coords, items);+ context.invalidate();+ return;+ }+ if event.kind == WMEK::Press(MousePress::Left) {+ let click_streak = self+ .last_mouse_click+ .as_ref()+ .map(|click| click.streak)+ .unwrap_or(1);+ let extend = event.modifiers.contains(::window::Modifiers::SHIFT);+ if click_streak == 1 && !extend {+ if let Some(target) = external_link_target {+ wezterm_open_url::open_url(&target);+ context.invalidate();+ return;+ }+ }+ let atomic_range = self+ .right_sidebar_note+ .atomic_source_for_point(event.coords.x as f32, event.coords.y as f32);+ if let Some(range) = atomic_range.as_ref() {+ let wiki_link =+ self.right_sidebar_note+ .projection+ .objects+ .iter()+ .find_map(|object| match object {+ crate::markdown_editor::ProjectedObject::WikiLink {+ source,+ target,+ resolved_path,+ ambiguous_paths,+ ..+ } if source == range => Some((+ target.clone(),+ resolved_path.clone(),+ ambiguous_paths.clone(),+ )),+ _ => None,+ });+ if click_streak == 1 && !extend {+ if let Some((target, resolved_path, ambiguous_paths)) = wiki_link {+ if ambiguous_paths.len() > 1 {+ self.show_right_sidebar_note_wiki_link_choices(+ context,+ event.coords,+ ambiguous_paths,+ );+ } else {+ self.activate_or_create_right_sidebar_wiki_link(+ &target,+ resolved_path.as_deref(),+ );+ }+ context.invalidate();+ return;+ }+ }let replacement =self.right_sidebar_note.session@@ -2144,8 +2371,39 @@ impl super::TermWindow {}})});- if let Some(replacement) = replacement {- self.right_sidebar_note.view.focused = true;+ if click_streak == 1 && !extend {+ if let Some(replacement) = replacement {+ self.right_sidebar_note.view.focused = true;+ self.right_sidebar_note.view.selection =+ crate::markdown_editor::SourceSelection {+ anchor: crate::markdown_editor::SourcePosition::new(+ range.start,+ ),+ focus: crate::markdown_editor::SourcePosition::new(+ range.end,+ ),+ };+ self.push_right_sidebar_text(replacement);+ context.invalidate();+ return;+ }+ }+ }+ self.right_sidebar_note.begin_live_editing();+ let position = self+ .right_sidebar_note+ .source_position_for_point(event.coords.x as f32, event.coords.y as f32);+ self.right_sidebar_note.view.focused = true;+ let granularity = if click_streak >= 3 {+ crate::markdown_editor::SelectionGranularity::MarkdownBlock+ } else if click_streak == 2 {+ crate::markdown_editor::SelectionGranularity::Word+ } else {+ crate::markdown_editor::SelectionGranularity::Character+ };+ if click_streak == 2 && !extend {+ if let Some(range) = atomic_range {+ self.right_sidebar_note.selection_granularity = granularity;self.right_sidebar_note.view.selection =crate::markdown_editor::SourceSelection {anchor: crate::markdown_editor::SourcePosition::new(@@ -2153,18 +2411,15 @@ impl super::TermWindow {),focus: crate::markdown_editor::SourcePosition::new(range.end),};- self.push_right_sidebar_text(replacement);- context.invalidate();- return;+ self.right_sidebar_note.drag_selection_base = Some(range);+ } else {+ self.right_sidebar_note+ .begin_selection(position, granularity, extend);}+ } else {+ self.right_sidebar_note+ .begin_selection(position, granularity, extend);}- let position = self- .right_sidebar_note- .source_position_for_point(event.coords.x as f32, event.coords.y as f32);- self.right_sidebar_note.view.focused = true;- self.right_sidebar_note.view.selection =- crate::markdown_editor::SourceSelection::caret(position.byte);- self.right_sidebar_note.view.preferred_column = None;self.right_sidebar_note.reveal_caret = true;self.right_sidebar_note.drag_selection_active = false;self.right_sidebar_note.refresh_projection();@@ -2317,8 +2572,12 @@ impl super::TermWindow {| UIItemType::RightSidebarSnippetDelete(_) => {self.mouse_event_right_sidebar_snippet(item.clone(), event, context);}- UIItemType::RightSidebarNoteModeToggle- | UIItemType::RightSidebarNoteSave+ UIItemType::RightSidebarNoteMenu+ | UIItemType::RightSidebarNoteChooseVault+ | UIItemType::RightSidebarNoteCreateVault+ | UIItemType::RightSidebarNoteTreeToggle+ | UIItemType::RightSidebarNoteTreeBack+ | UIItemType::RightSidebarNoteTreeRow(_)| UIItemType::RightSidebarNoteCodeToggle(_)| UIItemType::RightSidebarNoteCodeCopy(_)| UIItemType::RightSidebarNoteBody => {@@ -2612,6 +2871,12 @@ impl super::TermWindow {self.clear_right_sidebar_text_focus();}self.right_sidebar_mode = mode;+ if self.right_sidebar_mode == super::RightSidebarMode::Tasks {+ self.right_sidebar_note_memory_release_token =+ self.right_sidebar_note_memory_release_token.wrapping_add(1);+ } else if previous_mode == super::RightSidebarMode::Tasks {+ self.schedule_right_sidebar_note_memory_release();+ }// Leaving the file view (e.g. switching to Snippets/Tasks) makes the// file index idle; schedule it for release. Entering it refreshes +// (re)starts the periodic re-scan.@@ -3138,8 +3403,8 @@ impl super::TermWindow {fn project_context_menu_items(&self, project_id: &str) -> Vec<ContextMenuItem> {let project_id = project_id.to_string();let mut reveal_item = ContextMenuItem::item_with_icon(- "Reveal in Folder",- "folder",+ crate::termwindow::ui::context_menu::reveal_in_folder_label(),+ ContextMenuIcon::Folder,KeyAssignment::RevealProjectInFolder(project_id.clone()),);if crate::workspace_threads::project_reveal_path(&project_id).is_none() {@@ -3149,24 +3414,24 @@ impl super::TermWindow {vec![ContextMenuItem::item_with_icon("Rename Workspace...",- "pencil",+ ContextMenuIcon::Edit,KeyAssignment::PromptRenameProject(project_id.clone()),),reveal_item,ContextMenuItem::item_with_icon("New Thread",- "plus.square",+ ContextMenuIcon::New,KeyAssignment::CreateWorkspaceThread(project_id.clone()),),ContextMenuItem::item_with_icon("Collapse / Expand Threads",- "chevron.right",+ ContextMenuIcon::Collapse,KeyAssignment::ToggleWorkspaceThreadsCollapsed(project_id.clone()),),ContextMenuItem::Separator,ContextMenuItem::item_with_icon("Remove Workspace",- "folder.badge.minus",+ ContextMenuIcon::FolderRemove,KeyAssignment::RemoveProject(project_id),),]@@ -3186,13 +3451,11 @@ impl super::TermWindow {let mut item = ContextMenuItem::item_with_icon(label,if space.is_default {- "house"+ ContextMenuIcon::Home} else if space.is_remote {- // Must be a valid SF Symbol name: macOS renders these- // through the native menu's imageWithSystemSymbolName.- "server.rack"+ ContextMenuIcon::Server} else {- "square.stack"+ ContextMenuIcon::Stack},KeyAssignment::SwitchSpace(space.id.to_string()),)@@ -3206,7 +3469,7 @@ impl super::TermWindow {items.push(ContextMenuItem::Separator);items.push(ContextMenuItem::item_with_icon("New Space",- "plus.square",+ ContextMenuIcon::New,KeyAssignment::CreateSpace,));items.push(ContextMenuItem::item_with_icon(@@ -3215,7 +3478,7 @@ impl super::TermWindow {.find(|space| space.is_active).map(|space| format!("Rename \"{}\"...", space.name)).unwrap_or_else(|| "Rename Space...".to_string()),- "pencil",+ ContextMenuIcon::Edit,KeyAssignment::PromptRenameSpace(self.active_space_id.clone()),));let active_space_id = spaces@@ -3232,7 +3495,7 @@ impl super::TermWindow {} else {format!("Delete \"{}\"", space.name)},- "trash",+ ContextMenuIcon::Delete,KeyAssignment::DeleteSpace(space.id),)};@@ -3259,7 +3522,7 @@ impl super::TermWindow {if offer_remote_kill {items.push(ContextMenuItem::item_with_icon(format!("Delete \"{name}\" & End Remote Sessions"),- "trash",+ ContextMenuIcon::Delete,KeyAssignment::DeleteSpaceAndRemoteSessions(id),));}@@ -3271,8 +3534,9 @@ impl super::TermWindow {.map(delete_item).collect::<Vec<_>>();if !other_delete_candidates.is_empty() {- items.push(ContextMenuItem::submenu(+ items.push(ContextMenuItem::submenu_with_icon("Delete Other Space",+ ContextMenuIcon::Delete,other_delete_candidates,));}@@ -3283,43 +3547,68 @@ impl super::TermWindow {use config::keyassignment::KeyAssignment;vec![- ContextMenuItem::item("Group by", KeyAssignment::Nop).disabled(),- ContextMenuItem::item_with_icon("Workspace", "folder", KeyAssignment::Nop)- .checked(true)+ ContextMenuItem::item_with_icon("Group by", ContextMenuIcon::Stack, KeyAssignment::Nop).disabled(),+ ContextMenuItem::item_with_icon(+ "Workspace",+ ContextMenuIcon::Folder,+ KeyAssignment::Nop,+ )+ .checked(true)+ .disabled(),ContextMenuItem::Separator,- ContextMenuItem::item("Show", KeyAssignment::Nop).disabled(),- ContextMenuItem::submenu(+ ContextMenuItem::item_with_icon("Show", ContextMenuIcon::Info, KeyAssignment::Nop)+ .disabled(),+ ContextMenuItem::submenu_with_icon("Status",+ ContextMenuIcon::Check,vec![ContextMenuItem::item_with_icon("Running",- "arrow.triangle.2.circlepath",+ ContextMenuIcon::Refresh,KeyAssignment::Nop,).checked(true).disabled(),ContextMenuItem::item_with_icon("Needs Attention",- "exclamationmark.circle",+ ContextMenuIcon::Warning,+ KeyAssignment::Nop,+ )+ .checked(true)+ .disabled(),+ ContextMenuItem::item_with_icon(+ "Done",+ ContextMenuIcon::Check,KeyAssignment::Nop,).checked(true).disabled(),- ContextMenuItem::item_with_icon("Done", "checkmark.circle", KeyAssignment::Nop)- .checked(true)- .disabled(),],),- ContextMenuItem::item_with_icon("Unread", "envelope.badge", KeyAssignment::Nop)- .checked(true)- .disabled(),- ContextMenuItem::item_with_icon("Pinned", "pin", KeyAssignment::Nop)+ ContextMenuItem::item_with_icon(+ "Unread",+ ContextMenuIcon::Notification,+ KeyAssignment::Nop,+ )+ .checked(true)+ .disabled(),+ ContextMenuItem::item_with_icon("Pinned", ContextMenuIcon::Pin, KeyAssignment::Nop).checked(true).disabled(),ContextMenuItem::Separator,- ContextMenuItem::item("Collapse All", KeyAssignment::Nop).disabled(),- ContextMenuItem::item("Mark All Read", KeyAssignment::Nop).disabled(),+ ContextMenuItem::item_with_icon(+ "Collapse All",+ ContextMenuIcon::Collapse,+ KeyAssignment::Nop,+ )+ .disabled(),+ ContextMenuItem::item_with_icon(+ "Mark All Read",+ ContextMenuIcon::Check,+ KeyAssignment::Nop,+ )+ .disabled(),]}@@ -3394,14 +3683,14 @@ impl super::TermWindow {if connection.is_remote && connection.is_live {items.push(ContextMenuItem::item_with_icon("Disconnect Thread",- "unlink",+ ContextMenuIcon::Close,KeyAssignment::DisconnectWorkspaceThread(thread_id.clone()),));items.push(ContextMenuItem::Separator);} else if connection.is_remote && remote_host_exists {items.push(ContextMenuItem::item_with_icon("Connect Thread",- "link",+ ContextMenuIcon::ExternalLink,KeyAssignment::ConnectWorkspaceThread(thread_id.clone()),));items.push(ContextMenuItem::Separator);@@ -3415,22 +3704,26 @@ impl super::TermWindow {} else {"Pin Thread"},- if is_pinned { "pin.slash" } else { "pin" },+ if is_pinned {+ ContextMenuIcon::Unpin+ } else {+ ContextMenuIcon::Pin+ },KeyAssignment::ToggleWorkspaceThreadPinned(thread_id.clone()),),ContextMenuItem::item_with_icon("Rename Thread...",- "pencil",+ ContextMenuIcon::Edit,KeyAssignment::PromptRenameWorkspaceThread(thread_id.clone()),),ContextMenuItem::item_with_icon("Delete Thread",- "trash",+ ContextMenuIcon::Delete,KeyAssignment::DeleteWorkspaceThread(thread_id.clone()),),ContextMenuItem::item_with_icon("Mark as Unread",- "envelope.badge",+ ContextMenuIcon::Notification,KeyAssignment::MarkWorkspaceThreadUnread(thread_id),),]);@@ -4367,7 +4660,7 @@ impl super::TermWindow {fn pane_nav_tab_context_menu_items(&self, pane_id: mux::pane::PaneId) -> Vec<ContextMenuItem> {vec![ContextMenuItem::item_with_icon("Rename Tab...",- "pencil",+ ContextMenuIcon::Edit,KeyAssignment::PromptRenamePaneTab(pane_id),)]}@@ -4755,19 +5048,31 @@ impl super::TermWindow {let mut items = vec![ContextMenuItem::item_with_icon("Rename Tab...",- "pencil",+ ContextMenuIcon::Edit,Self::tab_context_action(tab_idx, KeyAssignment::PromptRenameTab),)];let mut close_items = vec![];if let Some(action) = Self::close_tabs_to_left_action(tab_idx) {- close_items.push(ContextMenuItem::item("Close Tabs to Left", action));+ close_items.push(ContextMenuItem::item_with_icon(+ "Close Tabs to Left",+ ContextMenuIcon::Close,+ action,+ ));}if let Some(action) = Self::close_tabs_to_right_action(tab_idx, tab_count) {- close_items.push(ContextMenuItem::item("Close Tabs to Right", action));+ close_items.push(ContextMenuItem::item_with_icon(+ "Close Tabs to Right",+ ContextMenuIcon::Close,+ action,+ ));}if let Some(action) = Self::close_other_tabs_action(tab_idx, tab_count) {- close_items.push(ContextMenuItem::item("Close Other Tabs", action));+ close_items.push(ContextMenuItem::item_with_icon(+ "Close Other Tabs",+ ContextMenuIcon::Close,+ action,+ ));}if !close_items.is_empty() {items.push(ContextMenuItem::Separator);@@ -4776,14 +5081,16 @@ impl super::TermWindow {let mut move_items = vec![];if tab_idx > 0 {- move_items.push(ContextMenuItem::item(+ move_items.push(ContextMenuItem::item_with_icon("Move Tab Left",+ ContextMenuIcon::MoveLeft,Self::tab_context_action(tab_idx, KeyAssignment::MoveTab(tab_idx - 1)),));}if tab_idx + 1 < tab_count {- move_items.push(ContextMenuItem::item(+ move_items.push(ContextMenuItem::item_with_icon("Move Tab Right",+ ContextMenuIcon::MoveRight,Self::tab_context_action(tab_idx, KeyAssignment::MoveTab(tab_idx + 1)),));}@@ -4795,15 +5102,16 @@ impl super::TermWindow {items.push(ContextMenuItem::Separator);items.push(ContextMenuItem::item_with_icon("New Terminal Tab to Right",- "plus.square",+ ContextMenuIcon::Terminal,Self::tab_context_action(tab_idx,KeyAssignment::SpawnTabToRight(SpawnTabDomain::CurrentPaneDomain),),));items.push(ContextMenuItem::Separator);- items.push(ContextMenuItem::item(+ items.push(ContextMenuItem::item_with_icon("Zoom Pane",+ ContextMenuIcon::Expand,Self::tab_context_action(tab_idx, KeyAssignment::TogglePaneZoomState),));@@ -5002,7 +5310,11 @@ impl super::TermWindow {}fn terminal_context_menu_items(&self) -> Vec<ContextMenuItem> {- fn split_item(label: &str, icon: &str, direction: PaneDirection) -> ContextMenuItem {+ fn split_item(+ label: &str,+ icon: ContextMenuIcon,+ direction: PaneDirection,+ ) -> ContextMenuItem {ContextMenuItem::item_with_icon(label,icon,@@ -5018,28 +5330,171 @@ impl super::TermWindow {vec![ContextMenuItem::item_with_icon("Copy",- "doc.on.doc",+ ContextMenuIcon::Copy,KeyAssignment::CopyTo(ClipboardCopyDestination::Clipboard),),ContextMenuItem::item_with_icon("Paste",- "doc.on.clipboard",+ ContextMenuIcon::Paste,KeyAssignment::PasteFrom(ClipboardPasteSource::Clipboard),),ContextMenuItem::Separator,- split_item("Split Right", "rectangle.split.2x1", PaneDirection::Right),- split_item("Split Left", "rectangle.split.2x1", PaneDirection::Left),- split_item("Split Down", "rectangle.split.1x2", PaneDirection::Down),- split_item("Split Up", "rectangle.split.1x2", PaneDirection::Up),+ split_item(+ "Split Right",+ ContextMenuIcon::SplitHorizontal,+ PaneDirection::Right,+ ),+ split_item(+ "Split Left",+ ContextMenuIcon::SplitHorizontal,+ PaneDirection::Left,+ ),+ split_item(+ "Split Down",+ ContextMenuIcon::SplitVertical,+ PaneDirection::Down,+ ),+ split_item(+ "Split Up",+ ContextMenuIcon::SplitVertical,+ PaneDirection::Up,+ ),ContextMenuItem::Separator,ContextMenuItem::item_with_icon("Reset Terminal",- "arrow.clockwise",+ ContextMenuIcon::Refresh,KeyAssignment::ResetTerminal,),]}+ fn right_sidebar_note_context_menu_items(+ &mut self,+ anchor: window::Point,+ ) -> Vec<ContextMenuItem> {+ use crate::termwindow::{ContextMenuApplicationAction, NoteEditorCommand};++ let Some(session) = self.right_sidebar_note.session.clone() else {+ return vec![];+ };+ let session = session.lock();+ let editable =+ self.right_sidebar_note.view.mode != crate::markdown_editor::EditorMode::ReadOnly;+ let has_selection = !self.right_sidebar_note.view.selection.is_caret();+ let has_text = !session.source().is_empty();+ let can_undo = editable && session.can_undo();+ let can_redo = editable && session.can_redo();+ let revision = session.revision();+ let selected_range = self.right_sidebar_note.view.selection.range();+ let spelling_issue = self+ .right_sidebar_note+ .spelling_issues+ .iter()+ .find(|issue| {+ issue.source.start < selected_range.end && selected_range.start < issue.source.end+ })+ .cloned();+ let lookup_text = session+ .selected_text(&self.right_sidebar_note.view)+ .map(str::to_string)+ .filter(|text| !text.trim().is_empty());+ drop(session);++ self.begin_context_menu_application_actions();+ let mut items = Vec::new();+ if let Some(issue) = spelling_issue {+ for suggestion in issue.suggestions.iter().take(5) {+ items.push(self.context_menu_application_item_with_icon(+ suggestion.clone(),+ ContextMenuIcon::Spellcheck,+ ContextMenuApplicationAction::Note(NoteEditorCommand::ReplaceSpelling {+ revision,+ range: issue.source.clone(),+ replacement: suggestion.clone(),+ }),+ editable,+ ));+ }+ if !issue.suggestions.is_empty() {+ items.push(ContextMenuItem::Separator);+ }+ items.push(self.context_menu_application_item_with_icon(+ "Ignore Spelling",+ ContextMenuIcon::Spellcheck,+ ContextMenuApplicationAction::Note(NoteEditorCommand::IgnoreSpelling {+ word: issue.word.clone(),+ }),+ true,+ ));+ items.push(self.context_menu_application_item_with_icon(+ "Learn Spelling",+ ContextMenuIcon::Spellcheck,+ ContextMenuApplicationAction::Note(NoteEditorCommand::LearnSpelling {+ word: issue.word,+ }),+ true,+ ));+ items.push(ContextMenuItem::Separator);+ }+ if let Some(text) = lookup_text {+ items.push(self.context_menu_application_item_with_icon(+ "Look Up",+ ContextMenuIcon::Search,+ ContextMenuApplicationAction::Note(NoteEditorCommand::LookUp {+ text,+ anchor: window::Rect::new(anchor, window::Size::new(1, 1)),+ }),+ true,+ ));+ items.push(ContextMenuItem::Separator);+ }+ items.push(self.context_menu_application_item_with_icon(+ "Undo",+ ContextMenuIcon::Undo,+ ContextMenuApplicationAction::Note(NoteEditorCommand::Undo),+ can_undo,+ ));+ items.push(self.context_menu_application_item_with_icon(+ "Redo",+ ContextMenuIcon::Redo,+ ContextMenuApplicationAction::Note(NoteEditorCommand::Redo),+ can_redo,+ ));+ items.push(ContextMenuItem::Separator);+ items.push(self.context_menu_application_item_with_icon(+ "Cut",+ ContextMenuIcon::Cut,+ ContextMenuApplicationAction::Note(NoteEditorCommand::Cut),+ editable && has_selection,+ ));+ items.push(self.context_menu_application_item_with_icon(+ "Copy",+ ContextMenuIcon::Copy,+ ContextMenuApplicationAction::Note(NoteEditorCommand::Copy),+ has_selection,+ ));+ items.push(self.context_menu_application_item_with_icon(+ "Paste",+ ContextMenuIcon::Paste,+ ContextMenuApplicationAction::Note(NoteEditorCommand::Paste),+ editable,+ ));+ items.push(self.context_menu_application_item_with_icon(+ "Delete",+ ContextMenuIcon::Delete,+ ContextMenuApplicationAction::Note(NoteEditorCommand::Delete),+ editable && has_selection,+ ));+ items.push(ContextMenuItem::Separator);+ items.push(self.context_menu_application_item_with_icon(+ "Select All",+ ContextMenuIcon::Check,+ ContextMenuApplicationAction::Note(NoteEditorCommand::SelectAll),+ has_text,+ ));+ items+ }+fn mouse_event_terminal(&mut self,mut pane: Arc<dyn Pane>,diff --git a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rsindex 94de72fa..036897e3 100644--- a/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs+++ b/wezterm-gui/src/termwindow/render/fancy_tab_bar.rs@@ -1442,6 +1442,122 @@ impl crate::TermWindow {Ok((x_pos - start_x).max(0.0))}+ /// Pixel-clip glyph quads and their texture coordinates at both horizontal+ /// edges. This is intended for horizontally scrollable text surfaces; fixed+ /// labels continue to use `paint_cached_ui_shape_clipped`, which preserves+ /// its whole-glyph truncation behavior.+ #[allow(clippy::too_many_arguments)]+ pub(crate) fn paint_cached_ui_shape_pixel_clipped<F>(+ &self,+ layers: &mut TripleLayerQuadAllocator,+ metrics: &RenderMetrics,+ shaped: &[ShapedInfo],+ start_x: f32,+ y: f32,+ clip_left: f32,+ clip_right: f32,+ mut color_for: F,+ ) -> anyhow::Result<f32>+ where+ F: FnMut(&ShapedInfo) -> LinearRgba,+ {+ if shaped.is_empty() || clip_right <= clip_left {+ return Ok(0.0);+ }++ let Some(gl_state) = self.render_state.as_ref() else {+ return Ok(0.0);+ };+ let mut glyph_cache = gl_state.glyph_cache.borrow_mut();+ let left_offset = self.dimensions.pixel_width as f32 / -2.0;+ let top_offset = self.dimensions.pixel_height as f32 / -2.0;+ let baseline = metrics.cell_size.height as f32 + metrics.descender.get() as f32;+ let mut x_pos = start_x;++ for info in shaped {+ let advance = info.glyph.x_advance.get() as f32;++ if let Some(key) = info.block_key {+ let sprite = glyph_cache.cached_block(key, metrics)?;+ let texture = sprite.texture_coords();+ if let Some(clip) = horizontal_texture_clip(+ x_pos,+ x_pos + advance,+ texture.min_x(),+ texture.max_x(),+ clip_left,+ clip_right,+ ) {+ let color = color_for(info);+ let mut quad = layers.allocate(2)?;+ quad.set_position(+ clip.position_left + left_offset,+ y + top_offset,+ clip.position_right + left_offset,+ y + top_offset + metrics.cell_size.height as f32,+ );+ quad.set_texture_discrete(+ clip.texture_left,+ clip.texture_right,+ texture.min_y(),+ texture.max_y(),+ );+ quad.set_fg_color(color);+ quad.set_alt_color_and_mix_value(color, 0.0);+ quad.set_hsv(None);+ } else if x_pos >= clip_right {+ break;+ }+ x_pos += advance;+ continue;+ }++ let glyph = &info.glyph;+ if let Some(texture) = glyph.texture.as_ref() {+ let glyph_x = x_pos + (glyph.x_offset + glyph.bearing_x).get() as f32;+ let glyph_y = y - (glyph.y_offset + glyph.bearing_y).get() as f32 + baseline;+ let glyph_width = texture.coords.size.width as f32 * glyph.scale as f32;+ let glyph_height = texture.coords.size.height as f32 * glyph.scale as f32;+ let texture_rect = texture.texture_coords();+ if let Some(clip) = horizontal_texture_clip(+ glyph_x,+ glyph_x + glyph_width,+ texture_rect.min_x(),+ texture_rect.max_x(),+ clip_left,+ clip_right,+ ) {+ let color = color_for(info);+ let mut quad = layers.allocate(2)?;+ quad.set_position(+ clip.position_left + left_offset,+ glyph_y + top_offset,+ clip.position_right + left_offset,+ glyph_y + top_offset + glyph_height,+ );+ quad.set_texture_discrete(+ clip.texture_left,+ clip.texture_right,+ texture_rect.min_y(),+ texture_rect.max_y(),+ );+ quad.set_fg_color(color);+ quad.set_alt_color_and_mix_value(color, 0.0);+ quad.set_has_color(glyph.has_color);+ quad.set_hsv(None);+ } else if glyph_x >= clip_right {+ break;+ }+ } else if x_pos >= clip_right {+ break;+ }++ x_pos += advance;+ }++ Ok((x_pos - start_x).max(0.0))+ }+fn paint_fancy_tab_icon(&self,layers: &mut TripleLayerQuadAllocator,@@ -1477,6 +1593,49 @@ impl crate::TermWindow {}}+#[derive(Debug, Clone, Copy, PartialEq)]+struct HorizontalTextureClip {+ position_left: f32,+ position_right: f32,+ texture_left: f32,+ texture_right: f32,+}++fn horizontal_texture_clip(+ position_left: f32,+ position_right: f32,+ texture_left: f32,+ texture_right: f32,+ clip_left: f32,+ clip_right: f32,+) -> Option<HorizontalTextureClip> {+ let width = position_right - position_left;+ if !(width > 0.0 && texture_right > texture_left && clip_right > clip_left) {+ return None;+ }+ let visible_left = position_left.max(clip_left);+ let visible_right = position_right.min(clip_right);+ if visible_right <= visible_left {+ return None;+ }+ // A sub-pixel remnant of a clipped glyph (particularly the outer edge of+ // braces) rasterizes as a stray dot. Keep genuine partial glyphs, but drop+ // the final fragment once it is narrower than one physical pixel.+ let was_clipped = visible_left > position_left || visible_right < position_right;+ if was_clipped && visible_right - visible_left < 1.0 {+ return None;+ }+ let left_fraction = (visible_left - position_left) / width;+ let right_fraction = (visible_right - position_left) / width;+ let texture_width = texture_right - texture_left;+ Some(HorizontalTextureClip {+ position_left: visible_left,+ position_right: visible_right,+ texture_left: texture_left + texture_width * left_fraction,+ texture_right: texture_left + texture_width * right_fraction,+ })+}+fn fancy_tab_icon_size(metrics: &RenderMetrics, tab_bar_height: f32) -> f32 {let cell_height = metrics.cell_size.height.max(1) as f32;let from_bar = (tab_bar_height - cell_height * 0.45).max(1.0);@@ -1498,3 +1657,37 @@ fn is_legacy_progress_marker(value: &str) -> bool {0x2800..=0x28ff | 0xf0130 | 0xf0a9e..=0xf0aa5 | 0xee00..=0xee0b)}++#[cfg(test)]+mod pixel_clip_tests {+ use super::{horizontal_texture_clip, HorizontalTextureClip};++ #[test]+ fn horizontal_texture_clip_crops_position_and_uv_together() {+ let clip = horizontal_texture_clip(10.0, 30.0, 0.2, 0.6, 15.0, 25.0).unwrap();+ assert_eq!(+ clip,+ HorizontalTextureClip {+ position_left: 15.0,+ position_right: 25.0,+ texture_left: 0.3,+ texture_right: 0.5,+ }+ );+ }++ #[test]+ fn horizontal_texture_clip_rejects_invisible_or_invalid_quads() {+ assert!(horizontal_texture_clip(10.0, 20.0, 0.2, 0.6, 20.0, 30.0).is_none());+ assert!(horizontal_texture_clip(10.0, 10.0, 0.2, 0.6, 0.0, 30.0).is_none());+ assert!(horizontal_texture_clip(10.0, 20.0, 0.6, 0.2, 0.0, 30.0).is_none());+ }++ #[test]+ fn horizontal_texture_clip_hides_subpixel_clipped_remnants() {+ assert!(horizontal_texture_clip(10.0, 20.0, 0.2, 0.6, 19.25, 30.0).is_none());++ // Do not discard a naturally narrow quad when no clipping occurred.+ assert!(horizontal_texture_clip(10.0, 10.75, 0.2, 0.6, 0.0, 30.0).is_some());+ }+}diff --git a/wezterm-gui/src/termwindow/ui/context_menu.rs b/wezterm-gui/src/termwindow/ui/context_menu.rsindex 6f076f02..08b99969 100644--- a/wezterm-gui/src/termwindow/ui/context_menu.rs+++ b/wezterm-gui/src/termwindow/ui/context_menu.rs@@ -5,10 +5,10 @@ use crate::ui::UiPalette;use crate::utilsprites::RenderMetrics;use ::window::color::LinearRgba;use ::window::{- Appearance, ContextMenuItem, MouseCursor, MouseEvent, MouseEventKind, MousePress, WindowOps,+ Appearance, ContextMenuAction, ContextMenuIcon, ContextMenuItem, MouseCursor, MouseEvent,+ MouseEventKind, MousePress, WindowOps,};use anyhow::Context;-use config::keyassignment::KeyAssignment;use mux::pane::Pane;use std::rc::Rc;use std::sync::Arc;@@ -32,6 +32,16 @@ const MENU_ROW_RADIUS: f32 = 15.0;const MENU_ROW_HOVER_INSET_X: usize = 8;const MENU_ROW_HOVER_INSET_Y: usize = 2;+pub(crate) fn reveal_in_folder_label() -> &'static str {+ if cfg!(target_os = "macos") {+ "Reveal in Finder"+ } else if cfg!(target_os = "windows") {+ "Show in File Explorer"+ } else {+ "Show in Folder"+ }+}+#[derive(Clone, Debug)]pub(crate) struct ContextMenuState {anchor: window::Point,@@ -115,7 +125,7 @@ impl ContextMenuState {}}- fn action_for_path(&self, path: &[usize]) -> Option<KeyAssignment> {+ fn action_for_path(&self, path: &[usize]) -> Option<ContextMenuAction> {match self.item_at_path(path) {Some(ContextMenuItem::Item {action,@@ -145,6 +155,47 @@ impl MenuRect {}impl crate::TermWindow {+ pub(crate) fn begin_context_menu_application_actions(&mut self) {+ self.context_menu_application_actions.clear();+ }++ pub(crate) fn context_menu_application_item_with_icon(+ &mut self,+ label: impl Into<String>,+ icon: ContextMenuIcon,+ action: crate::termwindow::ContextMenuApplicationAction,+ enabled: bool,+ ) -> ContextMenuItem {+ let action_id = self.next_context_menu_application_action_id;+ self.next_context_menu_application_action_id = self+ .next_context_menu_application_action_id+ .wrapping_add(1)+ .max(1);+ self.context_menu_application_actions+ .insert(action_id, action);+ let item = ContextMenuItem::application_item(label, action_id).with_icon(icon);+ if enabled {+ item+ } else {+ item.disabled()+ }+ }++ pub(crate) fn perform_context_menu_application_action(&mut self, action_id: u64) {+ let Some(action) = self+ .context_menu_application_actions+ .get(&action_id)+ .cloned()+ else {+ return;+ };+ match action {+ crate::termwindow::ContextMenuApplicationAction::Note(command) => {+ self.perform_right_sidebar_note_command(command);+ }+ }+ }+pub(crate) fn show_term_context_menu(&mut self,context: &dyn WindowOps,@@ -203,8 +254,15 @@ impl crate::TermWindow {if let Some(action) = menu.action_for_path(&path) {self.close_fallback_context_menu();context.invalidate();- if let Err(err) = self.perform_key_assignment(pane, &action) {- log::error!("context menu action failed: {err:#}");+ match action {+ ContextMenuAction::KeyAssignment(action) => {+ if let Err(err) = self.perform_key_assignment(pane, &action) {+ log::error!("context menu action failed: {err:#}");+ }+ }+ ContextMenuAction::ApplicationAction(action_id) => {+ self.perform_context_menu_application_action(action_id);+ }}return true;}@@ -746,44 +804,46 @@ fn context_menu_palette(appearance: Appearance) -> UiPalette {palette}-fn menu_icon(icon: &str) -> Option<SvgIcon> {+fn menu_icon(icon: &ContextMenuIcon) -> Option<SvgIcon> {match icon {- "app" => Some(SvgIcon::ExternalLink),- "arrow.clockwise" => Some(SvgIcon::RotateCcw),- "arrow.up.right.square" => Some(SvgIcon::ExternalLink),- "arrow.triangle.2.circlepath" => Some(SvgIcon::RotateCcw),- "checkmark.circle" => Some(SvgIcon::CircleCheck),- "chevron.right" => Some(SvgIcon::ChevronRight),- "doc.on.doc" => Some(SvgIcon::Copy),- "doc.on.clipboard" => Some(SvgIcon::ClipboardPaste),- "envelope.badge" => Some(SvgIcon::Bell),- "exclamationmark.circle" => Some(SvgIcon::CircleAlert),- "folder" => Some(SvgIcon::Folder),- "folder.badge.minus" => Some(SvgIcon::FolderMinus),- "folder.badge.plus" => Some(SvgIcon::FolderPlus),- "folder.badge.questionmark" => Some(SvgIcon::FolderOpen),- "folder.badge.xmark" => Some(SvgIcon::FolderOpen),- "folder.fill" => Some(SvgIcon::Folder),- "folder.fill.badge.gearshape" => Some(SvgIcon::Settings),- "folder.fill.badge.minus" => Some(SvgIcon::FolderMinus),- "folder.fill.badge.plus" => Some(SvgIcon::FolderPlus),- "folder.fill.badge.xmark" => Some(SvgIcon::FolderOpen),- "house" => Some(SvgIcon::House),- "pencil" => Some(SvgIcon::Pencil),- "pin" => Some(SvgIcon::Pin),- "pin.slash" => Some(SvgIcon::PinOff),- "plus" => Some(SvgIcon::Plus),- "plus.square" => Some(SvgIcon::SquarePlus),- "rectangle.split.1x2" => Some(SvgIcon::SplitVertical),- "rectangle.split.2x1" => Some(SvgIcon::SplitHorizontal),- "sidebar.leading" => Some(SvgIcon::PanelLeft),- "square.and.pencil" => Some(SvgIcon::NotebookTabs),- "server.rack" => Some(SvgIcon::Server),- "square.stack" => Some(SvgIcon::SquareStack),- "terminal" => Some(SvgIcon::Terminal),- "trash" => Some(SvgIcon::Trash2),- "trash.fill" => Some(SvgIcon::Trash2),- "xmark" => Some(SvgIcon::X),- _ => None,+ ContextMenuIcon::Application | ContextMenuIcon::ExternalLink => Some(SvgIcon::ExternalLink),+ ContextMenuIcon::Back | ContextMenuIcon::MoveLeft => Some(SvgIcon::ArrowLeft),+ ContextMenuIcon::Check => Some(SvgIcon::CircleCheck),+ ContextMenuIcon::Close => Some(SvgIcon::X),+ ContextMenuIcon::Code => Some(SvgIcon::CodeXml),+ ContextMenuIcon::Collapse => Some(SvgIcon::Shrink),+ ContextMenuIcon::Copy => Some(SvgIcon::Copy),+ ContextMenuIcon::Cut => Some(SvgIcon::Scissors),+ ContextMenuIcon::Delete => Some(SvgIcon::Trash2),+ ContextMenuIcon::Edit => Some(SvgIcon::Pencil),+ ContextMenuIcon::Expand => Some(SvgIcon::Expand),+ ContextMenuIcon::File => Some(SvgIcon::File),+ ContextMenuIcon::Folder => Some(SvgIcon::Folder),+ ContextMenuIcon::FolderAdd => Some(SvgIcon::FolderPlus),+ ContextMenuIcon::FolderRemove => Some(SvgIcon::FolderMinus),+ ContextMenuIcon::Home => Some(SvgIcon::House),+ ContextMenuIcon::Info => Some(SvgIcon::Info),+ ContextMenuIcon::MoveRight => Some(SvgIcon::ArrowRight),+ ContextMenuIcon::New => Some(SvgIcon::Plus),+ ContextMenuIcon::Note => Some(SvgIcon::NotebookTabs),+ ContextMenuIcon::Notification => Some(SvgIcon::Bell),+ ContextMenuIcon::Paste => Some(SvgIcon::ClipboardPaste),+ ContextMenuIcon::Pin => Some(SvgIcon::Pin),+ ContextMenuIcon::Refresh => Some(SvgIcon::RotateCcw),+ ContextMenuIcon::Redo => Some(SvgIcon::RotateCw),+ ContextMenuIcon::Save => Some(SvgIcon::Save),+ ContextMenuIcon::Search => Some(SvgIcon::Search),+ ContextMenuIcon::Server => Some(SvgIcon::Server),+ ContextMenuIcon::Settings => Some(SvgIcon::Settings),+ ContextMenuIcon::Sidebar => Some(SvgIcon::PanelLeft),+ ContextMenuIcon::Spellcheck => Some(SvgIcon::SpellCheck),+ ContextMenuIcon::SplitHorizontal => Some(SvgIcon::SplitHorizontal),+ ContextMenuIcon::SplitVertical => Some(SvgIcon::SplitVertical),+ ContextMenuIcon::Stack | ContextMenuIcon::Window => Some(SvgIcon::SquareStack),+ ContextMenuIcon::Terminal => Some(SvgIcon::Terminal),+ ContextMenuIcon::Undo => Some(SvgIcon::RotateCcw),+ ContextMenuIcon::Unpin => Some(SvgIcon::PinOff),+ ContextMenuIcon::Vault => Some(SvgIcon::FolderTree),+ ContextMenuIcon::Warning => Some(SvgIcon::CircleAlert),}}diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rsindex a98df0e9..c8de7f52 100644--- a/wezterm-gui/src/termwindow/ui/icons.rs+++ b/wezterm-gui/src/termwindow/ui/icons.rs@@ -6,6 +6,7 @@ use window::Image;pub enum SvgIcon {Archive,ArrowLeft,+ ArrowRight,Bell,Braces,Check,@@ -52,6 +53,9 @@ pub enum SvgIcon {PinOff,Plus,RotateCcw,+ RotateCw,+ Save,+ Scissors,Search,Server,Settings,@@ -67,6 +71,7 @@ pub enum SvgIcon {SquareTerminal,SplitHorizontal,SplitVertical,+ SpellCheck,Terminal,Trash2,X,@@ -79,6 +84,9 @@ impl SvgIcon {Self::ArrowLeft => {include_bytes!("../../../../third_party/lucide/icons/arrow-left.svg")}+ Self::ArrowRight => {+ include_bytes!("../../../../third_party/lucide/icons/arrow-right.svg")+ }Self::Bell => include_bytes!("../../../../third_party/lucide/icons/bell.svg"),Self::Braces => include_bytes!("../../../../third_party/lucide/icons/braces.svg"),Self::Check => include_bytes!("../../../../third_party/lucide/icons/check.svg"),@@ -171,6 +179,9 @@ impl SvgIcon {Self::RotateCcw => {include_bytes!("../../../../third_party/lucide/icons/rotate-ccw.svg")}+ Self::RotateCw => include_bytes!("../../../../third_party/lucide/icons/redo.svg"),+ Self::Save => include_bytes!("../../../../third_party/lucide/icons/save.svg"),+ Self::Scissors => include_bytes!("../../../../third_party/lucide/icons/scissors.svg"),Self::Search => include_bytes!("../../../../third_party/lucide/icons/search.svg"),Self::Server => include_bytes!("../../../../third_party/lucide/icons/server.svg"),Self::Settings => include_bytes!("../../../../third_party/lucide/icons/settings.svg"),@@ -206,6 +217,9 @@ impl SvgIcon {Self::SplitVertical => {include_bytes!("../../../../third_party/lucide/icons/square-split-vertical.svg")}+ Self::SpellCheck => {+ include_bytes!("../../../../third_party/lucide/icons/spell-check.svg")+ }Self::Terminal => include_bytes!("../../../../third_party/lucide/icons/terminal.svg"),Self::Trash2 => include_bytes!("../../../../third_party/lucide/icons/trash-2.svg"),Self::X => include_bytes!("../../../../third_party/lucide/icons/x.svg"),@@ -525,6 +539,7 @@ mod tests {SvgIcon::PinOff,SvgIcon::Plus,SvgIcon::RotateCcw,+ SvgIcon::RotateCw,SvgIcon::Search,SvgIcon::Settings,SvgIcon::SlidersHorizontal,diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rsindex a3f0840f..9d321add 100644--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs@@ -1,12 +1,14 @@use crate::markdown_editor::{- default_notebook, fit_table_columns, resolve_local_image, save_document_revision,- wrap_visual_document_by_width, BlockKind, EditorMode, NoteCodeBlockLayout, NoteLineLayout,- NoteRunLayout, ProjectedCodeBlock, ProjectedObject, SaveState, SourceSelection, TableAlignment,- VisualLineKind,+ AutosaveWakeAction, BlockKind, EditorMode, NoteCodeBlockLayout, NoteLineGeometry,+ NoteLineLayout, NoteRunLayout, NoteSpellingIssue, ProjectedCodeBlock, ProjectedObject,+ SaveState, SourceSelection, TableAlignment, VisualLineKind, build_spell_check_chunks_in_range,+ build_visual_document, fit_table_columns, load_remote_image, open_vault_document,+ resolve_local_image, save_document_revision, vault_file_paths, vault_markdown_paths,+ wrap_visual_document_by_width_cached,};use crate::quad::{QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait};use crate::termwindow::ui::icons::{- material_file_icon_for_name, material_folder_icon_for_name, MaterialIcon, SvgIcon,+ MaterialIcon, SvgIcon, material_file_icon_for_name, material_folder_icon_for_name,};use crate::termwindow::ui::tokens::{CAPSULE_BORDER_WIDTH, ICON_BUTTON_BORDER_WIDTH, SIDEBAR_ICON_GAP, SIDEBAR_INSET,@@ -14,16 +16,17 @@ use crate::termwindow::ui::tokens::{WINDOW_TAB_LEADING_ACTION_BUTTON_SIZE, WINDOW_TAB_LEADING_ACTION_GAP,};use crate::termwindow::{- RightSidebarFileCharBag, RightSidebarFileField, RightSidebarFileIndex,+ NoteEditorCommand, RightSidebarFileCharBag, RightSidebarFileField, RightSidebarFileIndex,RightSidebarFileIndexEntry, RightSidebarFileIndexStatus, RightSidebarFilePreviewImage,RightSidebarFilePreviewLine, RightSidebarFilePreviewSelection,RightSidebarFilePreviewSelectionPoint, RightSidebarFilePreviewSliceCacheKey,RightSidebarFilePreviewSliceCacheValue, RightSidebarFilePreviewSpan, RightSidebarFileTreeRow,RightSidebarFileView, RightSidebarFileViewState, RightSidebarInputLayout, RightSidebarMode,+ RightSidebarNoteImageSource, RightSidebarNoteTableLayout, RightSidebarNoteView,RightSidebarOpenWithCacheEntry, RightSidebarSnippetField, RightSidebarSnippetView,TermWindowNotif, UIItem, UIItemType, UiShapeCacheLookup,};-use crate::ui::{scale_ui_usize, unscale_ui_usize, TextInputState, UiPalette};+use crate::ui::{TextInputState, UiPalette, scale_ui_usize, unscale_ui_usize};use crate::utilsprites::RenderMetrics;use crate::workspace_threads;use anyhow::Context;@@ -31,7 +34,7 @@ use config::keyassignment::{ClipboardCopyDestination, ClipboardPasteSource, KeyAuse mux::Mux;use std::borrow::Cow;use std::cmp::Ordering;-use std::collections::{HashMap, HashSet};+use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};use std::fs;use std::hash::{DefaultHasher, Hash, Hasher};use std::io::Read;@@ -42,13 +45,14 @@ use std::sync::{Arc, Mutex, OnceLock, Weak};use std::time::{Duration, Instant};use termwiz::image::{ImageData, ImageDataType};use termwiz::input::{KeyCode as TermKeyCode, Modifiers as TermModifiers};-use thinkterm_syntax::{HighlightKind, HighlightResult, HighlightSpan};+use thinkterm_syntax::{HighlightKind, HighlightResult, HighlightSpan, LanguageId};+use unicode_segmentation::UnicodeSegmentation;use walkdir::{DirEntry as WalkDirEntry, WalkDir};use wezterm_font::LoadedFont;use window::color::LinearRgba;use window::{- Clipboard, ContextMenuItem, DeadKeyStatus, IntegratedTitleButtonStyle, Point, Rect,- WindowDecorations, WindowOps,+ Clipboard, ContextMenuIcon, ContextMenuItem, DeadKeyStatus, FolderPickerOptions,+ IntegratedTitleButtonStyle, Point, Rect, WindowDecorations, WindowOps,};const RIGHT_SIDEBAR_SECTION_GAP: usize = 12;@@ -78,20 +82,31 @@ const RIGHT_SIDEBAR_SCROLLBAR_VISIBLE_MS: u64 = 900;const SNIPPET_CARET_WIDTH: f32 = 3.0;const NOTE_TOOLBAR_HEIGHT: usize = 54;const NOTE_BODY_TOP_GAP: usize = 12;-const NOTE_BODY_PADDING: usize = 16;+const NOTE_BODY_PADDING: usize = 24;+const NOTE_READING_MAX_WIDTH: usize = 720;const NOTE_LINE_GAP: usize = 5;const NOTE_CARET_WIDTH: f32 = 2.0;const NOTE_TABLE_CELL_HORIZONTAL_PADDING: usize = 10;const NOTE_TABLE_CELL_VERTICAL_PADDING: usize = 7;-const NOTE_TABLE_MIN_COLUMN_WIDTH: usize = 64;+const NOTE_TABLE_MIN_COLUMN_WIDTH: usize = 120;+const NOTE_TABLE_MAX_COLUMN_WIDTH: usize = 480;+const NOTE_TABLE_SCROLLBAR_HEIGHT: usize = 3;const NOTE_CODE_HEADER_HEIGHT: usize = 38;const NOTE_CODE_HORIZONTAL_PADDING: usize = 12;const NOTE_CODE_VERTICAL_PADDING: usize = 9;const NOTE_CODE_CONTROL_SIZE: usize = 28;const NOTE_CODE_BLOCK_RADIUS: f32 = SIDEBAR_ROW_RADIUS;const NOTE_CODE_HIGHLIGHT_CACHE_CAPACITY: usize = 64;-const NOTE_AUTOSAVE_MS: u64 = 300;+const NOTE_CODE_HIGHLIGHT_LAST_BLOCK_CAPACITY: usize = 64;+const NOTE_CODE_HIGHLIGHT_DEBOUNCE_MS: u64 = 120;+const NOTE_CODE_HIGHLIGHT_REPAINT_MS: u64 = 8;+const NOTE_AUTOSAVE_MS: u64 = 500;+const NOTE_SPELLCHECK_DEBOUNCE_MS: u64 = 300;const NOTE_IMAGE_CACHE_CAPACITY: usize = 32;+const NOTE_IMAGE_CACHE_MAX_ENCODED_BYTES: usize = 64 * 1024 * 1024;+const NOTE_VAULT_SPLIT_MIN_WIDTH: usize = 620;+const NOTE_VAULT_TREE_WIDTH: usize = 230;+const NOTE_VAULT_RESCAN_SECS: u64 = 10;const FILE_FONT_MIN_SIZE: f64 = 14.0;const FILE_FILTER_HEIGHT: usize = 66;const FILE_TREE_TOP_GAP: usize = 14;@@ -121,6 +136,7 @@ const FILE_INDEX_ENTRY_LIMIT: usize = 100_000;// How long the file panel must stay closed/idle before its in-memory index and// buffers are released. Reopening within this window keeps everything resident.const FILE_INDEX_IDLE_RELEASE_SECS: u64 = 30;+const NOTE_IDLE_RELEASE_SECS: u64 = 30;// How often the Files panel re-scans the tree while it's visible + focused.const FILE_INDEX_RESCAN_SECS: u64 = 90;// Max number of (root, project) view-state snapshots kept in memory.@@ -161,27 +177,428 @@ fn note_code_row_height(}}+#[derive(Clone, Debug, PartialEq, Eq)]+struct NoteVaultTreeRow {+ relative_path: String,+ name: String,+ depth: usize,+ is_dir: bool,+}++fn note_vault_tree_rows(+ markdown_paths: &[String],+ expanded: &HashSet<String>,+) -> Vec<NoteVaultTreeRow> {+ let mut directories = BTreeSet::new();+ for path in markdown_paths {+ let mut current = PathBuf::new();+ let mut components = Path::new(path).components().peekable();+ while let Some(component) = components.next() {+ if components.peek().is_none() {+ break;+ }+ current.push(component.as_os_str());+ directories.insert(current.to_string_lossy().replace('\\', "/"));+ }+ }++ let mut candidates = directories+ .iter()+ .map(|path| (path.clone(), true))+ .chain(markdown_paths.iter().cloned().map(|path| (path, false)))+ .collect::<Vec<_>>();+ candidates.sort_by(|(left, left_dir), (right, right_dir)| {+ let left_key = left.to_ascii_lowercase();+ let right_key = right.to_ascii_lowercase();+ left_key+ .cmp(&right_key)+ .then_with(|| right_dir.cmp(left_dir))+ });++ candidates+ .into_iter()+ .filter_map(|(relative_path, is_dir)| {+ let path = Path::new(&relative_path);+ let parent_visible = path+ .ancestors()+ .skip(1)+ .filter(|parent| !parent.as_os_str().is_empty())+ .all(|parent| expanded.contains(&parent.to_string_lossy().replace('\\', "/")));+ if !parent_visible {+ return None;+ }+ Some(NoteVaultTreeRow {+ name: path+ .file_name()+ .and_then(|name| name.to_str())+ .unwrap_or(&relative_path)+ .to_string(),+ depth: path.components().count().saturating_sub(1),+ relative_path,+ is_dir,+ })+ })+ .collect()+}++fn visible_code_block_rounded_edges(+ block_top: f32,+ block_bottom: f32,+ viewport_top: f32,+ viewport_bottom: f32,+) -> (bool, bool) {+ (block_top >= viewport_top, block_bottom <= viewport_bottom)+}++fn virtual_note_line_range(+ geometry: &[NoteLineGeometry],+ scroll: f32,+ viewport_height: f32,+) -> std::ops::Range<usize> {+ if geometry.is_empty() || viewport_height <= 0.0 {+ return 0..0;+ }+ let overscan = viewport_height * 2.0;+ let paint_top = (scroll - overscan).max(0.0);+ let paint_bottom = scroll + viewport_height + overscan;+ let start = geometry.partition_point(|line| line.top + line.height + line.gap < paint_top);+ let end = geometry+ .partition_point(|line| line.top <= paint_bottom)+ .min(geometry.len());+ start..end+}++#[derive(Debug, Clone, Copy)]+struct NoteApproximateTextMetrics {+ latin: f32,+ space: f32,+ wide: f32,+}++fn approximate_note_text_width(text: &str, metrics: NoteApproximateTextMetrics) -> f32 {+ text.graphemes(true)+ .map(|grapheme| {+ if grapheme.chars().all(char::is_whitespace) {+ metrics.space+ } else if grapheme.is_ascii() {+ metrics.latin+ } else if unicode_width::UnicodeWidthStr::width(grapheme) >= 2 {+ metrics.wide+ } else {+ metrics.latin+ }+ })+ .sum()+}+#[derive(Debug, Clone)]struct NoteTableRowPaintLayout {+ table_start: usize,column_widths: Rc<Vec<f32>>,alignments: Rc<Vec<TableAlignment>>,row_index: usize,row_count: usize,+ total_width: f32,+ horizontal_offset: f32,+ max_horizontal_scroll: f32,+}++fn scrollable_note_table_columns(+ desired: &[f32],+ available_width: f32,+ minimum_width: f32,+ maximum_width: f32,+) -> Vec<f32> {+ if desired.is_empty() {+ return Vec::new();+ }+ let available_width = available_width.max(1.0);+ let minimum_width = minimum_width.max(1.0);+ let maximum_width = maximum_width.max(minimum_width);+ let widths = desired+ .iter()+ .map(|width| width.clamp(minimum_width, maximum_width))+ .collect::<Vec<_>>();+ let total = widths.iter().sum::<f32>();+ if total < available_width {+ fit_table_columns(&widths, available_width, minimum_width)+ } else {+ widths+ }+}++fn note_image_display_size(+ image_width: u32,+ image_height: u32,+ available_width: f32,+ available_height: f32,+) -> (f32, f32) {+ if image_width == 0 || image_height == 0 || available_width <= 0.0 || available_height <= 0.0 {+ return (0.0, 0.0);+ }++ // Markdown images should be useful at reading distance, including small+ // logos and diagrams. Allow moderate upscaling while bounding both axes;+ // giant/tall images remain contained inside the current viewport.+ const MAX_UPSCALE: f32 = 3.0;+ let scale = (available_width / image_width as f32)+ .min(available_height / image_height as f32)+ .min(MAX_UPSCALE);+ (+ (image_width as f32 * scale).max(1.0),+ (image_height as f32 * scale).max(1.0),+ )+}++fn note_image_row_height(+ image: Option<&RightSidebarFilePreviewImage>,+ text_height: f32,+ available_width: f32,+ available_height: f32,+) -> f32 {+ image+ .map(|image| {+ note_image_display_size(image.width, image.height, available_width, available_height).1+ })+ .unwrap_or(text_height)+ .max(text_height)+}++#[derive(Debug, Clone, Copy, PartialEq)]+struct NoteTextureClip {+ left: f32,+ top: f32,+ right: f32,+ bottom: f32,+ texture_left: f32,+ texture_top: f32,+ texture_right: f32,+ texture_bottom: f32,+}++#[allow(clippy::too_many_arguments)]+fn clip_note_texture(+ left: f32,+ top: f32,+ right: f32,+ bottom: f32,+ texture_left: f32,+ texture_top: f32,+ texture_right: f32,+ texture_bottom: f32,+ clip_left: f32,+ clip_top: f32,+ clip_right: f32,+ clip_bottom: f32,+) -> Option<NoteTextureClip> {+ let width = right - left;+ let height = bottom - top;+ if width <= 0.0+ || height <= 0.0+ || texture_right <= texture_left+ || texture_bottom <= texture_top+ || clip_right <= clip_left+ || clip_bottom <= clip_top+ {+ return None;+ }+ let visible_left = left.max(clip_left);+ let visible_top = top.max(clip_top);+ let visible_right = right.min(clip_right);+ let visible_bottom = bottom.min(clip_bottom);+ if visible_right <= visible_left || visible_bottom <= visible_top {+ return None;+ }+ let texture_width = texture_right - texture_left;+ let texture_height = texture_bottom - texture_top;+ Some(NoteTextureClip {+ left: visible_left,+ top: visible_top,+ right: visible_right,+ bottom: visible_bottom,+ texture_left: texture_left + texture_width * ((visible_left - left) / width),+ texture_top: texture_top + texture_height * ((visible_top - top) / height),+ texture_right: texture_left + texture_width * ((visible_right - left) / width),+ texture_bottom: texture_top + texture_height * ((visible_bottom - top) / height),+ })+}++fn note_open_pending_for_vault(opening: Option<&(PathBuf, String)>, vault_root: &Path) -> bool {+ opening.is_some_and(|(root, _)| root == vault_root)}#[derive(Debug, Clone)]struct NoteCodeRowPaintLayout {block_start: usize,language: String,+ code: Arc<ProjectedCodeBlock>,row_index: usize,row_count: usize,collapsed: bool,- colors: Arc<Vec<Vec<LinearRgba>>>,horizontal_offset: f32,block_height: f32,max_horizontal_scroll: f32,}+/// Immutable component geometry for one visual/layout revision. Vertical+/// scrolling only clones these Arcs; it must not clone the full Markdown+/// projection or remeasure every table/code cell on every frame.+#[derive(Default)]+pub(crate) struct NotePaintCache {+ key: Option<u64>,+ table_rows: Arc<HashMap<usize, NoteTableRowPaintLayout>>,+ code_rows: Arc<HashMap<usize, NoteCodeRowPaintLayout>>,+ image_sources: Arc<HashMap<usize, RightSidebarNoteImageSource>>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub(crate) struct NoteCodeHighlightKey {+ language: LanguageId,+ content_hash: u64,+ content_len: usize,+}++#[derive(Debug)]+struct NoteCodeHighlightEntry {+ key: NoteCodeHighlightKey,+ source: Arc<str>,+ light: Arc<Vec<Vec<LinearRgba>>>,+ dark: Arc<Vec<Vec<LinearRgba>>>,+}++impl NoteCodeHighlightEntry {+ fn colors(&self, use_dark_theme: bool) -> Arc<Vec<Vec<LinearRgba>>> {+ if use_dark_theme {+ Arc::clone(&self.dark)+ } else {+ Arc::clone(&self.light)+ }+ }+}++#[derive(Default)]+pub(crate) struct NoteCodeHighlightState {+ cache: HashMap<NoteCodeHighlightKey, Arc<NoteCodeHighlightEntry>>,+ cache_order: VecDeque<NoteCodeHighlightKey>,+ last_by_block: HashMap<usize, Arc<NoteCodeHighlightEntry>>,+ last_block_order: VecDeque<usize>,+ scheduled: HashMap<usize, (NoteCodeHighlightKey, u64)>,+ in_flight: HashMap<usize, (NoteCodeHighlightKey, Arc<AtomicUsize>)>,+ next_generation: u64,+ repaint_scheduled: bool,+}++impl NoteCodeHighlightState {+ fn cached(+ &self,+ key: NoteCodeHighlightKey,+ source: &str,+ ) -> Option<Arc<NoteCodeHighlightEntry>> {+ self.cache+ .get(&key)+ .filter(|entry| entry.source.as_ref() == source)+ .cloned()+ }++ fn insert_cache(&mut self, entry: Arc<NoteCodeHighlightEntry>) {+ let key = entry.key;+ if !self.cache.contains_key(&key) {+ self.cache_order.push_back(key);+ }+ self.cache.insert(key, entry);+ while self.cache_order.len() > NOTE_CODE_HIGHLIGHT_CACHE_CAPACITY {+ if let Some(expired) = self.cache_order.pop_front() {+ self.cache.remove(&expired);+ }+ }+ }++ fn remember_block(&mut self, block_start: usize, entry: Arc<NoteCodeHighlightEntry>) {+ self.last_block_order.retain(|start| *start != block_start);+ self.last_block_order.push_back(block_start);+ self.last_by_block.insert(block_start, entry);+ while self.last_block_order.len() > NOTE_CODE_HIGHLIGHT_LAST_BLOCK_CAPACITY {+ if let Some(expired) = self.last_block_order.pop_front() {+ self.last_by_block.remove(&expired);+ }+ }+ }++ fn previous_for_block(+ &self,+ block_start: usize,+ language: LanguageId,+ ) -> Option<Arc<NoteCodeHighlightEntry>> {+ self.last_by_block+ .get(&block_start)+ .filter(|entry| entry.key.language == language)+ .cloned()+ }++ fn schedule_block(&mut self, block_start: usize, key: NoteCodeHighlightKey) -> Option<u64> {+ if self+ .scheduled+ .get(&block_start)+ .is_some_and(|(scheduled, _)| *scheduled == key)+ || self+ .in_flight+ .get(&block_start)+ .is_some_and(|(pending, _)| *pending == key)+ {+ return None;+ }+ self.scheduled.remove(&block_start);+ if let Some((_, cancellation)) = self.in_flight.remove(&block_start) {+ cancellation.store(1, AtomicOrdering::Relaxed);+ }+ self.next_generation = self.next_generation.wrapping_add(1).max(1);+ let generation = self.next_generation;+ self.scheduled.insert(block_start, (key, generation));+ Some(generation)+ }++ fn cancel_block_work(&mut self, block_start: usize) {+ self.scheduled.remove(&block_start);+ if let Some((_, cancellation)) = self.in_flight.remove(&block_start) {+ cancellation.store(1, AtomicOrdering::Relaxed);+ }+ }++ fn retain_blocks(&mut self, current: &HashSet<usize>) {+ let removed = self+ .scheduled+ .keys()+ .chain(self.in_flight.keys())+ .chain(self.last_by_block.keys())+ .copied()+ .filter(|start| !current.contains(start))+ .collect::<HashSet<_>>();+ for block_start in removed {+ self.cancel_block_work(block_start);+ self.last_by_block.remove(&block_start);+ }+ self.last_block_order+ .retain(|start| current.contains(start));+ }+}++fn note_code_highlight_key(code: &ProjectedCodeBlock) -> Option<NoteCodeHighlightKey> {+ if code.text.len() > thinkterm_syntax::DEFAULT_HIGHLIGHT_BYTE_LIMIT {+ return None;+ }+ let language = code+ .language+ .as_deref()+ .and_then(thinkterm_syntax::detect_fence)?;+ let mut hasher = DefaultHasher::new();+ code.text.hash(&mut hasher);+ Some(NoteCodeHighlightKey {+ language,+ content_hash: hasher.finish(),+ content_len: code.text.len(),+ })+}+#[derive(Debug, Clone, Copy)]pub struct RightSidebarRect {pub x: usize,@@ -540,14 +957,23 @@ impl crate::TermWindow {self.clear_right_sidebar_text_focus();}self.schedule_right_sidebar_file_memory_release();+ self.schedule_right_sidebar_note_memory_release();} else {self.kick_right_sidebar_file_rescan_cycle();+ if self.right_sidebar_mode == RightSidebarMode::Tasks {+ self.right_sidebar_note_memory_release_token =+ self.right_sidebar_note_memory_release_token.wrapping_add(1);+ }}}pub fn expand_right_sidebar(&mut self) {self.right_sidebar_collapsed = false;self.kick_right_sidebar_file_rescan_cycle();+ if self.right_sidebar_mode == RightSidebarMode::Tasks {+ self.right_sidebar_note_memory_release_token =+ self.right_sidebar_note_memory_release_token.wrapping_add(1);+ }}/// The file panel (and its in-memory index) is only relevant while the right@@ -611,6 +1037,67 @@ impl crate::TermWindow {self.invalidate_window();}+ /// Notes are entirely lazy at runtime: once the panel stays hidden, drop+ /// source/projection/wrap/highlight/image/index state. The persisted active+ /// path is enough to reopen it; no polling or worker remains owned by the+ /// feature while it is unused.+ pub(crate) fn schedule_right_sidebar_note_memory_release(&mut self) {+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ self.right_sidebar_note_memory_release_token =+ self.right_sidebar_note_memory_release_token.wrapping_add(1);+ let token = self.right_sidebar_note_memory_release_token;+ let target = Instant::now() + Duration::from_secs(NOTE_IDLE_RELEASE_SECS);+ promise::spawn::spawn(async move {+ smol::Timer::at(target).await;+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.release_right_sidebar_note_memory_if_idle(token);+ })));+ })+ .detach();+ }++ fn release_right_sidebar_note_memory_if_idle(&mut self, token: u64) {+ if token != self.right_sidebar_note_memory_release_token+ || self.right_sidebar_note_visible()+ {+ return;+ }+ if self+ .right_sidebar_note+ .session+ .as_ref()+ .is_some_and(|session| session.lock().is_dirty())+ {+ self.save_right_sidebar_note_now();+ self.schedule_right_sidebar_note_memory_release();+ return;+ }++ self.right_sidebar_note_open_generation =+ self.right_sidebar_note_open_generation.wrapping_add(1);+ self.right_sidebar_note_vault_index_generation = self+ .right_sidebar_note_vault_index_generation+ .wrapping_add(1);+ self.right_sidebar_note = crate::markdown_editor::NoteHostState::default();+ self.right_sidebar_note_opening = None;+ self.right_sidebar_note_open_failure = None;+ self.right_sidebar_note_vault_index_root = None;+ self.right_sidebar_note_vault_paths = Arc::new(Vec::new());+ self.right_sidebar_note_vault_indexing = false;+ self.right_sidebar_note_vault_last_scan = None;+ self.right_sidebar_note_tree_expanded.clear();+ self.right_sidebar_note_table_horizontal_offsets.clear();+ self.right_sidebar_note_table_layouts.clear();+ self.right_sidebar_note_images.clear();+ self.right_sidebar_note_images_loading.clear();+ self.right_sidebar_note_image_order.clear();+ self.right_sidebar_note_image_failures.clear();+ self.right_sidebar_note_code_highlight = NoteCodeHighlightState::default();+ self.right_sidebar_note_paint_cache = NotePaintCache::default();+ }+fn right_sidebar_file_view_state_key(&self) -> Option<(PathBuf, String)> {self.right_sidebar_file_index_root.clone()@@ -712,11 +1199,20 @@ impl crate::TermWindow {self.right_sidebar_file_focus = None;self.right_sidebar_note.view.focused = false;if note_was_focused {+ self.right_sidebar_note.native_text_input_snapshot_key = None;+ if let Some(window) = self.window.as_ref() {+ window.set_native_text_input_snapshot(None);+ }+ self.right_sidebar_note.freeze_live_source();self.save_right_sidebar_note_now();}}pub(crate) fn open_new_snippet_editor(&mut self) {+ if self.right_sidebar_mode == RightSidebarMode::Tasks {+ self.clear_right_sidebar_text_focus();+ self.schedule_right_sidebar_note_memory_release();+ }self.right_sidebar_mode = RightSidebarMode::Snippets;self.right_sidebar_snippet_view = RightSidebarSnippetView::EditNew;self.right_sidebar_snippet_scroll_offset = 0.0;@@ -729,6 +1225,10 @@ impl crate::TermWindow {let Some(snippet) = crate::snippets::get_snippet(id) else {return;};+ if self.right_sidebar_mode == RightSidebarMode::Tasks {+ self.clear_right_sidebar_text_focus();+ self.schedule_right_sidebar_note_memory_release();+ }self.right_sidebar_mode = RightSidebarMode::Snippets;self.right_sidebar_snippet_view = RightSidebarSnippetView::EditExisting(snippet.id);self.right_sidebar_snippet_scroll_offset = 0.0;@@ -809,47 +1309,18 @@ impl crate::TermWindow {(old - self.right_sidebar_snippet_scroll_offset).abs() > f32::EPSILON}- pub(crate) fn scroll_right_sidebar_files(&mut self, amount: i16) -> bool {- if self.right_sidebar_collapsed- || self.right_sidebar_mode != RightSidebarMode::Chat- || amount == 0- {- return false;- }-+ pub(crate) fn scroll_right_sidebar_files_by(&mut self, delta: f32) -> bool {let old = self.right_sidebar_file_tree_scroll_offset;- let steps = amount.unsigned_abs().max(1) as f32;- let delta = (steps * 14.0).min(98.0);- if amount < 0 {- self.right_sidebar_file_tree_scroll_offset += delta;- } else {- self.right_sidebar_file_tree_scroll_offset =- (self.right_sidebar_file_tree_scroll_offset - delta).max(0.0);- }+ self.right_sidebar_file_tree_scroll_offset =+ (self.right_sidebar_file_tree_scroll_offset + delta).max(0.0);(old - self.right_sidebar_file_tree_scroll_offset).abs() > f32::EPSILON}- pub(crate) fn scroll_right_sidebar_file_preview(&mut self, amount: i16) -> bool {- if self.right_sidebar_collapsed- || self.right_sidebar_mode != RightSidebarMode::Chat- || self.right_sidebar_file_view != RightSidebarFileView::Preview- || self.right_sidebar_file_selected.is_none()- || amount == 0- {- return false;- }-+ pub(crate) fn scroll_right_sidebar_file_preview_by(&mut self, delta: f32) -> bool {let old = self.right_sidebar_file_preview_scroll_offset;let max = self.right_sidebar_file_preview_scroll_max();- let steps = amount.unsigned_abs().max(1) as f32;- let delta = (steps * 14.0).min(98.0);- if amount < 0 {- self.right_sidebar_file_preview_scroll_offset =- (self.right_sidebar_file_preview_scroll_offset + delta).clamp(0.0, max);- } else {- self.right_sidebar_file_preview_scroll_offset =- (self.right_sidebar_file_preview_scroll_offset - delta).clamp(0.0, max);- }+ self.right_sidebar_file_preview_scroll_offset =+ (self.right_sidebar_file_preview_scroll_offset + delta).clamp(0.0, max);(old - self.right_sidebar_file_preview_scroll_offset).abs() > f32::EPSILON}@@ -1026,90 +1497,178 @@ impl crate::TermWindow {code: &ProjectedCodeBlock,use_dark_theme: bool,) -> Arc<Vec<Vec<LinearRgba>>> {- let revision = self.right_sidebar_note.projection_revision.unwrap_or(0);- if self.right_sidebar_note_code_highlight_revision != revision {- self.right_sidebar_note_code_highlight_cancel- .store(1, AtomicOrdering::Relaxed);- self.right_sidebar_note_code_highlight_cancel = Arc::new(AtomicUsize::new(0));- self.right_sidebar_note_code_highlight_revision = revision;- self.right_sidebar_note_code_highlights_pending.clear();- }-- let key = (revision, code.source.start, use_dark_theme);- if let Some(lines) = self.right_sidebar_note_code_highlights.get(&key).cloned() {- return lines;- }-- let lines = Arc::new(vec![vec![]; note_code_line_count(&code.text)]);- self.insert_note_code_highlight_cache(key, Arc::clone(&lines));-- let supported = code.text.len() <= thinkterm_syntax::DEFAULT_HIGHLIGHT_BYTE_LIMIT- && code- .language- .as_deref()- .and_then(thinkterm_syntax::detect_fence)- .is_some();- let pending_key = (revision, code.source.start);- if supported- && self- .right_sidebar_note_code_highlights_pending- .insert(pending_key)+ let Some(key) = note_code_highlight_key(code) else {+ return Arc::new(vec![vec![]; note_code_line_count(&code.text)]);+ };+ if let Some(entry) = self+ .right_sidebar_note_code_highlight+ .cached(key, &code.text)+ {+ self.right_sidebar_note_code_highlight+ .cancel_block_work(code.source.start);+ self.right_sidebar_note_code_highlight+ .remember_block(code.source.start, Arc::clone(&entry));+ return entry.colors(use_dark_theme);+ }++ let previous = self+ .right_sidebar_note_code_highlight+ .previous_for_block(code.source.start, key.language);+ if let Some(generation) = self+ .right_sidebar_note_code_highlight+ .schedule_block(code.source.start, key){if let Some(window) = self.window.as_ref().cloned() {let code = code.clone();- let cancellation = Arc::clone(&self.right_sidebar_note_code_highlight_cancel);- syntax_highlight_pool().spawn(move || {- let result = note_code_highlight_pair(&code, Some(cancellation.as_ref()));+ promise::spawn::spawn(async move {+ smol::Timer::after(Duration::from_millis(NOTE_CODE_HIGHLIGHT_DEBOUNCE_MS))+ .await;window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {- term_window.apply_note_code_highlight_result(pending_key, result);+ term_window.start_note_code_highlight(+ code.source.start,+ key,+ generation,+ code,+ );})));- });+ })+ .detach();} else {- self.right_sidebar_note_code_highlights_pending- .remove(&pending_key);+ self.right_sidebar_note_code_highlight+ .scheduled+ .remove(&code.source.start);}}- lines+ previous+ .map(|entry| entry.colors(use_dark_theme))+ .unwrap_or_else(|| Arc::new(vec![vec![]; note_code_line_count(&code.text)]))+ }++ fn current_note_code_matches(+ &self,+ block_start: usize,+ key: NoteCodeHighlightKey,+ source: &str,+ ) -> bool {+ self.right_sidebar_note+ .projection+ .objects+ .iter()+ .find_map(|object| match object {+ ProjectedObject::CodeBlock(code) if code.source.start == block_start => Some(code),+ _ => None,+ })+ .is_some_and(|code| {+ note_code_highlight_key(code) == Some(key) && code.text.as_str() == source+ })}- fn insert_note_code_highlight_cache(+ fn start_note_code_highlight(&mut self,- key: (u64, usize, bool),- lines: Arc<Vec<Vec<LinearRgba>>>,+ block_start: usize,+ key: NoteCodeHighlightKey,+ generation: u64,+ code: ProjectedCodeBlock,) {- if !self.right_sidebar_note_code_highlights.contains_key(&key) {- self.right_sidebar_note_code_highlight_order.push_back(key);+ if self+ .right_sidebar_note_code_highlight+ .scheduled+ .get(&block_start)+ .copied()+ != Some((key, generation))+ {+ return;}- self.right_sidebar_note_code_highlights.insert(key, lines);- while self.right_sidebar_note_code_highlight_order.len()- > NOTE_CODE_HIGHLIGHT_CACHE_CAPACITY+ self.right_sidebar_note_code_highlight+ .scheduled+ .remove(&block_start);+ if !self.current_note_code_matches(block_start, key, &code.text) {+ return;+ }+ if let Some(entry) = self+ .right_sidebar_note_code_highlight+ .cached(key, &code.text){- if let Some(expired) = self.right_sidebar_note_code_highlight_order.pop_front() {- self.right_sidebar_note_code_highlights.remove(&expired);- }+ self.right_sidebar_note_code_highlight+ .remember_block(block_start, entry);+ self.schedule_note_code_highlight_repaint();+ return;}+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ let cancellation = Arc::new(AtomicUsize::new(0));+ self.right_sidebar_note_code_highlight+ .in_flight+ .insert(block_start, (key, Arc::clone(&cancellation)));+ let source: Arc<str> = Arc::from(code.text.as_str());+ syntax_highlight_pool().spawn(move || {+ let stage = crate::input_diagnostics::StageTimer::begin("note_highlight");+ let result = note_code_highlight_pair(&code, Some(cancellation.as_ref()));+ stage.finish(result.is_some());+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.apply_note_code_highlight_result(block_start, key, source, result);+ })));+ });}fn apply_note_code_highlight_result(&mut self,- pending_key: (u64, usize),+ block_start: usize,+ key: NoteCodeHighlightKey,+ source: Arc<str>,result: Option<(Vec<Vec<LinearRgba>>, Vec<Vec<LinearRgba>>)>,) {- self.right_sidebar_note_code_highlights_pending- .remove(&pending_key);- if self.right_sidebar_note.projection_revision.unwrap_or(0) != pending_key.0 {- return;+ if self+ .right_sidebar_note_code_highlight+ .in_flight+ .get(&block_start)+ .is_some_and(|(pending, _)| *pending == key)+ {+ self.right_sidebar_note_code_highlight+ .in_flight+ .remove(&block_start);}let Some((light, dark)) = result else {return;};- self.insert_note_code_highlight_cache(- (pending_key.0, pending_key.1, false),- Arc::new(light),- );- self.insert_note_code_highlight_cache((pending_key.0, pending_key.1, true), Arc::new(dark));- self.invalidate_window();+ let current_matches = self.current_note_code_matches(block_start, key, &source);+ let entry = Arc::new(NoteCodeHighlightEntry {+ key,+ source,+ light: Arc::new(light),+ dark: Arc::new(dark),+ });+ self.right_sidebar_note_code_highlight+ .insert_cache(Arc::clone(&entry));+ if current_matches {+ self.right_sidebar_note_code_highlight+ .remember_block(block_start, entry);+ self.schedule_note_code_highlight_repaint();+ }+ }++ fn schedule_note_code_highlight_repaint(&mut self) {+ if self.right_sidebar_note_code_highlight.repaint_scheduled {+ return;+ }+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ self.right_sidebar_note_code_highlight.repaint_scheduled = true;+ promise::spawn::spawn(async move {+ smol::Timer::after(Duration::from_millis(NOTE_CODE_HIGHLIGHT_REPAINT_MS)).await;+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window+ .right_sidebar_note_code_highlight+ .repaint_scheduled = false;+ if term_window.right_sidebar_note_visible() {+ term_window.invalidate_window();+ }+ })));+ })+ .detach();}/// Per-byte colours for a whole preview line, keyed by (generation, line@@ -1274,29 +1833,29 @@ impl crate::TermWindow {if !path.is_dir() {items.push(ContextMenuItem::item_with_icon("Open",- "arrow.up.forward.app",+ ContextMenuIcon::ExternalLink,KeyAssignment::OpenFileWithSystemDefault(path_string.clone()),));}items.push(ContextMenuItem::item_with_icon(- "Reveal in Folder",- "folder",+ super::context_menu::reveal_in_folder_label(),+ ContextMenuIcon::Folder,KeyAssignment::RevealFileInFolder(path_string.clone()),));items.push(ContextMenuItem::item_with_icon("Copy Path",- "doc.on.doc",+ ContextMenuIcon::Copy,KeyAssignment::CopyFilePathToClipboard(path_string.clone()),));items.push(ContextMenuItem::Separator);items.push(ContextMenuItem::item_with_icon("Rename...",- "pencil",+ ContextMenuIcon::Edit,KeyAssignment::RenameSidebarFile(path_string.clone()),));items.push(ContextMenuItem::item_with_icon("Move to Trash",- "trash",+ ContextMenuIcon::Delete,KeyAssignment::TrashSidebarFile(path_string),));items@@ -1419,7 +1978,7 @@ impl crate::TermWindow {.map(|candidate| {ContextMenuItem::item_with_icon(format!("Open With {}", candidate.label),- "app",+ ContextMenuIcon::Application,KeyAssignment::OpenFileWith {path: path_string.clone(),app: candidate.id,@@ -1434,7 +1993,7 @@ impl crate::TermWindow {}items.push(ContextMenuItem::item_with_icon("Open With Other…",- "app",+ ContextMenuIcon::Application,KeyAssignment::PickOpenFileWithApp(path_string),));items@@ -1553,11 +2112,7 @@ impl crate::TermWindow {text.push_str(&preview_text_range(&line.plain, line_start, line_end));}}- if text.is_empty() {- None- } else {- Some(text)- }+ if text.is_empty() { None } else { Some(text) }}fn right_sidebar_file_preview_selection_range(@@ -2127,31 +2682,436 @@ impl crate::TermWindow {}}- pub(crate) fn cut_right_sidebar_focused_input(&mut self) {- if self.right_sidebar_mode == RightSidebarMode::Tasks {- let Some(session) = self.right_sidebar_note.session.clone() else {- return;- };- let selected = session- .lock()- .selected_text(&self.right_sidebar_note.view)- .map(str::to_string);- if let Some(text) = selected {- if session.lock().backspace(&mut self.right_sidebar_note.view) {- self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, text);- self.note_did_edit();+ pub(crate) fn perform_right_sidebar_note_command(&mut self, command: NoteEditorCommand) {+ match command {+ NoteEditorCommand::Undo => {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ if session.lock().undo(&mut self.right_sidebar_note.view) {+ self.note_did_edit();+ }}}- return;- }- let Some(input) = self.right_sidebar_focused_input_mut() else {- return;- };- let text = if let Some(text) = input.caret_take_selected_text() {- text- } else {- let text = input.text.clone();- input.clear();+ NoteEditorCommand::Redo => {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ if session.lock().redo(&mut self.right_sidebar_note.view) {+ self.note_did_edit();+ }+ }+ }+ NoteEditorCommand::Cut => self.cut_right_sidebar_focused_input(),+ NoteEditorCommand::Copy => {+ self.copy_right_sidebar_focused_input(ClipboardCopyDestination::Clipboard)+ }+ NoteEditorCommand::Paste => {+ self.paste_into_right_sidebar_from_clipboard(ClipboardPasteSource::Clipboard)+ }+ NoteEditorCommand::Delete => {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ if session+ .lock()+ .delete_selection(&mut self.right_sidebar_note.view)+ {+ self.note_did_edit();+ }+ }+ }+ NoteEditorCommand::SelectAll => {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ session.lock().select_all(&mut self.right_sidebar_note.view);+ self.right_sidebar_note.refresh_projection();+ }+ }+ NoteEditorCommand::ReplaceSpelling {+ revision,+ range,+ replacement,+ } => {+ if let Some(session) = self.right_sidebar_note.session.clone() {+ if session.lock().replace_range_at_revision(+ &mut self.right_sidebar_note.view,+ revision,+ range,+ &replacement,+ ) {+ self.note_did_edit();+ }+ }+ }+ NoteEditorCommand::IgnoreSpelling { word } => {+ self.ignore_right_sidebar_note_spelling(&word);+ }+ NoteEditorCommand::LearnSpelling { word } => {+ self.learn_right_sidebar_note_spelling(&word);+ }+ NoteEditorCommand::LookUp { text, anchor } => {+ if let Some(window) = self.window.as_ref() {+ window.show_text_definition(&text, anchor);+ }+ }+ NoteEditorCommand::ToggleSourceMode => self.toggle_right_sidebar_note_mode(),+ NoteEditorCommand::Save => self.save_right_sidebar_note_now(),+ NoteEditorCommand::ChooseVault { managed } => {+ self.choose_right_sidebar_note_vault(managed)+ }+ NoteEditorCommand::NewNote => self.create_right_sidebar_note(),+ NoteEditorCommand::OpenNote { relative_path } => {+ self.activate_right_sidebar_note_tree_path(&relative_path)+ }+ NoteEditorCommand::RevealVault => {+ if let Some(vault) = workspace_threads::space_note_vault(&self.active_space_id) {+ wezterm_open_url::reveal_path(&vault.root);+ }+ }+ NoteEditorCommand::ToggleVaultTree => self.toggle_right_sidebar_note_vault_tree(),+ }+ }++ pub(crate) fn toggle_right_sidebar_note_vault_tree(&mut self) {+ if self.right_sidebar_note_wide_layout {+ self.right_sidebar_note_vault_tree_collapsed =+ !self.right_sidebar_note_vault_tree_collapsed;+ } else {+ self.right_sidebar_note_view = match self.right_sidebar_note_view {+ RightSidebarNoteView::Tree => RightSidebarNoteView::Editor,+ RightSidebarNoteView::Editor => RightSidebarNoteView::Tree,+ };+ }+ self.right_sidebar_note_tree_scroll_offset = 0.0;+ }++ fn choose_right_sidebar_note_vault(&mut self, managed: bool) {+ let Some(window) = self.window.clone() else {+ return;+ };+ let space_id = self.active_space_id.clone();+ let notify_window = window.clone();+ let options = if managed {+ FolderPickerOptions {+ title: "Create Vault".to_string(),+ prompt: "Create".to_string(),+ }+ } else {+ FolderPickerOptions {+ title: "Choose Vault".to_string(),+ prompt: "Choose".to_string(),+ }+ };+ window.pick_folder_async_with_options(+ options,+ Box::new(move |path| {+ let Some(path) = path else {+ return;+ };+ let result = workspace_threads::set_space_note_vault(&space_id, path, managed);+ notify_window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.right_sidebar_note_open_generation = term_window+ .right_sidebar_note_open_generation+ .wrapping_add(1);+ term_window.right_sidebar_note_opening = None;+ term_window.right_sidebar_note_open_failure = None;+ match result {+ Ok(_) => term_window.right_sidebar_note.clear_document(None),+ Err(err) => term_window+ .right_sidebar_note+ .clear_document(Some(format!("{err:#}"))),+ }+ term_window.invalidate_window();+ })));+ }),+ );+ }++ fn create_right_sidebar_note(&mut self) {+ let Some(vault) = workspace_threads::space_note_vault(&self.active_space_id) else {+ return;+ };+ let Some(project_id) =+ workspace_threads::active_project_id_for_space(&self.active_space_id)+ else {+ return;+ };+ let existing = vault_markdown_paths(&vault.root).unwrap_or_default();+ let existing = existing+ .into_iter()+ .map(|path| path.to_ascii_lowercase())+ .collect::<HashSet<_>>();+ let mut sequence = 1usize;+ let relative_path = loop {+ let candidate = if sequence == 1 {+ "Untitled.md".to_string()+ } else {+ format!("Untitled {sequence}.md")+ };+ if !existing.contains(&candidate.to_ascii_lowercase()) {+ break candidate;+ }+ sequence += 1;+ };+ self.right_sidebar_note_open_failure = None;+ self.request_right_sidebar_note_open(vault.root, relative_path, true, project_id, true);+ }++ pub(crate) fn activate_right_sidebar_note_tree_path(&mut self, relative_path: &str) {+ let Some(vault) = workspace_threads::space_note_vault(&self.active_space_id) else {+ return;+ };+ let candidate = vault.root.join(relative_path);+ if candidate.is_dir() {+ if !self.right_sidebar_note_tree_expanded.remove(relative_path) {+ self.right_sidebar_note_tree_expanded+ .insert(relative_path.to_string());+ }+ return;+ }+ if candidate+ .extension()+ .and_then(|extension| extension.to_str())+ .is_none_or(|extension| !extension.eq_ignore_ascii_case("md"))+ {+ let safe_candidate = candidate.canonicalize().ok().filter(|candidate| {+ vault+ .root+ .canonicalize()+ .is_ok_and(|root| candidate.starts_with(root))+ });+ let Some(candidate) = safe_candidate else {+ self.right_sidebar_note.load_error =+ Some(format!("Vault file is unavailable: {relative_path}"));+ return;+ };+ match url::Url::from_file_path(&candidate) {+ Ok(url) => wezterm_open_url::open_url(url.as_str()),+ Err(()) => {+ self.right_sidebar_note.load_error =+ Some(format!("Unable to open {}", candidate.display()));+ }+ }+ return;+ }+ let Some(project_id) =+ workspace_threads::active_project_id_for_space(&self.active_space_id)+ else {+ return;+ };+ self.right_sidebar_note_open_failure = None;+ self.request_right_sidebar_note_open(+ vault.root,+ relative_path.to_string(),+ false,+ project_id,+ false,+ );+ }++ pub(crate) fn activate_or_create_right_sidebar_wiki_link(+ &mut self,+ target: &str,+ resolved_path: Option<&str>,+ ) {+ if let Some(path) = resolved_path {+ self.activate_right_sidebar_note_tree_path(path);+ return;+ }+ let Some(document) = self.right_sidebar_note.document.clone() else {+ return;+ };+ let target = target.split(['#', '^']).next().unwrap_or(target).trim();+ if target.is_empty() {+ return;+ }+ let mut relative = Path::new(&document.relative_path)+ .parent()+ .unwrap_or_else(|| Path::new(""))+ .join(target);+ if relative.extension().is_none() {+ relative.set_extension("md");+ }+ let relative = relative.to_string_lossy().replace('\\', "/");+ let relative = match workspace_threads::normalize_vault_markdown_path(&relative) {+ Ok(relative) => relative,+ Err(err) => {+ self.right_sidebar_note.load_error = Some(format!("{err:#}"));+ return;+ }+ };+ let Some(project_id) =+ workspace_threads::active_project_id_for_space(&self.active_space_id)+ else {+ return;+ };+ self.right_sidebar_note_vault_last_scan = None;+ self.right_sidebar_note_open_failure = None;+ self.request_right_sidebar_note_open(+ document.vault_root,+ relative,+ true,+ project_id,+ false,+ );+ }++ pub(crate) fn show_right_sidebar_note_wiki_link_choices(+ &mut self,+ context: &dyn WindowOps,+ anchor: window::Point,+ candidates: Vec<String>,+ ) {+ self.begin_context_menu_application_actions();+ let items = candidates+ .into_iter()+ .map(|relative_path| {+ self.context_menu_application_item_with_icon(+ relative_path.clone(),+ ContextMenuIcon::File,+ crate::termwindow::ContextMenuApplicationAction::Note(+ NoteEditorCommand::OpenNote { relative_path },+ ),+ true,+ )+ })+ .collect();+ self.show_term_context_menu(context, anchor, items);+ }++ pub(crate) fn show_right_sidebar_note_menu(+ &mut self,+ context: &dyn WindowOps,+ anchor: window::Point,+ ) {+ self.begin_context_menu_application_actions();+ let source_mode = self.right_sidebar_note.view.mode == EditorMode::Source;+ let save_enabled = !matches!(+ self.right_sidebar_note.display_save_state(),+ SaveState::Saved | SaveState::Saving(_)+ );+ let mut source_item = self.context_menu_application_item_with_icon(+ "Source Mode",+ ContextMenuIcon::Code,+ crate::termwindow::ContextMenuApplicationAction::Note(+ NoteEditorCommand::ToggleSourceMode,+ ),+ true,+ );+ source_item = source_item.checked(source_mode);+ let vault_tree_label = if self.right_sidebar_note_wide_layout {+ if self.right_sidebar_note_vault_tree_collapsed {+ "Show Vault Sidebar"+ } else {+ "Hide Vault Sidebar"+ }+ } else if self.right_sidebar_note_view == RightSidebarNoteView::Tree {+ "Hide Vault"+ } else {+ "Show Vault"+ };+ let items = vec![+ self.context_menu_application_item_with_icon(+ "New Note",+ ContextMenuIcon::Note,+ crate::termwindow::ContextMenuApplicationAction::Note(NoteEditorCommand::NewNote),+ true,+ ),+ self.context_menu_application_item_with_icon(+ "Save",+ ContextMenuIcon::Save,+ crate::termwindow::ContextMenuApplicationAction::Note(NoteEditorCommand::Save),+ save_enabled,+ ),+ source_item,+ self.context_menu_application_item_with_icon(+ vault_tree_label,+ ContextMenuIcon::Sidebar,+ crate::termwindow::ContextMenuApplicationAction::Note(+ NoteEditorCommand::ToggleVaultTree,+ ),+ true,+ ),+ ContextMenuItem::Separator,+ self.context_menu_application_item_with_icon(+ "Choose Another Vault…",+ ContextMenuIcon::Vault,+ crate::termwindow::ContextMenuApplicationAction::Note(+ NoteEditorCommand::ChooseVault { managed: false },+ ),+ true,+ ),+ self.context_menu_application_item_with_icon(+ super::context_menu::reveal_in_folder_label(),+ ContextMenuIcon::Folder,+ crate::termwindow::ContextMenuApplicationAction::Note(+ NoteEditorCommand::RevealVault,+ ),+ workspace_threads::space_note_vault(&self.active_space_id).is_some(),+ ),+ ];+ self.show_term_context_menu(context, anchor, items);+ }++ fn ignore_right_sidebar_note_spelling(&mut self, word: &str) {+ let Some(session) = self.right_sidebar_note.session.as_ref() else {+ return;+ };+ let document_id = session.lock().document_id.clone();+ if let Some(window) = self.window.as_ref() {+ window.ignore_spelling_word(&document_id, word);+ }+ self.right_sidebar_note.spelling_issues = Arc::new(+ self.right_sidebar_note+ .spelling_issues+ .iter()+ .filter(|issue| !issue.word.eq_ignore_ascii_case(word))+ .cloned()+ .collect(),+ );+ self.right_sidebar_note.spelling_revision = None;+ self.right_sidebar_note.spelling_context = None;+ self.schedule_right_sidebar_note_spellcheck(Duration::from_millis(50));+ self.invalidate_window();+ }++ fn learn_right_sidebar_note_spelling(&mut self, word: &str) {+ if let Some(window) = self.window.as_ref() {+ window.learn_spelling_word(word);+ }+ self.right_sidebar_note.spelling_issues = Arc::new(+ self.right_sidebar_note+ .spelling_issues+ .iter()+ .filter(|issue| !issue.word.eq_ignore_ascii_case(word))+ .cloned()+ .collect(),+ );+ self.right_sidebar_note.spelling_revision = None;+ self.right_sidebar_note.spelling_context = None;+ self.schedule_right_sidebar_note_spellcheck(Duration::from_millis(50));+ self.invalidate_window();+ }++ pub(crate) fn cut_right_sidebar_focused_input(&mut self) {+ if self.right_sidebar_mode == RightSidebarMode::Tasks {+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return;+ };+ let selected = session+ .lock()+ .selected_text(&self.right_sidebar_note.view)+ .map(str::to_string);+ if let Some(text) = selected {+ if session.lock().backspace(&mut self.right_sidebar_note.view) {+ self.copy_to_clipboard(ClipboardCopyDestination::Clipboard, text);+ self.note_did_edit();+ }+ }+ return;+ }+ let Some(input) = self.right_sidebar_focused_input_mut() else {+ return;+ };+ let text = if let Some(text) = input.caret_take_selected_text() {+ text+ } else {+ let text = input.text.clone();+ input.clear();text};if !text.is_empty() {@@ -2421,6 +3381,7 @@ impl crate::TermWindow {pub(crate) fn push_right_sidebar_text(&mut self, text: &str) -> bool {if self.right_sidebar_mode == RightSidebarMode::Tasks {+ self.right_sidebar_note.begin_live_editing();let Some(session) = self.right_sidebar_note.session.clone() else {return false;};@@ -2442,6 +3403,7 @@ impl crate::TermWindow {}fn handle_right_sidebar_note_key(&mut self, key: TermKeyCode, mods: TermModifiers) -> bool {+ self.right_sidebar_note.begin_live_editing();let shift = mods.contains(TermModifiers::SHIFT);let super_ = mods.contains(TermModifiers::SUPER);let ctrl = mods.contains(TermModifiers::CTRL);@@ -2705,11 +3667,14 @@ impl crate::TermWindow {EditorMode::LivePreview => EditorMode::Source,EditorMode::Source | EditorMode::ReadOnly => EditorMode::LivePreview,};+ self.schedule_right_sidebar_note_parse();self.right_sidebar_note.refresh_projection();+ self.schedule_right_sidebar_note_spellcheck(Duration::from_millis(50));self.invalidate_window();}pub(crate) fn save_right_sidebar_note_now(&mut self) {+ self.right_sidebar_note.cancel_autosave_deadline();let Some(session) = self.right_sidebar_note.session.clone() else {return;};@@ -2719,27 +3684,39 @@ impl crate::TermWindow {let Some(window) = self.window.as_ref().cloned() else {return;};+ let origin_mux_window_id = self.mux_window_id;+ let saved_session = Arc::clone(&session);promise::spawn::spawn(async move {- let result =- promise::spawn::spawn_into_new_thread(move || save_document_revision(&session))- .await;- window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {- if let Err(err) = result {- log::error!("failed to save Note: {err:#}");- }- if let Some(front_end) = crate::frontend::try_front_end() {- for gui_window in front_end.gui_windows() {- gui_window.window.invalidate();+ let result = promise::spawn::spawn_into_new_thread(move || {+ let stage = crate::input_diagnostics::StageTimer::begin("note_save");+ let result = save_document_revision(&session);+ stage.finish(result.is_ok());+ result+ })+ .await;+ window.notify(TermWindowNotif::Apply(Box::new(+ move |term_window| match result {+ Ok(outcome) => {+ term_window.publish_right_sidebar_note_revision(+ origin_mux_window_id,+ saved_session,+ outcome.saved_revision,+ );}- } else {- term_window.invalidate_window();- }- })));+ Err(err) => {+ log::error!("failed to save Note: {err:#}");+ if term_window.right_sidebar_note_visible() {+ term_window.invalidate_window();+ }+ }+ },+ )));}).detach();}pub(crate) fn flush_right_sidebar_note_blocking(&mut self) {+ self.right_sidebar_note.cancel_autosave_deadline();let Some(session) = self.right_sidebar_note.session.clone() else {return;};@@ -2750,68 +3727,533 @@ impl crate::TermWindow {}}- fn note_did_edit(&mut self) {+ pub(crate) fn note_did_edit(&mut self) {self.right_sidebar_note.refresh_projection();+ self.schedule_right_sidebar_note_parse();self.right_sidebar_note.reveal_caret = true;- self.right_sidebar_note.save_generation =- self.right_sidebar_note.save_generation.wrapping_add(1);- let generation = self.right_sidebar_note.save_generation;+ self.schedule_right_sidebar_note_spellcheck(Duration::from_millis(+ NOTE_SPELLCHECK_DEBOUNCE_MS,+ ));+ if self+ .right_sidebar_note+ .note_edited(Instant::now(), Duration::from_millis(NOTE_AUTOSAVE_MS))+ {+ if let Some(window) = self.window.as_ref().cloned() {+ Self::schedule_right_sidebar_note_autosave_wakeup(+ window,+ Duration::from_millis(NOTE_AUTOSAVE_MS),+ );+ }+ }+ }++ fn schedule_right_sidebar_note_parse(&mut self) {+ let Some((revision, source, mode, caret, document)) =+ self.right_sidebar_note.background_parse_request()+ else {+ return;+ };let Some(window) = self.window.as_ref().cloned() else {+ self.right_sidebar_note.parse_in_flight_revision = None;return;};promise::spawn::spawn(async move {- smol::Timer::after(Duration::from_millis(NOTE_AUTOSAVE_MS)).await;+ let result = promise::spawn::spawn_into_new_thread(move || {+ let stage = crate::input_diagnostics::StageTimer::begin("note_projection");+ let mut projection = crate::markdown_editor::MarkdownProjection::parse(&source);+ if let Some((vault_root, relative_path)) = document {+ projection.resolve_vault_links(&vault_root, &relative_path);+ }+ let visual = build_visual_document(&source, &projection, mode, caret);+ stage.finish(true);+ Ok((projection, visual))+ })+ .await;window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {- if term_window.right_sidebar_note.save_generation != generation {- return;+ match result {+ Ok((projection, visual)) => {+ let applied = term_window+ .right_sidebar_note+ .apply_background_parse(revision, mode, caret, projection, visual);+ if applied {+ term_window+ .schedule_right_sidebar_note_spellcheck(Duration::from_millis(50));+ term_window.invalidate_window();+ }+ }+ Err(err) => {+ term_window.right_sidebar_note.parse_in_flight_revision = None;+ log::error!("failed to parse Note in background: {err:#}");+ }+ }+ if term_window.right_sidebar_note.background_parse_pending() {+ term_window.schedule_right_sidebar_note_parse();}- term_window.save_right_sidebar_note_now();})));}).detach();- if let Some(front_end) = crate::frontend::try_front_end() {- for gui_window in front_end.gui_windows() {- gui_window- .window- .notify(TermWindowNotif::Apply(Box::new(|term_window| {- if let Some(session) = term_window.right_sidebar_note.session.clone() {- session- .lock()- .clamp_view(&mut term_window.right_sidebar_note.view);- term_window.right_sidebar_note.refresh_projection();- term_window.invalidate_window();- }- })));- }- } else {- self.invalidate_window();- }- }-- /// Map a sidebar text-input `UIItemType` to its `TextInputState`.- fn right_sidebar_input_for_item(&self, item_type: &UIItemType) -> Option<&TextInputState> {- match item_type {- UIItemType::RightSidebarFileFilter => Some(&self.right_sidebar_file_filter),- UIItemType::RightSidebarSnippetSearch => Some(&self.right_sidebar_snippet_search),- UIItemType::RightSidebarSnippetTitle => Some(&self.right_sidebar_snippet_title),- _ => None,- }}- /// Hit-test an x coordinate against a single-line input painted this frame,- /// returning the closest caret char index.- pub(crate) fn right_sidebar_input_char_index_for_x(- &self,- item_type: &UIItemType,- x: isize,- ) -> Option<usize> {- let layout = self- .right_sidebar_input_layouts- .iter()- .find(|layout| &layout.item_type == item_type)?;- let input = self.right_sidebar_input_for_item(item_type)?;- let font = layout.font.clone();- let chars: Vec<char> = input.text.chars().collect();+ fn schedule_right_sidebar_note_wrap(+ &mut self,+ wrap_key: usize,+ wrap_width: f32,+ normal_metrics: NoteApproximateTextMetrics,+ h1_metrics: NoteApproximateTextMetrics,+ h2_metrics: NoteApproximateTextMetrics,+ h3_metrics: NoteApproximateTextMetrics,+ code_metrics: NoteApproximateTextMetrics,+ ) {+ let Some((key, visual, mut wrap_cache)) =+ self.right_sidebar_note.background_wrap_request(wrap_key)+ else {+ return;+ };+ let Some(window) = self.window.as_ref().cloned() else {+ self.right_sidebar_note.background_wrap_in_flight_key = None;+ self.right_sidebar_note.wrap_cache = wrap_cache;+ return;+ };+ promise::spawn::spawn(async move {+ let result = promise::spawn::spawn_into_new_thread(move || {+ let stage = crate::input_diagnostics::StageTimer::begin("note_wrap");+ let wrapped = wrap_visual_document_by_width_cached(+ &visual,+ wrap_width,+ wrap_key,+ &mut wrap_cache,+ |block, _, text| {+ let metrics = match block {+ BlockKind::Heading(1) => h1_metrics,+ BlockKind::Heading(2) => h2_metrics,+ BlockKind::Heading(_) => h3_metrics,+ BlockKind::CodeBlock => code_metrics,+ _ => normal_metrics,+ };+ Ok::<f32, anyhow::Error>(approximate_note_text_width(text, metrics))+ },+ )?;+ stage.finish(true);+ Ok((wrapped, wrap_cache))+ })+ .await;+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ match result {+ Ok((wrapped, wrap_cache)) => {+ term_window+ .right_sidebar_note+ .apply_background_wrap(key, wrapped, wrap_cache);+ }+ Err(err) => {+ if term_window.right_sidebar_note.background_wrap_in_flight_key == Some(key)+ {+ term_window.right_sidebar_note.background_wrap_in_flight_key = None;+ }+ log::error!("failed to wrap Note in background: {err:#}");+ }+ }+ term_window.invalidate_window();+ })));+ })+ .detach();+ }++ fn note_approximate_text_metrics(+ &self,+ font: &Rc<LoadedFont>,+ render_metrics: &RenderMetrics,+ ) -> anyhow::Result<NoteApproximateTextMetrics> {+ // Background wrapping cannot move LoadedFont to its worker thread. Shape+ // a tiny representative sample on the UI thread and pass only these+ // Copy metrics across. Using the terminal cell width for every grapheme+ // made proportional Latin text almost twice as wide as what we paint,+ // causing long notes to wrap much earlier than short notes.+ const LATIN_SAMPLE: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";+ const WIDE_SAMPLE: &str = "系统";++ let latin = self.cached_ui_text_advance(font, render_metrics, LATIN_SAMPLE)?+ / LATIN_SAMPLE.chars().count() as f32;+ let space = self.cached_ui_text_advance(font, render_metrics, " ")?;+ let wide = self.cached_ui_text_advance(font, render_metrics, WIDE_SAMPLE)?+ / WIDE_SAMPLE.chars().count() as f32;++ Ok(NoteApproximateTextMetrics {+ latin: latin.max(1.0),+ space: space.max(1.0),+ wide: wide.max(1.0),+ })+ }++ fn schedule_right_sidebar_note_spellcheck(&mut self, delay: Duration) {+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ if !self.config.note_spellcheck_enabled+ || !window.text_check_capabilities().spelling+ || self.right_sidebar_note.view.mode == EditorMode::ReadOnly+ {+ return;+ }+ let Some(session) = self.right_sidebar_note.session.as_ref() else {+ return;+ };+ let revision = session.lock().revision();+ let focus = self.right_sidebar_note.view.selection.focus.byte;+ let current_context_is_valid = self.right_sidebar_note.spelling_revision == Some(revision)+ && self+ .right_sidebar_note+ .spelling_context+ .as_ref()+ .is_some_and(|context| context.start <= focus && focus <= context.end);+ if current_context_is_valid+ || self.right_sidebar_note.spellcheck_scheduled_revision == Some(revision)+ || self.right_sidebar_note.spellcheck_in_flight_revision == Some(revision)+ {+ return;+ }+ self.right_sidebar_note.spellcheck_scheduled_revision = Some(revision);+ promise::spawn::spawn(async move {+ smol::Timer::after(delay).await;+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.run_right_sidebar_note_spellcheck(revision);+ })));+ })+ .detach();+ }++ fn run_right_sidebar_note_spellcheck(&mut self, revision: u64) {+ if self.right_sidebar_note.spellcheck_scheduled_revision != Some(revision) {+ return;+ }+ self.right_sidebar_note.spellcheck_scheduled_revision = None;+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return;+ };+ let (document_id, chunks, check_range) = {+ let session = session.lock();+ if session.revision() != revision {+ self.schedule_right_sidebar_note_spellcheck(Duration::from_millis(+ NOTE_SPELLCHECK_DEBOUNCE_MS,+ ));+ return;+ }+ let source = session.source();+ let mut check_range = if source.len() > 64 * 1024 {+ self.right_sidebar_note+ .projection+ .active_block_range(self.right_sidebar_note.view.selection.focus.byte)+ .unwrap_or_else(|| {+ session.source_line_selection_range(+ self.right_sidebar_note.view.selection.focus.byte,+ )+ })+ } else {+ 0..source.len()+ };+ const MAX_SPELLCHECK_CONTEXT_BYTES: usize = 64 * 1024;+ if check_range.end.saturating_sub(check_range.start) > MAX_SPELLCHECK_CONTEXT_BYTES {+ let focus = self+ .right_sidebar_note+ .view+ .selection+ .focus+ .byte+ .min(source.len());+ let mut start = focus.saturating_sub(MAX_SPELLCHECK_CONTEXT_BYTES / 2);+ while start < focus && !source.is_char_boundary(start) {+ start += 1;+ }+ let mut end = (start + MAX_SPELLCHECK_CONTEXT_BYTES).min(source.len());+ while end > start && !source.is_char_boundary(end) {+ end -= 1;+ }+ check_range = start..end;+ }+ (+ session.document_id.clone(),+ build_spell_check_chunks_in_range(+ source,+ &self.right_sidebar_note.projection,+ check_range.clone(),+ ),+ check_range,+ )+ };+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ self.right_sidebar_note.spellcheck_in_flight_revision = Some(revision);+ promise::spawn::spawn(async move {+ let mut issues = Vec::new();+ for (index, chunk) in chunks.into_iter().enumerate() {+ let request_id = revision.wrapping_mul(1_000_003).wrapping_add(index as u64);+ let response = window+ .request_text_check(window::TextCheckRequest {+ document_id: document_id.clone(),+ request_id,+ text: chunk.text.clone(),+ })+ .await;+ let Ok(response) = response else {+ continue;+ };+ if response.request_id != request_id {+ continue;+ }+ for issue in response.issues {+ let Some(source_range) = chunk.source_range_for_issue(issue.range.clone())+ else {+ continue;+ };+ let Some(word) = chunk.text.get(issue.range).map(str::to_string) else {+ continue;+ };+ issues.push(NoteSpellingIssue {+ source: source_range,+ word,+ suggestions: issue.suggestions,+ });+ }+ }+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window.apply_right_sidebar_note_spellcheck(revision, check_range, issues);+ })));+ })+ .detach();+ }++ fn apply_right_sidebar_note_spellcheck(+ &mut self,+ revision: u64,+ check_range: std::ops::Range<usize>,+ mut issues: Vec<NoteSpellingIssue>,+ ) {+ if self.right_sidebar_note.spellcheck_in_flight_revision == Some(revision) {+ self.right_sidebar_note.spellcheck_in_flight_revision = None;+ }+ let Some(session) = self.right_sidebar_note.session.as_ref() else {+ return;+ };+ if session.lock().revision() != revision {+ self.schedule_right_sidebar_note_spellcheck(Duration::from_millis(+ NOTE_SPELLCHECK_DEBOUNCE_MS,+ ));+ return;+ }+ issues.sort_by_key(|issue| (issue.source.start, issue.source.end));+ issues.dedup_by(|a, b| a.source == b.source);+ self.right_sidebar_note.spelling_issues = Arc::new(issues);+ self.right_sidebar_note.spelling_revision = Some(revision);+ self.right_sidebar_note.spelling_context = Some(check_range.clone());+ let focus = self.right_sidebar_note.view.selection.focus.byte;+ if focus < check_range.start || focus > check_range.end {+ self.schedule_right_sidebar_note_spellcheck(Duration::from_millis(50));+ }+ self.invalidate_window();+ }++ fn sync_right_sidebar_note_native_text_input_snapshot(&mut self, wrap_key: usize) {+ let active = self.right_sidebar_note.view.focused+ && self.right_sidebar_note.view.mode != EditorMode::ReadOnly;+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ if !active {+ if self+ .right_sidebar_note+ .native_text_input_snapshot_key+ .take()+ .is_some()+ {+ window.set_native_text_input_snapshot(None);+ }+ return;+ }+ let Some(session) = self.right_sidebar_note.session.clone() else {+ return;+ };+ let selection = self.right_sidebar_note.view.selection.range();+ let revision = session.lock().revision();+ let key = (+ revision,+ selection.start,+ selection.end,+ self.right_sidebar_note.view.scroll_offset.to_bits(),+ wrap_key,+ );+ if self.right_sidebar_note.native_text_input_snapshot_key == Some(key) {+ return;+ }++ const MAX_NATIVE_CONTEXT_BYTES: usize = 64 * 1024;+ let focus = self.right_sidebar_note.view.selection.focus.byte;+ let mut context = self+ .right_sidebar_note+ .projection+ .active_block_range(focus)+ .unwrap_or_else(|| session.lock().source_line_selection_range(focus));+ let (context_text, native_selection) = {+ let session = session.lock();+ let source = session.source();+ let focus = focus.min(source.len());+ context.start = context.start.min(selection.start).min(source.len());+ context.end = context.end.max(selection.end).min(source.len());+ let native_selection =+ if context.end.saturating_sub(context.start) > MAX_NATIVE_CONTEXT_BYTES {+ let half = MAX_NATIVE_CONTEXT_BYTES / 2;+ let mut start = focus.saturating_sub(half);+ let mut end = start+ .saturating_add(MAX_NATIVE_CONTEXT_BYTES)+ .min(source.len());+ start = end.saturating_sub(MAX_NATIVE_CONTEXT_BYTES);+ while start > 0 && !source.is_char_boundary(start) {+ start -= 1;+ }+ while end > start && !source.is_char_boundary(end) {+ end -= 1;+ }+ context = start..end;+ focus..focus+ } else {+ selection.clone()+ };+ while context.start > 0 && !source.is_char_boundary(context.start) {+ context.start -= 1;+ }+ while context.end > context.start && !source.is_char_boundary(context.end) {+ context.end -= 1;+ }+ (source[context.clone()].to_string(), native_selection)+ };++ let mut hits = Vec::new();+ for line in &self.right_sidebar_note.line_layouts {+ for run in &line.runs {+ for (x, byte) in &run.boundaries {+ if *byte < context.start || *byte > context.end {+ continue;+ }+ hits.push(window::NativeTextHit {+ rect: Rect::new(+ Point::new(*x as isize, line.y as isize),+ window::Size::new(1, line.height.max(1.0) as isize),+ ),+ byte: byte.saturating_sub(context.start),+ });+ }+ }+ }+ self.right_sidebar_note.native_text_input_token = self+ .right_sidebar_note+ .native_text_input_token+ .wrapping_add(1)+ .max(1);+ let relative_selection = native_selection.start.saturating_sub(context.start)+ ..native_selection.end.saturating_sub(context.start);+ window.set_native_text_input_snapshot(Some(window::NativeTextInputSnapshot {+ token: self.right_sidebar_note.native_text_input_token,+ revision,+ source_base: context.start,+ text: context_text,+ selection: relative_selection,+ hits,+ }));+ self.right_sidebar_note.native_text_input_snapshot_key = Some(key);+ }++ fn schedule_right_sidebar_note_autosave_wakeup(window: window::Window, delay: Duration) {+ promise::spawn::spawn(async move {+ smol::Timer::after(delay).await;+ let notify_window = window.clone();+ window.notify(TermWindowNotif::Apply(Box::new(+ move |term_window| match term_window+ .right_sidebar_note+ .autosave_woke(Instant::now())+ {+ AutosaveWakeAction::Idle => {}+ AutosaveWakeAction::SaveNow => term_window.save_right_sidebar_note_now(),+ AutosaveWakeAction::Reschedule(remaining) => {+ Self::schedule_right_sidebar_note_autosave_wakeup(notify_window, remaining);+ }+ },+ )));+ })+ .detach();+ }++ fn right_sidebar_note_visible(&self) -> bool {+ !self.right_sidebar_collapsed && self.right_sidebar_mode == RightSidebarMode::Tasks+ }++ fn apply_right_sidebar_note_published_revision(+ &mut self,+ session: &Arc<parking_lot::Mutex<crate::markdown_editor::MarkdownDocumentSession>>,+ saved_revision: u64,+ ) {+ if self+ .right_sidebar_note+ .session+ .as_ref()+ .is_none_or(|current| !Arc::ptr_eq(current, session))+ {+ return;+ }+ self.right_sidebar_note+ .apply_published_snapshot(saved_revision);+ // Live hosts remain Live, but still repaint the Saving/Saved badge.+ if self.right_sidebar_note_visible() {+ self.invalidate_window();+ }+ }++ fn publish_right_sidebar_note_revision(+ &mut self,+ origin_mux_window_id: mux::window::WindowId,+ session: Arc<parking_lot::Mutex<crate::markdown_editor::MarkdownDocumentSession>>,+ saved_revision: u64,+ ) {+ self.apply_right_sidebar_note_published_revision(&session, saved_revision);+ let Some(front_end) = crate::frontend::try_front_end() else {+ return;+ };+ for gui_window in front_end.gui_windows() {+ if gui_window.mux_window_id == origin_mux_window_id {+ continue;+ }+ let session = Arc::clone(&session);+ gui_window+ .window+ .notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ term_window+ .apply_right_sidebar_note_published_revision(&session, saved_revision);+ })));+ }+ }++ /// Map a sidebar text-input `UIItemType` to its `TextInputState`.+ fn right_sidebar_input_for_item(&self, item_type: &UIItemType) -> Option<&TextInputState> {+ match item_type {+ UIItemType::RightSidebarFileFilter => Some(&self.right_sidebar_file_filter),+ UIItemType::RightSidebarSnippetSearch => Some(&self.right_sidebar_snippet_search),+ UIItemType::RightSidebarSnippetTitle => Some(&self.right_sidebar_snippet_title),+ _ => None,+ }+ }++ /// Hit-test an x coordinate against a single-line input painted this frame,+ /// returning the closest caret char index.+ pub(crate) fn right_sidebar_input_char_index_for_x(+ &self,+ item_type: &UIItemType,+ x: isize,+ ) -> Option<usize> {+ let layout = self+ .right_sidebar_input_layouts+ .iter()+ .find(|layout| &layout.item_type == item_type)?;+ let input = self.right_sidebar_input_for_item(item_type)?;+ let font = layout.font.clone();+ let chars: Vec<char> = input.text.chars().collect();let first = layout.first_char.min(chars.len());let relative = (x as f32 - layout.text_x).clamp(0.0, layout.text_width.max(0.0));let mut best_idx = first;@@ -3838,8 +5280,125 @@ impl crate::TermWindow {}}+ fn refresh_note_vault_index_if_needed(&mut self, root: &Path) {+ let root_changed = self+ .right_sidebar_note_vault_index_root+ .as_ref()+ .is_none_or(|current| current != root);+ if root_changed {+ self.right_sidebar_note_vault_index_generation = self+ .right_sidebar_note_vault_index_generation+ .wrapping_add(1);+ self.right_sidebar_note_vault_index_root = Some(root.to_path_buf());+ self.right_sidebar_note_vault_paths = Arc::new(Vec::new());+ self.right_sidebar_note_tree_expanded.clear();+ self.right_sidebar_note_vault_last_scan = None;+ self.right_sidebar_note_vault_indexing = false;+ self.right_sidebar_note_tree_scroll_offset = 0.0;+ }+ if self.right_sidebar_note_vault_indexing+ || (!root_changed+ && self.right_sidebar_note_vault_last_scan.is_some_and(|last| {+ last.elapsed() < Duration::from_secs(NOTE_VAULT_RESCAN_SECS)+ }))+ {+ return;+ }++ self.right_sidebar_note_vault_index_generation = self+ .right_sidebar_note_vault_index_generation+ .wrapping_add(1);+ let generation = self.right_sidebar_note_vault_index_generation;+ self.right_sidebar_note_vault_indexing = true;+ self.right_sidebar_note_vault_last_scan = Some(Instant::now());+ let root = root.to_path_buf();+ let worker_root = root.clone();+ let active_document = self+ .right_sidebar_note+ .document+ .as_ref()+ .filter(|document| document.vault_root == root)+ .map(|document| {+ (+ document.document_path.clone(),+ document.session.lock().disk_stamp(),+ )+ });+ let Some(window) = self.window.clone() else {+ return;+ };+ promise::spawn::spawn(async move {+ let result = promise::spawn::spawn_into_new_thread(move || {+ let paths = vault_file_paths(&worker_root)?;+ let active_snapshot = active_document+ .map(|(path, known_stamp)| -> anyhow::Result<_> {+ let metadata = fs::metadata(&path)+ .with_context(|| format!("stat {}", path.display()))?;+ let modified = metadata+ .modified()+ .with_context(|| format!("read mtime {}", path.display()))?;+ let len = metadata.len();+ if known_stamp == Some((modified, len)) {+ return Ok(None);+ }+ let source = fs::read_to_string(&path)+ .with_context(|| format!("read {}", path.display()))?;+ Ok(Some((modified, len, source)))+ })+ .transpose()?+ .flatten();+ Ok::<_, anyhow::Error>((paths, active_snapshot))+ })+ .await;+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ if generation != term_window.right_sidebar_note_vault_index_generation+ || term_window.right_sidebar_note_vault_index_root.as_ref() != Some(&root)+ {+ return;+ }+ term_window.right_sidebar_note_vault_indexing = false;+ let mut changed = term_window.right_sidebar_note.document.is_none();+ match result {+ Ok((paths, active_snapshot)) => {+ if term_window.right_sidebar_note_vault_paths.as_ref() != &paths {+ for path in &paths {+ let mut parent = Path::new(path).parent();+ while let Some(directory) = parent {+ if directory.as_os_str().is_empty() {+ break;+ }+ term_window+ .right_sidebar_note_tree_expanded+ .insert(directory.to_string_lossy().replace('\\', "/"));+ parent = directory.parent();+ }+ }+ term_window.right_sidebar_note_vault_paths = Arc::new(paths);+ changed = true;+ }+ if let Some((modified, len, source)) = active_snapshot {+ changed |= term_window+ .right_sidebar_note+ .apply_external_snapshot(modified, len, source);+ }+ }+ Err(err) => {+ let message = format!("{err:#}");+ changed = term_window.right_sidebar_note.load_error.as_deref()+ != Some(message.as_str());+ term_window.right_sidebar_note.load_error = Some(message);+ }+ }+ if changed {+ term_window.invalidate_window();+ }+ })));+ })+ .detach();+ }+#[allow(clippy::too_many_arguments)]- fn paint_note_sidebar(+ fn paint_note_vault_tree(&mut self,layers: &mut TripleLayerQuadAllocator,ui_font: &Rc<LoadedFont>,@@ -3851,122 +5410,324 @@ impl crate::TermWindow {content_top: usize,content_width: usize,content_bottom: usize,- base_font_size: f64,+ narrow: bool,) -> anyhow::Result<()> {- if !self.right_sidebar_note.ensure_loaded() {- let message = self- .right_sidebar_note- .load_error- .clone()- .unwrap_or_else(|| "Unable to open Notes".to_string());- self.paint_sidebar_text(+ let header_height = self.ui_px(NOTE_TOOLBAR_HEIGHT);+ let button_size = header_height;+ let mut title_x = content_x + self.ui_px(SIDEBAR_INSET);+ if narrow {+ self.paint_snippet_icon_button(layers,- ui_font,- ui_metrics,- &message,+ chrome,+ foreground,+ muted_fg,content_x,content_top,- content_width,- muted_fg,+ button_size,+ SvgIcon::ArrowLeft,+ UIItemType::RightSidebarNoteTreeBack,)?;- return Ok(());- }- self.right_sidebar_note.refresh_projection();-- let toolbar_height = self.ui_px(NOTE_TOOLBAR_HEIGHT);- let button_gap = self.ui_px(8);- let mode_label = match self.right_sidebar_note.view.mode {- EditorMode::LivePreview => "Preview",- EditorMode::Source => "Source",- EditorMode::ReadOnly => "Read only",- };- let save_state = self+ title_x = content_x + button_size + self.ui_px(6);+ } else {+ self.paint_snippet_icon_button(+ layers,+ chrome,+ foreground,+ muted_fg,+ content_x + content_width.saturating_sub(button_size),+ content_top,+ button_size,+ SvgIcon::PanelLeftClose,+ UIItemType::RightSidebarNoteTreeToggle,+ )?;+ }+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ "Vault",+ title_x,+ content_top + header_height.saturating_sub(ui_metrics.cell_size.height as usize) / 2,+ content_x.saturating_add(content_width).saturating_sub(+ title_x + self.ui_px(SIDEBAR_INSET) + if narrow { 0 } else { button_size },+ ),+ foreground,+ )?;++ let rows = note_vault_tree_rows(+ &self.right_sidebar_note_vault_paths,+ &self.right_sidebar_note_tree_expanded,+ );+ let tree_top = content_top + header_height + self.ui_px(4);+ let tree_bottom = content_bottom.saturating_sub(self.ui_px(SIDEBAR_INSET));+ let visible_height = tree_bottom.saturating_sub(tree_top);+ let row_metrics = right_sidebar_file_row_metrics(ui_metrics);+ let max_scroll = rows+ .len()+ .saturating_mul(row_metrics.row_height)+ .saturating_sub(visible_height) as f32;+ self.right_sidebar_note_tree_scroll_offset = self+ .right_sidebar_note_tree_scroll_offset+ .clamp(0.0, max_scroll);+ let range = visible_file_row_range(+ rows.len(),+ self.right_sidebar_note_tree_scroll_offset,+ visible_height,+ row_metrics.row_height,+ );+ let selected = self.right_sidebar_note- .session+ .document.as_ref()- .map(|session| session.lock().save_state().clone())- .unwrap_or(SaveState::Saved);- let save_label = match &save_state {- SaveState::Saved => "Saved",- SaveState::Dirty => "Save",- SaveState::Saving(_) => "Saving…",- SaveState::Failed(_) => "Retry",- };- let compact_button_padding = self.ui_px(SIDEBAR_INSET) * 2;- let desired_mode_width = (self.sidebar_text_width(ui_font, mode_label)?.ceil() as usize- + compact_button_padding)- .max(self.ui_px(64));- let desired_save_width = (self.sidebar_text_width(ui_font, save_label)?.ceil() as usize- + compact_button_padding)- .max(self.ui_px(64));- let desired_actions_width = desired_mode_width + button_gap + desired_save_width;- let title_label = "Inbox.md";- let title_label_width = self.sidebar_text_width(ui_font, title_label)?.ceil() as usize;- let show_title = content_width >= title_label_width + button_gap + desired_actions_width;- let (title_width, mode_x, mode_width, save_width) = if show_title {- let title_width = content_width.saturating_sub(desired_actions_width + button_gap);- (- title_width,- content_x + title_width + button_gap,- desired_mode_width,- desired_save_width,- )- } else {- let action_width = content_width.saturating_sub(button_gap);- let mode_width = action_width / 2;- (- 0,+ .map(|document| document.relative_path.as_str());+ for index in range {+ let row = &rows[index];+ let y = tree_top as f32 + (index * row_metrics.row_height) as f32+ - self.right_sidebar_note_tree_scroll_offset;+ let y = y.floor().max(tree_top as f32) as usize;+ let height = row_metrics.row_height.min(tree_bottom.saturating_sub(y));+ if height == 0 {+ continue;+ }+ let active = !row.is_dir && selected == Some(row.relative_path.as_str());+ let hovered = self.is_pointer_over_ui_rect(content_x, y, content_width, height);+ if active || hovered {+ self.fill_rounded_rectangle(+ layers,+ 1,+ euclid::rect(+ content_x as f32,+ y as f32,+ content_width as f32,+ height as f32,+ ),+ if active {+ chrome.selected_bg.mul_alpha(0.46)+ } else {+ chrome.sidebar_button_hover_bg+ },+ self.ui_f32(SIDEBAR_ROW_RADIUS),+ )?;+ }+ self.ui_items.push(UIItem {+ x: content_x,+ y,+ width: content_width,+ height,+ item_type: UIItemType::RightSidebarNoteTreeRow(row.relative_path.clone()),+ });+ let indent = row+ .depth+ .saturating_mul(row_metrics.indent_step)+ .min(content_width.saturating_sub(24));+ let icon_x = content_x + self.ui_px(SIDEBAR_INSET) + indent;+ let icon_y = y + height.saturating_sub(row_metrics.icon_size) / 2;+ if row.is_dir {+ self.paint_sidebar_icon(+ layers,+ if self+ .right_sidebar_note_tree_expanded+ .contains(&row.relative_path)+ {+ SvgIcon::FolderOpen+ } else {+ SvgIcon::Folder+ },+ icon_x,+ icon_y,+ row_metrics.icon_size,+ muted_fg,+ )?;+ } else {+ if let Some(icon) = material_file_icon_for_name(&row.name) {+ self.paint_sidebar_material_icon(+ layers,+ icon,+ icon_x,+ icon_y,+ row_metrics.icon_size,+ )?;+ } else {+ self.paint_sidebar_icon(+ layers,+ SvgIcon::FileText,+ icon_x,+ icon_y,+ row_metrics.icon_size,+ if active { foreground } else { muted_fg },+ )?;+ }+ }+ let text_x = icon_x + row_metrics.icon_size + row_metrics.icon_gap;+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ &row.name,+ text_x,+ y + height.saturating_sub(ui_metrics.cell_size.height as usize) / 2,+ content_x+ .saturating_add(content_width)+ .saturating_sub(text_x + self.ui_px(SIDEBAR_INSET)),+ if active { foreground } else { muted_fg },+ )?;+ }++ if self.right_sidebar_note_tree_scroll_offset > 0.0 {+ self.paint_right_sidebar_file_top_fade(+ layers,+ chrome,content_x,- mode_width,- action_width.saturating_sub(mode_width),- )- };- if show_title {+ tree_top,+ content_width,+ self.ui_px(FILE_SCROLL_FADE_HEIGHT),+ )?;+ }+ if !narrow {+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(+ content_x.saturating_add(content_width) as f32,+ content_top as f32,+ 1.0,+ content_bottom.saturating_sub(content_top) as f32,+ ),+ chrome.separator,+ )?;+ }+ Ok(())+ }++ #[allow(clippy::too_many_arguments)]+ fn paint_note_sidebar(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ ui_font: &Rc<LoadedFont>,+ ui_metrics: RenderMetrics,+ chrome: UiPalette,+ foreground: LinearRgba,+ muted_fg: LinearRgba,+ content_x: usize,+ content_top: usize,+ content_width: usize,+ content_bottom: usize,+ base_font_size: f64,+ ) -> anyhow::Result<()> {+ self.right_sidebar_note_table_layouts.clear();+ if let Some(vault) = workspace_threads::space_note_vault(&self.active_space_id) {+ self.refresh_note_vault_index_if_needed(&vault.root);+ }+ if !self.ensure_active_right_sidebar_note_document() {+ let message = self+ .right_sidebar_note+ .load_error+ .clone()+ .unwrap_or_else(|| "Unable to open Notes".to_string());self.paint_sidebar_text(layers,ui_font,ui_metrics,- title_label,+ &message,content_x,- content_top- + (toolbar_height.saturating_sub(ui_metrics.cell_size.height as usize)) / 2,- title_width,+ content_top,+ content_width,+ muted_fg,+ )?;+ if workspace_threads::space_note_vault(&self.active_space_id).is_none() {+ let button_height = self.ui_px(52);+ let gap = self.ui_px(10);+ let first_y = content_top + ui_metrics.cell_size.height as usize + self.ui_px(20);+ self.paint_snippet_button(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ first_y,+ content_width,+ button_height,+ Some(SvgIcon::FolderOpen),+ "Choose Existing Vault…",+ UIItemType::RightSidebarNoteChooseVault,+ true,+ )?;+ self.paint_snippet_button(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ first_y + button_height + gap,+ content_width,+ button_height,+ Some(SvgIcon::FolderPlus),+ "Create New Vault…",+ UIItemType::RightSidebarNoteCreateVault,+ true,+ )?;+ }+ return Ok(());+ }+ let wide_layout = content_width >= self.ui_px(NOTE_VAULT_SPLIT_MIN_WIDTH);+ self.right_sidebar_note_wide_layout = wide_layout;+ let split = wide_layout && !self.right_sidebar_note_vault_tree_collapsed;+ if !wide_layout && self.right_sidebar_note_view == RightSidebarNoteView::Tree {+ self.paint_note_vault_tree(+ layers,+ ui_font,+ ui_metrics,+ chrome,foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ content_bottom,+ true,)?;+ return Ok(());}- self.paint_snippet_button(- layers,- ui_font,- ui_metrics,- chrome,- foreground,- muted_fg,- mode_x,- content_top,- mode_width,- toolbar_height,- None,- mode_label,- UIItemType::RightSidebarNoteModeToggle,- true,- )?;- let save_x = mode_x + mode_width + button_gap;- self.paint_snippet_button(- layers,- ui_font,- ui_metrics,- chrome,- foreground,- muted_fg,- save_x,- content_top,- save_width,- toolbar_height,- None,- save_label,- UIItemType::RightSidebarNoteSave,- !matches!(save_state, SaveState::Saving(_)),- )?;+ let (content_x, content_width) = if split {+ let tree_width = self+ .ui_px(NOTE_VAULT_TREE_WIDTH)+ .min(content_width.saturating_sub(self.ui_px(300)));+ self.paint_note_vault_tree(+ layers,+ ui_font,+ ui_metrics,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ tree_width,+ content_bottom,+ false,+ )?;+ (+ content_x + tree_width + self.ui_px(SIDEBAR_INSET),+ content_width.saturating_sub(tree_width + self.ui_px(SIDEBAR_INSET)),+ )+ } else {+ (content_x, content_width)+ };+ self.right_sidebar_note.refresh_projection();+ self.schedule_right_sidebar_note_parse();+ self.schedule_right_sidebar_note_spellcheck(Duration::from_millis(50));++ let toolbar_height = self.ui_px(NOTE_TOOLBAR_HEIGHT);+ let menu_size = toolbar_height;+ let show_tree_button = !split;+ let tree_button_icon = if wide_layout {+ SvgIcon::PanelLeftOpen+ } else {+ SvgIcon::FolderTree+ };let body_y = content_top + toolbar_height + self.ui_px(NOTE_BODY_TOP_GAP);let body_bottom = content_bottom.saturating_sub(self.ui_px(SIDEBAR_INSET));@@ -3974,6 +5735,7 @@ impl crate::TermWindow {if body_height == 0 || content_width == 0 {return Ok(());}+ let note_layout_stage = crate::input_diagnostics::StageTimer::begin("note_layout");self.ui_items.push(UIItem {x: content_x,y: body_y,@@ -4027,6 +5789,18 @@ impl crate::TermWindow {let code_metrics = RenderMetrics::with_font_metrics(&code_font.metrics());let selection = self.right_sidebar_note.view.selection;let focused = self.right_sidebar_note.view.focused;+ let spelling_issues = (self.right_sidebar_note.spelling_revision+ == self.right_sidebar_note.projection_revision+ && self.right_sidebar_note.view.mode != EditorMode::ReadOnly)+ .then(|| Arc::clone(&self.right_sidebar_note.spelling_issues));+ let active_spelling_word = if focused && selection.is_caret() {+ self.right_sidebar_note+ .session+ .as_ref()+ .map(|session| session.lock().word_range_at(selection.focus.byte))+ } else {+ None+ };self.right_sidebar_note.view.preedit = if focused {match &self.dead_key_status {DeadKeyStatus::Composing(text) => Some(text.clone()),@@ -4037,120 +5811,130 @@ impl crate::TermWindow {};let preedit = self.right_sidebar_note.view.preedit.clone();let padding = self.ui_px(NOTE_BODY_PADDING) as f32;- let text_left = content_x as f32 + padding;+ let available_reading_width = (content_width as f32 - padding * 2.0).max(1.0);+ let reading_width = available_reading_width.min(self.ui_f32(NOTE_READING_MAX_WIDTH as f32));+ let text_left = content_x as f32 + (content_width as f32 - reading_width) / 2.0;let clip_left = text_left;- let clip_right = (content_x + content_width) as f32 - padding;+ let clip_right = text_left + reading_width;let wrap_width = (clip_right - clip_left).max(1.0);let mut wrap_hasher = DefaultHasher::new();(wrap_width.floor() as usize).hash(&mut wrap_hasher);self.dimensions.dpi.hash(&mut wrap_hasher);- for font_id in [- ui_font.id(),- bold_font.id(),- italic_font.id(),- bold_italic_font.id(),- h1_font.id(),- h2_font.id(),- h3_font.id(),- h1_italic_font.id(),- h2_italic_font.id(),- h3_italic_font.id(),- code_font.id(),+ // LoadedFont ids are allocation identities. Appearance changes rebuild+ // those objects even when typography is identical, which used to+ // throw away the whole Note wrap cache on every light/dark switch.+ // Hash only inputs that can actually change line breaks.+ base_font_size.to_bits().hash(&mut wrap_hasher);+ normal_weight.hash(&mut wrap_hasher);+ self.config.font.hash(&mut wrap_hasher);+ for metrics in [+ ui_metrics,+ bold_metrics,+ italic_metrics,+ bold_italic_metrics,+ h1_metrics,+ h2_metrics,+ h3_metrics,+ h1_italic_metrics,+ h2_italic_metrics,+ h3_italic_metrics,+ code_metrics,] {- font_id.hash(&mut wrap_hasher);+ metrics.cell_size.width.hash(&mut wrap_hasher);+ metrics.cell_size.height.hash(&mut wrap_hasher);}let wrap_key = wrap_hasher.finish() as usize;let visual = if let Some(visual) = self.right_sidebar_note.cached_wrapped_visual(wrap_key) {visual+ } else if self.right_sidebar_note.prefers_background_wrap() {+ let normal_approx_metrics = self.note_approximate_text_metrics(ui_font, &ui_metrics)?;+ let h1_approx_metrics = self.note_approximate_text_metrics(&h1_font, &h1_metrics)?;+ let h2_approx_metrics = self.note_approximate_text_metrics(&h2_font, &h2_metrics)?;+ let h3_approx_metrics = self.note_approximate_text_metrics(&h3_font, &h3_metrics)?;+ let code_approx_metrics =+ self.note_approximate_text_metrics(&code_font, &code_metrics)?;+ self.schedule_right_sidebar_note_wrap(+ wrap_key,+ wrap_width,+ normal_approx_metrics,+ h1_approx_metrics,+ h2_approx_metrics,+ h3_approx_metrics,+ code_approx_metrics,+ );+ self.right_sidebar_note.provisional_wrapped_visual()} else {- let wrapped = wrap_visual_document_by_width(+ let wrap_stage = crate::input_diagnostics::StageTimer::begin("note_wrap");+ let mut wrap_cache = std::mem::take(&mut self.right_sidebar_note.wrap_cache);+ let wrapped = wrap_visual_document_by_width_cached(&self.right_sidebar_note.visual,wrap_width,- |block, run| {+ wrap_key,+ &mut wrap_cache,+ |block, style, text| {let (font, metrics) = match block {- BlockKind::Heading(1) if run.style.emphasis => {+ BlockKind::Heading(1) if style.emphasis => {(&h1_italic_font, h1_italic_metrics)}- BlockKind::Heading(2) if run.style.emphasis => {+ BlockKind::Heading(2) if style.emphasis => {(&h2_italic_font, h2_italic_metrics)}- BlockKind::Heading(_) if run.style.emphasis => {+ BlockKind::Heading(_) if style.emphasis => {(&h3_italic_font, h3_italic_metrics)}BlockKind::Heading(1) => (&h1_font, h1_metrics),BlockKind::Heading(2) => (&h2_font, h2_metrics),BlockKind::Heading(_) => (&h3_font, h3_metrics),BlockKind::CodeBlock => (&code_font, code_metrics),- _ if run.style.strong && run.style.emphasis => {+ _ if style.strong && style.emphasis => {(&bold_italic_font, bold_italic_metrics)}- _ if run.style.strong => (&bold_font, bold_metrics),- _ if run.style.emphasis => (&italic_font, italic_metrics),+ _ if style.strong => (&bold_font, bold_metrics),+ _ if style.emphasis => (&italic_font, italic_metrics),_ => (ui_font, ui_metrics),};- self.cached_ui_text_advance(font, &metrics, &run.text)+ self.cached_ui_text_advance(font, &metrics, text)},- )?;+ );+ self.right_sidebar_note.wrap_cache = wrap_cache;+ let wrapped = wrapped?;+ wrap_stage.finish(true);self.right_sidebar_note.cache_wrapped_visual(wrap_key, wrapped)};- let projected_objects = self.right_sidebar_note.projection.objects.clone();+ if visual.lines.is_empty() && self.right_sidebar_note.prefers_background_wrap() {+ self.paint_sidebar_text(+ layers,+ ui_font,+ ui_metrics,+ "Laying out note…",+ content_x + self.ui_px(NOTE_BODY_PADDING),+ body_y + self.ui_px(NOTE_BODY_PADDING),+ content_width.saturating_sub(self.ui_px(NOTE_BODY_PADDING) * 2),+ muted_fg,+ )?;+ self.right_sidebar_note.line_layouts.clear();+ self.right_sidebar_note.code_block_layouts.clear();+ self.right_sidebar_note.viewport_height = body_height as f32;+ self.right_sidebar_note.content_height = body_height as f32;+ self.paint_note_editor_toolbar(+ layers,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ menu_size,+ show_tree_button,+ tree_button_icon,+ )?;+ note_layout_stage.finish(true);+ return Ok(());+ }let table_horizontal_padding = self.ui_f32(NOTE_TABLE_CELL_HORIZONTAL_PADDING as f32);let table_vertical_padding = self.ui_f32(NOTE_TABLE_CELL_VERTICAL_PADDING as f32);let table_row_height = ui_metrics.cell_size.height as f32 + table_vertical_padding * 2.0;- let mut table_rows = vec![None; visual.lines.len()];- for object in &projected_objects {- let ProjectedObject::Table(table) = object else {- continue;- };- let row_indices = visual- .lines- .iter()- .enumerate()- .filter_map(|(index, line)| {- (line.block == BlockKind::Table- && line.runs.iter().any(|run| {- table.source.start <= run.source.start- && run.source.end <= table.source.end- }))- .then_some(index)- })- .collect::<Vec<_>>();- let column_count = table.rows.iter().map(Vec::len).max().unwrap_or(0);- if row_indices.is_empty() || column_count == 0 {- continue;- }- let mut desired_widths = vec![0.0f32; column_count];- for (row_index, row) in table.rows.iter().enumerate() {- let (font, metrics) = if row_index == 0 {- (&bold_font, bold_metrics)- } else {- (ui_font, ui_metrics)- };- for (column_index, cell) in row.iter().enumerate() {- let width = self.cached_ui_text_advance(font, &metrics, &cell.text)?- + table_horizontal_padding * 2.0;- desired_widths[column_index] = desired_widths[column_index].max(width);- }- }- let column_widths = Rc::new(fit_table_columns(- &desired_widths,- wrap_width,- self.ui_f32(NOTE_TABLE_MIN_COLUMN_WIDTH as f32),- ));- let mut alignments = table.alignments.clone();- alignments.resize(column_count, TableAlignment::None);- let alignments = Rc::new(alignments);- let row_count = row_indices.len();- for (row_index, visual_index) in row_indices.into_iter().enumerate() {- table_rows[visual_index] = Some(NoteTableRowPaintLayout {- column_widths: Rc::clone(&column_widths),- alignments: Rc::clone(&alignments),- row_index,- row_count,- });- }- }let use_dark_syntax_theme = matches!(crate::native_settings::effective_appearance(),window::Appearance::Dark | window::Appearance::DarkHighContrast@@ -4160,129 +5944,396 @@ impl crate::TermWindow {let code_header_height = self.ui_f32(NOTE_CODE_HEADER_HEIGHT as f32);let code_line_height = code_metrics.cell_size.height as f32;let code_inner_width = (wrap_width - code_horizontal_padding * 2.0).max(1.0);- let mut code_rows = vec![None; visual.lines.len()];- for object in &projected_objects {- let ProjectedObject::CodeBlock(code) = object else {- continue;- };- let row_indices = visual- .lines+ let active_document = self.right_sidebar_note.document.clone();+ let mut component_hasher = DefaultHasher::new();+ wrap_key.hash(&mut component_hasher);+ (Arc::as_ptr(&visual) as usize).hash(&mut component_hasher);+ self.right_sidebar_note+ .projection_revision+ .hash(&mut component_hasher);+ self.config+ .note_remote_images_enabled+ .hash(&mut component_hasher);+ if let Some(document) = active_document.as_ref() {+ document.vault_root.hash(&mut component_hasher);+ document.relative_path.hash(&mut component_hasher);+ }+ let mut collapsed_blocks = self+ .right_sidebar_note+ .collapsed_code_blocks+ .iter()+ .copied()+ .collect::<Vec<_>>();+ collapsed_blocks.sort_unstable();+ collapsed_blocks.hash(&mut component_hasher);+ let mut code_offsets = self+ .right_sidebar_note+ .code_horizontal_offsets+ .iter()+ .map(|(source, offset)| (*source, offset.to_bits()))+ .collect::<Vec<_>>();+ code_offsets.sort_unstable_by_key(|(source, _)| *source);+ code_offsets.hash(&mut component_hasher);+ let mut table_offsets = self+ .right_sidebar_note_table_horizontal_offsets+ .iter()+ .map(|(source, offset)| (*source, offset.to_bits()))+ .collect::<Vec<_>>();+ table_offsets.sort_unstable_by_key(|(source, _)| *source);+ table_offsets.hash(&mut component_hasher);+ let component_key = component_hasher.finish();++ if self.right_sidebar_note_paint_cache.key != Some(component_key) {+ // Component geometry only needs heavyweight objects. Avoid a deep+ // clone of every inline emphasis/link/tag in a multi-megabyte+ // projection when the first full layout is published.+ let projected_objects = self+ .right_sidebar_note+ .projection+ .objects.iter()- .enumerate()- .filter_map(|(index, line)| {- (line.block == BlockKind::CodeBlock- && code.content.start <= line.source.start- && line.source.end <= code.content.end)- .then_some(index)+ .filter(|object| {+ matches!(+ object,+ ProjectedObject::Table(_)+ | ProjectedObject::CodeBlock(_)+ | ProjectedObject::Image { .. }+ | ProjectedObject::WikiLink { embed: true, .. }+ )})+ .cloned().collect::<Vec<_>>();- if row_indices.is_empty() {- continue;+ let current_code_starts = projected_objects+ .iter()+ .filter_map(|object| match object {+ ProjectedObject::CodeBlock(code) => Some(code.source.start),+ _ => None,+ })+ .collect::<HashSet<_>>();+ self.right_sidebar_note_code_highlight+ .retain_blocks(¤t_code_starts);++ let mut table_rows = HashMap::new();+ let mut current_table_starts = HashSet::new();+ for object in &projected_objects {+ let ProjectedObject::Table(table) = object else {+ continue;+ };+ let start = visual+ .lines+ .partition_point(|line| line.source.end < table.source.start);+ let end = visual+ .lines+ .partition_point(|line| line.source.start <= table.source.end);+ let row_indices = (start..end)+ .filter(|index| {+ let line = &visual.lines[*index];+ line.block == BlockKind::Table+ && line.runs.iter().any(|run| {+ table.source.start <= run.source.start+ && run.source.end <= table.source.end+ })+ })+ .collect::<Vec<_>>();+ let column_count = table.rows.iter().map(Vec::len).max().unwrap_or(0);+ if row_indices.is_empty() || column_count == 0 {+ continue;+ }+ let mut desired_widths = vec![0.0f32; column_count];+ for (row_index, row) in table.rows.iter().enumerate() {+ let (font, metrics) = if row_index == 0 {+ (&bold_font, bold_metrics)+ } else {+ (ui_font, ui_metrics)+ };+ for (column_index, cell) in row.iter().enumerate() {+ let width = self.cached_ui_text_advance(font, &metrics, &cell.text)?+ + table_horizontal_padding * 2.0;+ desired_widths[column_index] = desired_widths[column_index].max(width);+ }+ }+ let column_widths = Rc::new(scrollable_note_table_columns(+ &desired_widths,+ wrap_width,+ self.ui_f32(NOTE_TABLE_MIN_COLUMN_WIDTH as f32),+ self.ui_f32(NOTE_TABLE_MAX_COLUMN_WIDTH as f32),+ ));+ let total_width = column_widths.iter().sum::<f32>();+ let max_horizontal_scroll = (total_width - wrap_width).max(0.0);+ current_table_starts.insert(table.source.start);+ let horizontal_offset = self+ .right_sidebar_note_table_horizontal_offsets+ .entry(table.source.start)+ .or_default();+ *horizontal_offset = horizontal_offset.clamp(0.0, max_horizontal_scroll);+ let horizontal_offset = *horizontal_offset;+ let mut alignments = table.alignments.clone();+ alignments.resize(column_count, TableAlignment::None);+ let alignments = Rc::new(alignments);+ let row_count = row_indices.len();+ for (row_index, visual_index) in row_indices.into_iter().enumerate() {+ table_rows.insert(+ visual_index,+ NoteTableRowPaintLayout {+ table_start: table.source.start,+ column_widths: Rc::clone(&column_widths),+ alignments: Rc::clone(&alignments),+ row_index,+ row_count,+ total_width,+ horizontal_offset,+ max_horizontal_scroll,+ },+ );+ }}- let highlights = self.cached_note_code_highlights(code, use_dark_syntax_theme);- let collapsed = self- .right_sidebar_note- .collapsed_code_blocks- .contains(&code.source.start);- let max_content_width = code- .text- .split_inclusive('\n')- .map(|raw_line| raw_line.strip_suffix('\n').unwrap_or(raw_line))- .map(|line| self.cached_ui_text_advance(&code_font, &code_metrics, line))- .collect::<anyhow::Result<Vec<_>>>()?- .into_iter()- .fold(0.0f32, f32::max);- let max_horizontal_scroll = (max_content_width - code_inner_width).max(0.0);- let horizontal_offset = self- .right_sidebar_note- .code_horizontal_offsets- .entry(code.source.start)- .or_default();- *horizontal_offset = horizontal_offset.clamp(0.0, max_horizontal_scroll);- let horizontal_offset = *horizontal_offset;- let row_count = row_indices.len();- let block_height = code_header_height- + if collapsed {- 0.0- } else {- code_vertical_padding * 2.0 + code_line_height * row_count as f32+ self.right_sidebar_note_table_horizontal_offsets+ .retain(|source_start, _| current_table_starts.contains(source_start));++ let mut code_rows = HashMap::new();+ for object in &projected_objects {+ let ProjectedObject::CodeBlock(code) = object else {+ continue;};- let language = code- .language- .as_deref()- .unwrap_or("code")- .to_ascii_uppercase();- for (row_index, visual_index) in row_indices.into_iter().enumerate() {- code_rows[visual_index] = Some(NoteCodeRowPaintLayout {- block_start: code.source.start,- language: language.clone(),- row_index,- row_count,- collapsed,- colors: Arc::clone(&highlights),- horizontal_offset,- block_height,- max_horizontal_scroll,- });+ let start = visual+ .lines+ .partition_point(|line| line.source.end < code.content.start);+ let end = visual+ .lines+ .partition_point(|line| line.source.start <= code.content.end);+ let row_indices = (start..end)+ .filter(|index| {+ let line = &visual.lines[*index];+ line.block == BlockKind::CodeBlock+ && code.content.start <= line.source.start+ && line.source.end <= code.content.end+ })+ .collect::<Vec<_>>();+ if row_indices.is_empty() {+ continue;+ }+ let collapsed = self+ .right_sidebar_note+ .collapsed_code_blocks+ .contains(&code.source.start);+ let mut max_content_width = 0.0f32;+ for raw_line in code.text.split_inclusive('\n') {+ let line = raw_line.strip_suffix('\n').unwrap_or(raw_line);+ max_content_width = max_content_width.max(self.cached_ui_text_advance(+ &code_font,+ &code_metrics,+ line,+ )?);+ }+ let max_horizontal_scroll = (max_content_width - code_inner_width).max(0.0);+ let horizontal_offset = self+ .right_sidebar_note+ .code_horizontal_offsets+ .entry(code.source.start)+ .or_default();+ *horizontal_offset = horizontal_offset.clamp(0.0, max_horizontal_scroll);+ let horizontal_offset = *horizontal_offset;+ let row_count = row_indices.len();+ let block_height = code_header_height+ + if collapsed {+ 0.0+ } else {+ code_vertical_padding * 2.0 + code_line_height * row_count as f32+ };+ let language = code+ .language+ .as_deref()+ .unwrap_or("code")+ .to_ascii_uppercase();+ let code = Arc::new(code.clone());+ for (row_index, visual_index) in row_indices.into_iter().enumerate() {+ code_rows.insert(+ visual_index,+ NoteCodeRowPaintLayout {+ block_start: code.source.start,+ language: language.clone(),+ code: Arc::clone(&code),+ row_index,+ row_count,+ collapsed,+ horizontal_offset,+ block_height,+ max_horizontal_scroll,+ },+ );+ }+ }++ let mut image_sources = HashMap::new();+ if let Some(document) = active_document.as_ref() {+ for object in &projected_objects {+ let resolved = match object {+ ProjectedObject::Image { source, target, .. } => {+ if self.config.note_remote_images_enabled+ && (target.starts_with("https://") || target.starts_with("http://"))+ {+ Some((+ source.start,+ RightSidebarNoteImageSource::Remote(target.clone()),+ ))+ } else {+ resolve_local_image(+ &document.vault_root,+ &document.document_path,+ target,+ )+ .ok()+ .map(|path| {+ (source.start, RightSidebarNoteImageSource::Local(path))+ })+ }+ }+ ProjectedObject::WikiLink {+ source,+ embed: true,+ resolved_path: Some(target),+ ..+ } => {+ let candidate = document.vault_root.join(target).canonicalize().ok();+ candidate+ .filter(|candidate| candidate.starts_with(&document.vault_root))+ .map(|path| {+ (source.start, RightSidebarNoteImageSource::Local(path))+ })+ }+ _ => None,+ };+ if let Some((source_start, source)) = resolved {+ image_sources.insert(source_start, source);+ }+ }}+ self.right_sidebar_note_paint_cache = NotePaintCache {+ key: Some(component_key),+ table_rows: Arc::new(table_rows),+ code_rows: Arc::new(code_rows),+ image_sources: Arc::new(image_sources),+ };}- let notebook = default_notebook().ok();+ let table_rows = Arc::clone(&self.right_sidebar_note_paint_cache.table_rows);+ let code_rows = Arc::clone(&self.right_sidebar_note_paint_cache.code_rows);+ let note_image_paths = Arc::clone(&self.right_sidebar_note_paint_cache.image_sources);let viewport_top = body_y as f32;let viewport_bottom = body_bottom as f32;- let image_line_height = self.ui_f32(180.0);+ let image_max_height = (body_height as f32 * 0.72)+ .max(ui_metrics.cell_size.height as f32)+ .min(self.ui_f32(720.0));let line_gap = self.ui_px(NOTE_LINE_GAP) as f32;- let mut measured_y = padding;- let mut caret_row = None;- for (line_index, line) in visual.lines.iter().enumerate() {- let metrics = match line.block {- BlockKind::Heading(1) => h1_metrics,- BlockKind::Heading(2) => h2_metrics,- BlockKind::Heading(_) => h3_metrics,- BlockKind::CodeBlock => code_metrics,- _ => ui_metrics,- };- let mut height = metrics.cell_size.height as f32;- if line.kind == VisualLineKind::Image {- height = height.max(image_line_height);- }- if table_rows[line_index].is_some() {- height = table_row_height;- }- if let Some(code_row) = code_rows[line_index].as_ref() {- height = note_code_row_height(- code_row.row_index,- code_row.row_count,- code_row.collapsed,- code_line_height,- code_header_height,- code_vertical_padding,- );- }- if selection.is_caret()- && (line.runs.iter().any(|run| {- run.source.start <= selection.focus.byte- && selection.focus.byte <= run.source.end- }) || (line.runs.is_empty() && line.source.start == selection.focus.byte)- || selection.focus.byte == line.source.end)- {- caret_row = Some((measured_y, height));- }- let row_gap = if let Some(code_row) = code_rows[line_index].as_ref() {- if code_row.row_index + 1 < code_row.row_count {- 0.0- } else {- line_gap+ let mut geometry_hasher = DefaultHasher::new();+ wrap_key.hash(&mut geometry_hasher);+ self.right_sidebar_note+ .visual_key+ .hash(&mut geometry_hasher);+ table_row_height.to_bits().hash(&mut geometry_hasher);+ code_line_height.to_bits().hash(&mut geometry_hasher);+ code_header_height.to_bits().hash(&mut geometry_hasher);+ code_vertical_padding.to_bits().hash(&mut geometry_hasher);+ image_max_height.to_bits().hash(&mut geometry_hasher);+ let mut loaded_image_metrics = note_image_paths+ .iter()+ .filter_map(|(source_start, path)| {+ self.right_sidebar_note_images+ .get(path)+ .map(|image| (*source_start, image.width, image.height))+ })+ .collect::<Vec<_>>();+ loaded_image_metrics.sort_unstable();+ loaded_image_metrics.hash(&mut geometry_hasher);+ line_gap.to_bits().hash(&mut geometry_hasher);+ let mut collapsed = self+ .right_sidebar_note+ .collapsed_code_blocks+ .iter()+ .copied()+ .collect::<Vec<_>>();+ collapsed.sort_unstable();+ collapsed.hash(&mut geometry_hasher);+ let geometry_key = geometry_hasher.finish();+ if self.right_sidebar_note.line_geometry_key != Some(geometry_key)+ || self.right_sidebar_note.line_geometry.len() != visual.lines.len()+ {+ let mut top = padding;+ let mut geometry = Vec::with_capacity(visual.lines.len());+ for (line_index, line) in visual.lines.iter().enumerate() {+ let metrics = match line.block {+ BlockKind::Heading(1) => h1_metrics,+ BlockKind::Heading(2) => h2_metrics,+ BlockKind::Heading(_) => h3_metrics,+ BlockKind::CodeBlock => code_metrics,+ _ => ui_metrics,+ };+ let mut height = metrics.cell_size.height as f32;+ if line.kind == VisualLineKind::Image {+ let image = note_image_paths+ .get(&line.source.start)+ .and_then(|path| self.right_sidebar_note_images.get(path));+ height = note_image_row_height(image, height, wrap_width, image_max_height);}- } else {- table_rows[line_index]- .as_ref()- .filter(|row| row.row_index + 1 < row.row_count)- .map(|_| 0.0)- .unwrap_or(line_gap)- };- measured_y += height + row_gap;+ if matches!(+ line.block,+ BlockKind::Properties | BlockKind::Callout | BlockKind::Embed+ ) {+ height += self.ui_f32(8.0);+ }+ if table_rows.contains_key(&line_index) {+ height = table_row_height;+ }+ if let Some(code_row) = code_rows.get(&line_index) {+ height = note_code_row_height(+ code_row.row_index,+ code_row.row_count,+ code_row.collapsed,+ code_line_height,+ code_header_height,+ code_vertical_padding,+ );+ }+ let gap = if let Some(code_row) = code_rows.get(&line_index) {+ if code_row.row_index + 1 < code_row.row_count {+ 0.0+ } else {+ line_gap+ }+ } else {+ let grouped_card_continues =+ visual+ .lines+ .get(line_index + 1)+ .is_some_and(|next| match line.block {+ BlockKind::Properties | BlockKind::Callout => {+ next.block == line.block+ }+ BlockKind::Embed => {+ next.block == line.block && next.source == line.source+ }+ _ => false,+ });+ if grouped_card_continues {+ 0.0+ } else {+ table_rows+ .get(&line_index)+ .filter(|row| row.row_index + 1 < row.row_count)+ .map(|_| 0.0)+ .unwrap_or(line_gap)+ }+ };+ geometry.push(NoteLineGeometry { top, height, gap });+ top += height + gap;+ }+ self.right_sidebar_note.line_geometry_key = Some(geometry_key);+ self.right_sidebar_note.line_geometry = Arc::new(geometry);}- let measured_content_height = measured_y + padding;+ let line_geometry = Arc::clone(&self.right_sidebar_note.line_geometry);+ let measured_content_height = line_geometry+ .last()+ .map(|line| line.top + line.height + line.gap + padding)+ .unwrap_or(padding * 2.0);let max_scroll = (measured_content_height - body_height as f32).max(0.0);let mut scroll = self.right_sidebar_note@@ -4290,7 +6341,22 @@ impl crate::TermWindow {.scroll_offset.clamp(0.0, max_scroll);if focused && self.right_sidebar_note.reveal_caret {- if let Some((caret_top, caret_height)) = caret_row {+ let caret_byte = selection.focus.byte;+ let candidate_start = visual+ .lines+ .partition_point(|line| line.source.end < caret_byte);+ let candidate_end = visual+ .lines+ .partition_point(|line| line.source.start <= caret_byte);+ let caret_row = (candidate_start..candidate_end)+ .find(|index| {+ let line = &visual.lines[*index];+ line.source.start <= caret_byte && caret_byte <= line.source.end+ })+ .and_then(|index| line_geometry.get(index));+ if let Some(caret_row) = caret_row {+ let caret_top = caret_row.top;+ let caret_height = caret_row.height;let safe_top = scroll + padding;let safe_bottom = scroll + body_height as f32 - padding;if caret_top < safe_top {@@ -4303,15 +6369,19 @@ impl crate::TermWindow {self.right_sidebar_note.reveal_caret = false;}self.right_sidebar_note.view.scroll_offset = scroll;- let mut logical_y = padding;let mut layouts = Vec::new();let mut code_block_layouts = Vec::new();+ let mut table_layouts = Vec::new();let mut caret_rect: Option<(f32, f32, f32)> = None;let selected = selection.range();- for (line_index, line) in visual.lines.iter().enumerate() {- let table_row = table_rows[line_index].as_ref();- let code_row = code_rows[line_index].as_ref();+ let paint_range = virtual_note_line_range(&line_geometry, scroll, body_height as f32);+ let paint_start = paint_range.start;+ for line_index in paint_range {+ let line = &visual.lines[line_index];+ let geometry = line_geometry[line_index];+ let table_row = table_rows.get(&line_index);+ let code_row = code_rows.get(&line_index);let (line_font, line_metrics) = match line.block {BlockKind::Heading(1) => (&h1_font, h1_metrics),BlockKind::Heading(2) => (&h2_font, h2_metrics),@@ -4319,38 +6389,10 @@ impl crate::TermWindow {BlockKind::CodeBlock => (&code_font, code_metrics),_ => (ui_font, ui_metrics),};- let mut line_height = line_metrics.cell_size.height as f32;- if line.kind == VisualLineKind::Image {- line_height = line_height.max(image_line_height);- }- if table_row.is_some() {- line_height = table_row_height;- }- if let Some(code_row) = code_row {- line_height = note_code_row_height(- code_row.row_index,- code_row.row_count,- code_row.collapsed,- code_line_height,- code_header_height,- code_vertical_padding,- );- }- let line_y = body_y as f32 + logical_y - scroll;+ let line_height = geometry.height;+ let line_y = body_y as f32 + geometry.top - scroll;let line_bottom = line_y + line_height;let visible = line_bottom >= viewport_top && line_y <= viewport_bottom;- let row_gap = if let Some(code_row) = code_row {- if code_row.row_index + 1 < code_row.row_count {- 0.0- } else {- line_gap- }- } else {- table_row- .filter(|row| row.row_index + 1 < row.row_count)- .map(|_| 0.0)- .unwrap_or(line_gap)- };let code_text_y = code_row.map(|row| {if row.row_index == 0 {line_y + code_header_height + code_vertical_padding@@ -4358,33 +6400,62 @@ impl crate::TermWindow {line_y}});- let mut x = if let Some(code_row) = code_row {+ let card_horizontal_padding = self.ui_f32(10.0);+ let card_vertical_padding = self.ui_f32(4.0);+ let continuation_indent = line.continuation_indent();+ let mut x = if let Some(table_row) = table_row {+ text_left - table_row.horizontal_offset+ } else if let Some(code_row) = code_row {text_left + code_horizontal_padding - code_row.horizontal_offset+ } else if matches!(+ line.block,+ BlockKind::Properties | BlockKind::Callout | BlockKind::Embed+ ) {+ text_left + card_horizontal_padding + continuation_indent} else {- text_left+ text_left + continuation_indent};let mut run_layouts = Vec::new();- if let Some(code_row) = code_row.filter(|row| row.row_index == 0) {- let block_bottom = line_y + code_row.block_height;- let draw_top = line_y.max(viewport_top);+ let starts_painted_code_block = code_row.is_some_and(|row| {+ row.row_index == 0+ || line_index == paint_start+ || code_rows+ .get(&line_index.saturating_sub(1))+ .is_none_or(|previous| previous.block_start != row.block_start)+ });+ if let Some(code_row) = code_row.filter(|_| starts_painted_code_block) {+ let block_top = line_y+ - if code_row.row_index == 0 {+ 0.0+ } else {+ code_header_height+ + code_vertical_padding+ + code_line_height * code_row.row_index as f32+ };+ let block_bottom = block_top + code_row.block_height;+ let draw_top = block_top.max(viewport_top);let draw_bottom = block_bottom.min(viewport_bottom);if draw_bottom > draw_top {let block_rect =euclid::rect(text_left, draw_top, wrap_width, draw_bottom - draw_top);- if line_y >= viewport_top && block_bottom <= viewport_bottom {- self.fill_rounded_rectangle(- layers,- 1,- block_rect,- chrome.sidebar_button_bg,- self.ui_f32(NOTE_CODE_BLOCK_RADIUS),- )?;- } else {- self.filled_rectangle(layers, 1, block_rect, chrome.sidebar_button_bg)?;- }+ let (round_top, round_bottom) = visible_code_block_rounded_edges(+ block_top,+ block_bottom,+ viewport_top,+ viewport_bottom,+ );+ self.fill_vertically_rounded_rectangle(+ layers,+ 1,+ block_rect,+ chrome.sidebar_button_bg,+ self.ui_f32(NOTE_CODE_BLOCK_RADIUS),+ round_top,+ round_bottom,+ )?;}- let content_y = line_y + code_header_height;+ let content_y = block_top + code_header_height;let content_height = (code_row.block_height - code_header_height).max(0.0);code_block_layouts.push(NoteCodeBlockLayout {source_start: code_row.block_start,@@ -4394,11 +6465,11 @@ impl crate::TermWindow {height: content_height,max_horizontal_scroll: code_row.max_horizontal_scroll,});- if line_y >= viewport_top- && line_y + code_header_height <= viewport_bottom+ if block_top >= viewport_top+ && block_top + code_header_height <= viewport_bottom&& code_header_height >= 1.0{- let header_y = line_y.max(0.0) as usize;+ let header_y = block_top.max(0.0) as usize;let header_height = code_header_height as usize;self.ui_items.push(UIItem {x: text_left as usize,@@ -4455,7 +6526,7 @@ impl crate::TermWindow {1,euclid::rect(text_left,- line_y + code_header_height - 1.0,+ block_top + code_header_height - 1.0,wrap_width,1.0,),@@ -4465,39 +6536,75 @@ impl crate::TermWindow {}if line_height <= 0.0 {- logical_y += row_gap;continue;}- let note_image_path = if visible && line.kind == VisualLineKind::Image {- projected_objects.iter().find_map(|object| match object {- ProjectedObject::Image { source, target, .. } if *source == line.source => {- notebook.as_ref().and_then(|notebook| {- resolve_local_image(- ¬ebook.content_root,- ¬ebook.document_path,- target,- )- .ok()- })- }- _ => None,- })+ let note_image_source = if visible && line.kind == VisualLineKind::Image {+ note_image_paths.get(&line.source.start).cloned()} else {None};- let note_image = note_image_path+ let note_image = note_image_source.as_ref()- .and_then(|path| self.right_sidebar_note_images.get(path))+ .and_then(|source| self.right_sidebar_note_images.get(source)).cloned();if note_image.is_none() {- if let Some(path) = note_image_path.clone() {- self.schedule_right_sidebar_note_image(path);+ if let Some(source) = note_image_source.clone() {+ self.schedule_right_sidebar_note_image(source);}}if visible {+ if matches!(+ line.block,+ BlockKind::Properties | BlockKind::Callout | BlockKind::Embed+ ) {+ let belongs_to_same_card = |other_block: BlockKind, same_source: bool| {+ other_block == line.block+ && (matches!(line.block, BlockKind::Properties | BlockKind::Callout)+ || same_source)+ };+ let same_as_previous = line_index > 0+ && belongs_to_same_card(+ visual.lines[line_index - 1].block,+ visual.lines[line_index - 1].source == line.source,+ );+ let same_as_next = visual.lines.get(line_index + 1).is_some_and(|next| {+ belongs_to_same_card(next.block, next.source == line.source)+ });+ let background = match line.block {+ BlockKind::Properties => chrome.control_bg.mul_alpha(0.72),+ BlockKind::Callout => chrome.selected_bg.mul_alpha(0.20),+ BlockKind::Embed => chrome.sidebar_button_bg,+ _ => unreachable!(),+ };+ self.fill_vertically_rounded_rectangle(+ layers,+ 1,+ euclid::rect(text_left, line_y, wrap_width, line_height),+ background,+ self.ui_f32(SIDEBAR_ROW_RADIUS),+ !same_as_previous,+ !same_as_next,+ )?;+ if matches!(line.block, BlockKind::Callout | BlockKind::Embed) {+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(text_left, line_y, self.ui_f32(3.0).max(1.0), line_height),+ chrome.secondary_text,+ )?;+ }+ }if let Some(table_row) = table_row {+ table_layouts.push(RightSidebarNoteTableLayout {+ source_start: table_row.table_start,+ x: text_left,+ y: line_y.max(viewport_top),+ width: wrap_width,+ height: line_bottom.min(viewport_bottom) - line_y.max(viewport_top),+ max_horizontal_scroll: table_row.max_horizontal_scroll,+ });if table_row.row_index == 0 {self.filled_rectangle(layers,@@ -4519,21 +6626,59 @@ impl crate::TermWindow {euclid::rect(text_left, line_y + line_height - 1.0, wrap_width, 1.0),chrome.separator,)?;- }- let mut boundary_x = text_left;- self.filled_rectangle(- layers,- 1,- euclid::rect(boundary_x, line_y, 1.0, line_height),- chrome.separator,- )?;- for column_width in table_row.column_widths.iter() {- boundary_x += *column_width;+ }+ let mut boundary_x = text_left - table_row.horizontal_offset;+ if boundary_x >= clip_left && boundary_x <= clip_right {+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(boundary_x, line_y, 1.0, line_height),+ chrome.separator,+ )?;+ }+ for column_width in table_row.column_widths.iter() {+ boundary_x += *column_width;+ if boundary_x >= clip_left && boundary_x <= clip_right {+ self.filled_rectangle(+ layers,+ 1,+ euclid::rect(boundary_x - 1.0, line_y, 1.0, line_height),+ chrome.separator,+ )?;+ }+ }+ if table_row.row_index + 1 == table_row.row_count+ && table_row.max_horizontal_scroll > 0.0+ {+ let track_height = self.ui_f32(NOTE_TABLE_SCROLLBAR_HEIGHT as f32);+ let thumb_width = (wrap_width * wrap_width / table_row.total_width)+ .max(self.ui_f32(24.0))+ .min(wrap_width);+ let thumb_x = text_left+ + (wrap_width - thumb_width)+ * (table_row.horizontal_offset+ / table_row.max_horizontal_scroll.max(1.0));+ self.filled_rectangle(+ layers,+ 2,+ euclid::rect(+ text_left,+ line_y + line_height - track_height,+ wrap_width,+ track_height,+ ),+ chrome.separator.mul_alpha(0.46),+ )?;self.filled_rectangle(layers,- 1,- euclid::rect(boundary_x - 1.0, line_y, 1.0, line_height),- chrome.separator,+ 2,+ euclid::rect(+ thumb_x,+ line_y + line_height - track_height,+ thumb_width,+ track_height,+ ),+ chrome.scrollbar_thumb,)?;}}@@ -4561,6 +6706,8 @@ impl crate::TermWindow {line_y,(clip_right - text_left).max(0.0),line_height,+ viewport_top,+ viewport_bottom,)?;}}@@ -4582,7 +6729,6 @@ impl crate::TermWindow {}if !visible {- logical_y += line_height + row_gap;continue;}@@ -4618,8 +6764,10 @@ impl crate::TermWindow {.copied().unwrap_or(0.0);let cell_left = x;- let cell_right = (cell_left + cell_width).min(clip_right);- let cell_clip_left = (cell_left + table_horizontal_padding).min(cell_right);+ let cell_right = cell_left + cell_width;+ let cell_clip_left = (cell_left + table_horizontal_padding)+ .max(clip_left)+ .min(clip_right);let cell_clip_right = (cell_right - table_horizontal_padding).max(cell_clip_left).min(clip_right);@@ -4661,6 +6809,18 @@ impl crate::TermWindow {content_left,(content_right - content_left).max(0.0),)+ } else if matches!(+ line.block,+ BlockKind::Properties | BlockKind::Callout | BlockKind::Embed+ ) {+ (+ x,+ line_y + card_vertical_padding,+ clip_left + card_horizontal_padding,+ clip_right - card_horizontal_padding,+ x,+ advance,+ )} else {(x, line_y, clip_left, clip_right, x, advance)};@@ -4719,8 +6879,13 @@ impl crate::TermWindow {} else {foreground};- let code_colors = code_row.and_then(|row| row.colors.get(row.row_index));- self.paint_cached_ui_shape_clipped(+ let code_colors = code_row.map(|row| {+ (+ row.row_index,+ self.cached_note_code_highlights(&row.code, use_dark_syntax_theme),+ )+ });+ self.paint_cached_ui_shape_pixel_clipped(layers,&metrics,&shaped,@@ -4730,6 +6895,8 @@ impl crate::TermWindow {run_clip_right,|info| {code_colors+ .as_ref()+ .and_then(|(row_index, lines)| lines.get(*row_index)).and_then(|colors| colors.get(info.cluster)).copied().unwrap_or(color)@@ -4748,6 +6915,50 @@ impl crate::TermWindow {color,)?;}+ if !run.atomic {+ if let Some(issues) = spelling_issues.as_ref() {+ for issue in issues.iter().filter(|issue| {+ issue.source.start < run.source.end+ && run.source.start < issue.source.end+ && !active_spelling_word.as_ref().is_some_and(|active| {+ active.start < issue.source.end+ && issue.source.start < active.end+ })+ }) {+ let source_start = issue.source.start.max(run.source.start);+ let source_end = issue.source.end.min(run.source.end);+ let underline_start =+ note_boundary_x(&boundaries, source_start).max(run_clip_left);+ let underline_end =+ note_boundary_x(&boundaries, source_end).min(run_clip_right);+ let segment_width = self.ui_f32(1.5).max(1.0);+ let segment_gap = self.ui_f32(1.0).max(1.0);+ let mut underline_x = underline_start;+ let mut raised = false;+ while underline_x < underline_end {+ let width =+ segment_width.min((underline_end - underline_x).max(0.0));+ if width <= 0.0 {+ break;+ }+ self.filled_rectangle(+ layers,+ 2,+ euclid::rect(+ underline_x,+ run_y + run_height+ - self.ui_f32(if raised { 1.0 } else { 2.0 }),+ width,+ self.ui_f32(1.0).max(1.0),+ ),+ chrome.spelling_error,+ )?;+ raised = !raised;+ underline_x += segment_width + segment_gap;+ }+ }+ }+ }}if focused&& selection.is_caret()@@ -4791,7 +7002,7 @@ impl crate::TermWindow {if code_row.is_some() {text_left + code_horizontal_padding} else {- text_left+ text_left + continuation_indent},code_text_y.unwrap_or(line_y),if code_row.is_some() {@@ -4817,14 +7028,15 @@ impl crate::TermWindow {},runs: run_layouts,});- logical_y += line_height + row_gap;}self.right_sidebar_note.line_layouts = layouts;self.right_sidebar_note.code_block_layouts = code_block_layouts;+ self.right_sidebar_note_table_layouts = table_layouts;self.right_sidebar_note.viewport_height = body_height as f32;self.right_sidebar_note.content_height = measured_content_height;self.right_sidebar_note.clamp_scroll();+ self.sync_right_sidebar_note_native_text_input_snapshot(wrap_key);if let Some((caret_x, caret_y, caret_height)) = caret_rect {if caret_y + caret_height >= viewport_top && caret_y <= viewport_bottom {@@ -4878,6 +7090,45 @@ impl crate::TermWindow {}}+ self.paint_right_sidebar_file_mask(+ layers,+ chrome,+ content_x,+ content_top,+ content_width,+ body_y.saturating_sub(content_top),+ )?;+ self.paint_right_sidebar_file_mask(+ layers,+ chrome,+ content_x,+ body_bottom,+ content_width,+ content_bottom.saturating_sub(body_bottom),+ )?;+ if self.right_sidebar_note.view.scroll_offset > 0.0 {+ self.paint_right_sidebar_note_top_fade(+ layers,+ chrome,+ content_x,+ body_y,+ content_width,+ self.ui_px(FILE_SCROLL_FADE_HEIGHT).min(body_height),+ )?;+ }+ self.paint_note_editor_toolbar(+ layers,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ content_width,+ menu_size,+ show_tree_button,+ tree_button_icon,+ )?;+if self.right_sidebar_note.content_height > self.right_sidebar_note.viewport_height {let track_height = body_height as f32;let thumb_height = (track_height * self.right_sidebar_note.viewport_height@@ -4901,37 +7152,294 @@ impl crate::TermWindow {chrome.scrollbar_thumb,)?;}+ note_layout_stage.finish(true);Ok(())}- fn schedule_right_sidebar_note_image(&mut self, path: PathBuf) {- if self.right_sidebar_note_images.contains_key(&path)- || !self.right_sidebar_note_images_loading.insert(path.clone())+ #[allow(clippy::too_many_arguments)]+ fn paint_note_editor_toolbar(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ chrome: UiPalette,+ foreground: LinearRgba,+ muted_fg: LinearRgba,+ content_x: usize,+ content_top: usize,+ content_width: usize,+ menu_size: usize,+ show_tree_button: bool,+ tree_button_icon: SvgIcon,+ ) -> anyhow::Result<()> {+ if show_tree_button {+ if self.is_pointer_over_ui_rect(content_x, content_top, menu_size, menu_size) {+ self.fill_rounded_rectangle(+ layers,+ 2,+ euclid::rect(+ content_x as f32,+ content_top as f32,+ menu_size as f32,+ menu_size as f32,+ ),+ chrome.control_hover_bg,+ WINDOW_TAB_ADD_BUTTON_RADIUS,+ )?;+ }+ self.paint_snippet_icon_button(+ layers,+ chrome,+ foreground,+ muted_fg,+ content_x,+ content_top,+ menu_size,+ tree_button_icon,+ UIItemType::RightSidebarNoteTreeToggle,+ )?;+ }+ let menu_x = content_x + content_width.saturating_sub(menu_size);+ if self.is_pointer_over_ui_rect(menu_x, content_top, menu_size, menu_size) {+ self.fill_rounded_rectangle(+ layers,+ 2,+ euclid::rect(+ menu_x as f32,+ content_top as f32,+ menu_size as f32,+ menu_size as f32,+ ),+ chrome.control_hover_bg,+ WINDOW_TAB_ADD_BUTTON_RADIUS,+ )?;+ }+ self.paint_snippet_icon_button(+ layers,+ chrome,+ foreground,+ muted_fg,+ menu_x,+ content_top,+ menu_size,+ SvgIcon::Ellipsis,+ UIItemType::RightSidebarNoteMenu,+ )+ }++ fn request_right_sidebar_note_open(+ &mut self,+ vault_root: PathBuf,+ relative_path: String,+ create: bool,+ project_id: String,+ focus: bool,+ ) -> bool {+ let key = (vault_root.clone(), relative_path.clone());+ if self+ .right_sidebar_note+ .document+ .as_ref()+ .is_some_and(|document| {+ document.vault_root == vault_root && document.relative_path == relative_path+ })+ {+ self.right_sidebar_note_opening = None;+ self.right_sidebar_note_open_failure = None;+ self.right_sidebar_note.load_error = None;+ if focus {+ self.right_sidebar_note.view.focused = true;+ }+ if let Err(err) =+ workspace_threads::set_project_active_note_path(&project_id, Some(&relative_path))+ {+ log::warn!("failed to persist active Note path: {err:#}");+ }+ return true;+ }+ if let Some((failed_key, message)) = self.right_sidebar_note_open_failure.as_ref() {+ if failed_key == &key {+ self.right_sidebar_note.load_error = Some(message.clone());+ return false;+ }+ }+ if self.right_sidebar_note_opening.as_ref() == Some(&key) {+ self.right_sidebar_note.load_error = Some("Opening note…".to_string());+ return false;+ }++ // Keep switching responsive. The immutable save snapshot and the new+ // document read can proceed independently on workers; save completion+ // is session-gated so it cannot publish into the newly bound note.+ if self.right_sidebar_note.document.is_some() {+ self.right_sidebar_note.freeze_live_source();+ self.save_right_sidebar_note_now();+ }+ self.right_sidebar_note_open_generation =+ self.right_sidebar_note_open_generation.wrapping_add(1);+ let generation = self.right_sidebar_note_open_generation;+ self.right_sidebar_note_opening = Some(key.clone());+ self.right_sidebar_note_open_failure = None;+ self.right_sidebar_note.load_error = Some("Opening note…".to_string());+ let Some(window) = self.window.as_ref().cloned() else {+ self.right_sidebar_note_opening = None;+ return false;+ };++ promise::spawn::spawn(async move {+ let worker_root = vault_root.clone();+ let worker_path = relative_path.clone();+ let result = promise::spawn::spawn_into_new_thread(move || {+ open_vault_document(&worker_root, &worker_path, create)+ })+ .await;+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ if term_window.right_sidebar_note_open_generation != generation+ || term_window.right_sidebar_note_opening.as_ref() != Some(&key)+ {+ return;+ }+ term_window.right_sidebar_note_opening = None;+ match result {+ Ok(document) => {+ term_window.right_sidebar_note_open_failure = None;+ term_window.right_sidebar_note.load_error = None;+ term_window.right_sidebar_note.bind_document(document);+ term_window.right_sidebar_note.view.focused = focus;+ term_window.right_sidebar_note_view = RightSidebarNoteView::Editor;+ term_window+ .right_sidebar_note_table_horizontal_offsets+ .clear();+ term_window.right_sidebar_note_table_layouts.clear();+ if let Err(err) = workspace_threads::set_project_active_note_path(+ &project_id,+ Some(&relative_path),+ ) {+ log::warn!("failed to persist active Note path: {err:#}");+ }+ if create {+ term_window.right_sidebar_note_vault_last_scan = None;+ }+ }+ Err(err) => {+ let message = format!("{err:#}");+ term_window.right_sidebar_note.load_error = Some(message.clone());+ term_window.right_sidebar_note_open_failure = Some((key, message));+ }+ }+ term_window.invalidate_window();+ })));+ })+ .detach();+ false+ }++ fn ensure_active_right_sidebar_note_document(&mut self) -> bool {+ let Some(vault) = workspace_threads::space_note_vault(&self.active_space_id) else {+ self.right_sidebar_note.clear_document(Some(+ "Choose an existing Vault or create a new one to start Notes.".to_string(),+ ));+ return false;+ };+ let Some(project_id) =+ workspace_threads::active_project_id_for_space(&self.active_space_id)+ else {+ self.right_sidebar_note+ .clear_document(Some("No active Project in this Space.".to_string()));+ return false;+ };++ // The persisted active path is updated only after the worker has+ // successfully opened the clicked file. Until then it still names the+ // old document. Re-applying it from paint would cancel the user's new+ // request before its completion callback can bind the document.+ if note_open_pending_for_vault(self.right_sidebar_note_opening.as_ref(), &vault.root) {+ return self.right_sidebar_note.document.is_some();+ }++ let relative_path = match workspace_threads::project_active_note_path(&project_id) {+ Some(path) => path,+ None => {+ if self.right_sidebar_note_vault_index_root.as_ref() != Some(&vault.root)+ || self.right_sidebar_note_vault_indexing+ {+ self.right_sidebar_note.load_error = Some("Indexing Vault…".to_string());+ return false;+ }+ self.right_sidebar_note_vault_paths+ .iter()+ .find(|path| {+ Path::new(path)+ .extension()+ .and_then(|extension| extension.to_str())+ .is_some_and(|extension| extension.eq_ignore_ascii_case("md"))+ })+ .cloned()+ .unwrap_or_else(|| "Untitled.md".to_string())+ }+ };+ let create = !vault.root.join(&relative_path).exists();+ self.request_right_sidebar_note_open(vault.root, relative_path, create, project_id, false)+ }++ fn schedule_right_sidebar_note_image(&mut self, source: RightSidebarNoteImageSource) {+ if self.right_sidebar_note_images.contains_key(&source)+ || self+ .right_sidebar_note_image_failures+ .get(&source)+ .is_some_and(|failed| failed.elapsed() < Duration::from_secs(60))+ || !self+ .right_sidebar_note_images_loading+ .insert(source.clone()){return;}let Some(window) = self.window.as_ref().cloned() else {- self.right_sidebar_note_images_loading.remove(&path);+ self.right_sidebar_note_images_loading.remove(&source);return;};promise::spawn::spawn(async move {- let load_path = path.clone();- let result =- promise::spawn::spawn_into_new_thread(move || load_file_preview_image(&load_path))- .await;+ let load_source = source.clone();+ let result = promise::spawn::spawn_into_new_thread(move || match load_source {+ RightSidebarNoteImageSource::Local(path) => load_file_preview_image(&path),+ RightSidebarNoteImageSource::Remote(url) => {+ let image = load_remote_image(&url)?;+ let encoded_bytes = image.bytes.len();+ let width = image.width;+ let height = image.height;+ Ok(RightSidebarFilePreviewImage {+ data: Arc::new(ImageData::with_data(image.into_image_data())),+ width,+ height,+ encoded_bytes,+ })+ }+ })+ .await;window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {- term_window.right_sidebar_note_images_loading.remove(&path);+ term_window+ .right_sidebar_note_images_loading+ .remove(&source);match result {Ok(image) => {+ term_window+ .right_sidebar_note_image_failures+ .remove(&source);term_window.right_sidebar_note_image_order- .retain(|cached| cached != &path);+ .retain(|cached| cached != &source);term_window.right_sidebar_note_image_order- .push_back(path.clone());- term_window.right_sidebar_note_images.insert(path, image);+ .push_back(source.clone());+ term_window+ .right_sidebar_note_images+ .insert(source.clone(), image);while term_window.right_sidebar_note_image_order.len()> NOTE_IMAGE_CACHE_CAPACITY+ || term_window+ .right_sidebar_note_images+ .values()+ .map(|image| image.encoded_bytes)+ .sum::<usize>()+ > NOTE_IMAGE_CACHE_MAX_ENCODED_BYTES{if let Some(expired) =term_window.right_sidebar_note_image_order.pop_front()@@ -4941,7 +7449,10 @@ impl crate::TermWindow {}}Err(err) => {- log::warn!("unable to render Note image {}: {err:#}", path.display());+ term_window+ .right_sidebar_note_image_failures+ .insert(source.clone(), Instant::now());+ log::warn!("unable to render Note image {:?}: {err:#}", source);}}term_window.invalidate_window();@@ -4959,15 +7470,14 @@ impl crate::TermWindow {y: f32,width: f32,height: f32,+ clip_top: f32,+ clip_bottom: f32,) -> anyhow::Result<()> {if image.width == 0 || image.height == 0 || width <= 0.0 || height <= 0.0 {return Ok(());}- let scale = (width / image.width as f32)- .min(height / image.height as f32)- .min(1.0);- let draw_width = (image.width as f32 * scale).max(1.0);- let draw_height = (image.height as f32 * scale).max(1.0);+ let (draw_width, draw_height) =+ note_image_display_size(image.width, image.height, width, height);let draw_x = x + (width - draw_width) / 2.0;let draw_y = y + (height - draw_height) / 2.0;let Some(gl_state) = self.render_state.as_ref() else {@@ -4979,16 +7489,38 @@ impl crate::TermWindow {.cached_image(&image.data, None, self.allow_images).context("right sidebar Note image")?;self.update_next_frame_time(next_due);+ let texture = sprite.texture_coords();+ let Some(clip) = clip_note_texture(+ draw_x,+ draw_y,+ draw_x + draw_width,+ draw_y + draw_height,+ texture.min_x(),+ texture.min_y(),+ texture.max_x(),+ texture.max_y(),+ x,+ clip_top,+ x + width,+ clip_bottom,+ ) else {+ return Ok(());+ };let left_offset = self.dimensions.pixel_width as f32 / 2.0;let top_offset = self.dimensions.pixel_height as f32 / 2.0;let mut quad = layers.allocate(2)?;quad.set_position(- draw_x - left_offset,- draw_y - top_offset,- draw_x + draw_width - left_offset,- draw_y + draw_height - top_offset,+ clip.left - left_offset,+ clip.top - top_offset,+ clip.right - left_offset,+ clip.bottom - top_offset,+ );+ quad.set_texture_discrete(+ clip.texture_left,+ clip.texture_right,+ clip.texture_top,+ clip.texture_bottom,);- quad.set_texture(sprite.texture_coords());quad.set_hsv(None);quad.set_has_color(true);quad.set_fg_color(LinearRgba::with_components(1.0, 1.0, 1.0, 1.0));@@ -5546,6 +8078,30 @@ impl crate::TermWindow {)}+ fn paint_right_sidebar_note_top_fade(+ &mut self,+ layers: &mut TripleLayerQuadAllocator,+ chrome: UiPalette,+ x: usize,+ y: usize,+ width: usize,+ height: usize,+ ) -> anyhow::Result<()> {+ if width == 0 || height == 0 {+ return Ok(());+ }+ let opaque_height = self.ui_px(12).min(height);+ self.paint_right_sidebar_file_mask(layers, chrome, x, y, width, opaque_height)?;+ self.paint_right_sidebar_file_top_fade(+ layers,+ chrome,+ x,+ y + opaque_height,+ width,+ height.saturating_sub(opaque_height),+ )+ }+fn paint_right_sidebar_file_mask(&mut self,layers: &mut TripleLayerQuadAllocator,@@ -6601,7 +9157,7 @@ impl crate::TermWindow {let y = line_y as f32;if line.spans.is_empty() {- self.paint_cached_ui_shape_clipped(+ self.paint_cached_ui_shape_pixel_clipped(layers,&ui_metrics,&shaped,@@ -6613,7 +9169,7 @@ impl crate::TermWindow {)?;} else {let colors = self.cached_full_line_colors(line_index, line);- self.paint_cached_ui_shape_clipped(+ self.paint_cached_ui_shape_pixel_clipped(layers,&ui_metrics,&shaped,@@ -7950,11 +10506,7 @@ fn syntax_color(kind: HighlightKind, use_dark_theme: bool) -> LinearRgba {}fn preview_line_count(lines: &[RightSidebarFilePreviewLine]) -> usize {- if lines.is_empty() {- 1- } else {- lines.len()- }+ if lines.is_empty() { 1 } else { lines.len() }}fn decimal_digit_count(mut value: usize) -> usize {@@ -8313,6 +10865,7 @@ fn load_file_preview_image(path: &Path) -> anyhow::Result<RightSidebarFilePreviedata: Arc::new(ImageData::with_data(image_data)),width,height,+ encoded_bytes: metadata.len() as usize,})}@@ -8407,8 +10960,8 @@ impl RightSidebarFileCharBag {/// `Arc<RightSidebarFileIndex>` instead of each scanning and holding its own/// copy. Only weak refs live here, so an index is freed the moment the last/// window drops its strong ref (e.g. via the idle-release path).-fn shared_file_index_registry(-) -> &'static Mutex<HashMap<(PathBuf, String), Weak<RightSidebarFileIndex>>> {+fn shared_file_index_registry()+-> &'static Mutex<HashMap<(PathBuf, String), Weak<RightSidebarFileIndex>>> {static REGISTRY: OnceLock<Mutex<HashMap<(PathBuf, String), Weak<RightSidebarFileIndex>>>> =OnceLock::new();REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))@@ -9017,27 +11570,32 @@ fn snippet_cursor_visible(now_ms: u128, blink_ms: u64) -> bool {#[cfg(test)]mod tests {use super::{- build_right_sidebar_file_index, full_line_colors_by_byte,+ FILE_PREVIEW_MAX_BYTES, NOTE_CODE_BLOCK_RADIUS, NOTE_CODE_HEADER_HEIGHT,+ NoteApproximateTextMetrics, NoteCodeHighlightEntry, NoteCodeHighlightState,+ approximate_note_text_width, build_right_sidebar_file_index, clip_note_texture,+ full_line_colors_by_byte,image_pixels_within_preview_budget, load_file_preview, load_file_preview_image,- naturalish_cmp, note_code_highlight_lines, note_code_row_height,- open_with_candidate_allowed, path_key, preview_line_count, preview_lines_from_text,- preview_plain_lines_from_text, preview_text_range, preview_visible_colored,- preview_visible_line_range, right_sidebar_file_browse_rows_from_index,- right_sidebar_file_row_metrics, right_sidebar_open_with_cache_key,+ naturalish_cmp, note_code_highlight_key, note_code_highlight_lines, note_code_row_height,+ note_image_display_size, note_open_pending_for_vault, open_with_candidate_allowed,+ path_key, preview_line_count, preview_lines_from_text, preview_plain_lines_from_text,+ preview_text_range, preview_visible_colored, preview_visible_line_range,+ right_sidebar_file_browse_rows_from_index, right_sidebar_file_row_metrics,+ right_sidebar_open_with_cache_key, scrollable_note_table_columns,search_right_sidebar_file_index, snippet_cursor_visible, snippet_run_buffer,- sorted_open_with_candidates, visible_file_row_range, wrap_snippet_text_for_width,- FILE_PREVIEW_MAX_BYTES, NOTE_CODE_BLOCK_RADIUS, NOTE_CODE_HEADER_HEIGHT,+ sorted_open_with_candidates, virtual_note_line_range, visible_code_block_rounded_edges,+ visible_file_row_range, wrap_snippet_text_for_width,};- use crate::markdown_editor::ProjectedCodeBlock;+ use crate::markdown_editor::{NoteLineGeometry, ProjectedCodeBlock};use crate::termwindow::{RightSidebarFilePreviewLine, RightSidebarFilePreviewSpan};use crate::utilsprites::RenderMetrics;use std::collections::HashSet;use std::fs;use std::io::Cursor;+ use std::sync::Arc;use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};use wezterm_font::units::PixelLength;- use window::color::LinearRgba;use window::Size;+ use window::color::LinearRgba;fn test_render_metrics(cell_height: isize, cell_width: isize) -> RenderMetrics {RenderMetrics {@@ -9050,6 +11608,89 @@ mod tests {}}+ #[test]+ fn note_virtualization_keeps_two_viewports_of_overscan() {+ let geometry = (0..1_000)+ .map(|index| NoteLineGeometry {+ top: index as f32 * 10.0,+ height: 10.0,+ gap: 0.0,+ })+ .collect::<Vec<_>>();+ let range = virtual_note_line_range(&geometry, 5_000.0, 100.0);+ assert!(range.start <= 480);+ assert!(range.end >= 530);+ assert!(range.len() < 60, "virtual range was {} rows", range.len());+ }++ #[test]+ fn note_images_scale_responsively_without_escaping_the_viewport() {+ assert_eq!(note_image_display_size(0, 100, 600.0, 500.0), (0.0, 0.0));+ assert_eq!(+ note_image_display_size(200, 100, 600.0, 500.0),+ (600.0, 300.0)+ );+ assert_eq!(+ note_image_display_size(1200, 2400, 600.0, 500.0),+ (250.0, 500.0)+ );+ }++ #[test]+ fn note_images_clip_position_and_texture_at_the_body_edges() {+ let clip = clip_note_texture(+ 0.0, 0.0, 100.0, 100.0, 0.0, 0.0, 1.0, 1.0, 10.0, 25.0, 90.0, 75.0,+ )+ .unwrap();+ assert_eq!(clip.left, 10.0);+ assert_eq!(clip.top, 25.0);+ assert_eq!(clip.right, 90.0);+ assert_eq!(clip.bottom, 75.0);+ assert_eq!(clip.texture_left, 0.1);+ assert_eq!(clip.texture_top, 0.25);+ assert_eq!(clip.texture_right, 0.9);+ assert_eq!(clip.texture_bottom, 0.75);+ }++ #[test]+ fn background_note_width_does_not_double_count_cjk_or_emoji() {+ let metrics = NoteApproximateTextMetrics {+ latin: 5.0,+ space: 3.0,+ wide: 10.0,+ };+ assert_eq!(approximate_note_text_width("abc", metrics), 15.0);+ assert_eq!(approximate_note_text_width("a b", metrics), 13.0);+ assert_eq!(approximate_note_text_width("系统", metrics), 20.0);+ assert_eq!(approximate_note_text_width("👨👩👧👦", metrics), 10.0);++ let mixed = "alpha:示例 beta";+ let all_full_width = mixed.chars().count() as f32 * metrics.wide;+ assert!(approximate_note_text_width(mixed, metrics) < all_full_width * 0.7);+ }++ #[test]+ fn pending_note_open_wins_over_the_old_persisted_active_path() {+ let root = std::path::PathBuf::from("/vault");+ let opening = (root.clone(), "Second.md".to_string());+ assert!(note_open_pending_for_vault(Some(&opening), &root));+ assert!(!note_open_pending_for_vault(+ Some(&opening),+ std::path::Path::new("/another-vault")+ ));+ }++ #[test]+ fn wide_note_tables_keep_natural_width_for_horizontal_scrolling() {+ let widths = scrollable_note_table_columns(&[260.0, 240.0, 220.0], 400.0, 120.0, 480.0);+ assert_eq!(widths, vec![260.0, 240.0, 220.0]);+ assert!(widths.iter().sum::<f32>() > 400.0);++ let narrow = scrollable_note_table_columns(&[20.0, 40.0], 400.0, 120.0, 480.0);+ assert_eq!(narrow.iter().sum::<f32>(), 400.0);+ assert!(narrow.iter().all(|width| *width >= 120.0));+ }+#[test]fn note_code_highlighting_resolves_aliases_and_utf8_byte_colors() {assert!(thinkterm_syntax::detect_fence("python").is_some());@@ -9074,6 +11715,51 @@ mod tests {);}+ #[test]+ fn note_code_highlight_cache_is_content_based_and_keeps_previous_colors() {+ let code = |start: usize, text: &str, language: &str| ProjectedCodeBlock {+ source: start..start + text.len() + 12,+ content: start + 6..start + 6 + text.len(),+ text: text.to_string(),+ language: Some(language.to_string()),+ };+ let python = code(0, "print(1)\n", "python");+ let shifted_alias = code(200, "print(1)\n", "py");+ let changed = code(0, "print(2)\n", "python");+ let key = note_code_highlight_key(&python).unwrap();+ assert_eq!(key, note_code_highlight_key(&shifted_alias).unwrap());+ let changed_key = note_code_highlight_key(&changed).unwrap();+ assert_ne!(key, changed_key);++ let empty = Arc::new(vec![vec![]]);+ let entry = Arc::new(NoteCodeHighlightEntry {+ key,+ source: Arc::from(python.text.as_str()),+ light: Arc::clone(&empty),+ dark: Arc::clone(&empty),+ });+ let mut state = NoteCodeHighlightState::default();+ state.insert_cache(Arc::clone(&entry));+ state.remember_block(python.source.start, Arc::clone(&entry));+ assert!(state.cached(key, &python.text).is_some());+ assert!(state.cached(key, "hash collision guard").is_none());+ assert!(+ state+ .previous_for_block(python.source.start, changed_key.language)+ .is_some()+ );++ let generation = state+ .schedule_block(python.source.start, changed_key)+ .unwrap();+ assert!(generation > 0);+ assert!(+ state+ .schedule_block(python.source.start, changed_key)+ .is_none()+ );+ }+#[test]fn note_code_row_heights_form_one_continuous_block() {assert_eq!(note_code_row_height(0, 3, false, 20.0, 38.0, 9.0), 67.0);@@ -9083,6 +11769,26 @@ mod tests {assert_eq!(note_code_row_height(1, 3, true, 20.0, 38.0, 9.0), 0.0);}+ #[test]+ fn clipped_code_blocks_only_round_real_visible_edges() {+ assert_eq!(+ visible_code_block_rounded_edges(20.0, 80.0, 0.0, 100.0),+ (true, true)+ );+ assert_eq!(+ visible_code_block_rounded_edges(-20.0, 80.0, 0.0, 100.0),+ (false, true)+ );+ assert_eq!(+ visible_code_block_rounded_edges(20.0, 120.0, 0.0, 100.0),+ (true, false)+ );+ assert_eq!(+ visible_code_block_rounded_edges(-20.0, 120.0, 0.0, 100.0),+ (false, false)+ );+ }+#[test]fn note_code_block_uses_panel_radius_not_capsule_radius() {assert!(NOTE_CODE_BLOCK_RADIUS < NOTE_CODE_HEADER_HEIGHT as f32 / 2.0);@@ -9347,7 +12053,7 @@ mod tests {assert!(image_pixels_within_preview_budget(1920, 1080)); // 2 MPassert!(image_pixels_within_preview_budget(4096, 2160)); // ~8.8 MP (4K)assert!(image_pixels_within_preview_budget(4000, 4000)); // 16 MP (== budget)- // Bombs are rejected, and the u64 product cannot overflow.+ // Bombs are rejected, and the u64 product cannot overflow.assert!(!image_pixels_within_preview_budget(8000, 8000)); // 64 MPassert!(!image_pixels_within_preview_budget(100_000, 100_000));assert!(!image_pixels_within_preview_budget(u32::MAX, u32::MAX));diff --git a/wezterm-gui/src/termwindow/ui/sidebar.rs b/wezterm-gui/src/termwindow/ui/sidebar.rsindex 5f531783..f2765770 100644--- a/wezterm-gui/src/termwindow/ui/sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/sidebar.rs@@ -2364,6 +2364,23 @@ impl crate::TermWindow {rect: RectF,color: LinearRgba,radius: f32,+ ) -> anyhow::Result<()> {+ self.fill_vertically_rounded_rectangle(layers, layer_num, rect, color, radius, true, true)+ }++ /// Fill a rectangle whose top and bottom corner pairs can be rounded+ /// independently. Scrollable surfaces use this to preserve the real edge's+ /// corners while keeping a viewport-created cut edge square.+ #[allow(clippy::too_many_arguments)]+ pub(crate) fn fill_vertically_rounded_rectangle(+ &self,+ layers: &mut TripleLayerQuadAllocator,+ layer_num: usize,+ rect: RectF,+ color: LinearRgba,+ radius: f32,+ round_top: bool,+ round_bottom: bool,) -> anyhow::Result<()> {let radius = snapped_rounded_corner_radius(rect, radius);// Sub-pixel radii round down to a 0px corner sprite (which panics when@@ -2374,46 +2391,76 @@ impl crate::TermWindow {}let corner_size = euclid::size2(radius, radius);- self.poly_quad(- layers,- layer_num,- euclid::point2(rect.min_x(), rect.min_y()),- TOP_LEFT_ROUNDED_CORNER,- 0,- corner_size,- color,- )?- .set_grayscale();- self.poly_quad(- layers,- layer_num,- euclid::point2(rect.max_x() - radius, rect.min_y()),- TOP_RIGHT_ROUNDED_CORNER,- 0,- corner_size,- color,- )?- .set_grayscale();- self.poly_quad(- layers,- layer_num,- euclid::point2(rect.min_x(), rect.max_y() - radius),- BOTTOM_LEFT_ROUNDED_CORNER,- 0,- corner_size,- color,- )?- .set_grayscale();- self.poly_quad(- layers,- layer_num,- euclid::point2(rect.max_x() - radius, rect.max_y() - radius),- BOTTOM_RIGHT_ROUNDED_CORNER,- 0,- corner_size,- color,- )?- .set_grayscale();+ if round_top {+ self.poly_quad(+ layers,+ layer_num,+ euclid::point2(rect.min_x(), rect.min_y()),+ TOP_LEFT_ROUNDED_CORNER,+ 0,+ corner_size,+ color,+ )?+ .set_grayscale();+ self.poly_quad(+ layers,+ layer_num,+ euclid::point2(rect.max_x() - radius, rect.min_y()),+ TOP_RIGHT_ROUNDED_CORNER,+ 0,+ corner_size,+ color,+ )?+ .set_grayscale();+ } else {+ self.filled_rectangle(+ layers,+ layer_num,+ euclid::rect(rect.min_x(), rect.min_y(), radius, radius),+ color,+ )?;+ self.filled_rectangle(+ layers,+ layer_num,+ euclid::rect(rect.max_x() - radius, rect.min_y(), radius, radius),+ color,+ )?;+ }+ if round_bottom {+ self.poly_quad(+ layers,+ layer_num,+ euclid::point2(rect.min_x(), rect.max_y() - radius),+ BOTTOM_LEFT_ROUNDED_CORNER,+ 0,+ corner_size,+ color,+ )?+ .set_grayscale();+ self.poly_quad(+ layers,+ layer_num,+ euclid::point2(rect.max_x() - radius, rect.max_y() - radius),+ BOTTOM_RIGHT_ROUNDED_CORNER,+ 0,+ corner_size,+ color,+ )?+ .set_grayscale();+ } else {+ self.filled_rectangle(+ layers,+ layer_num,+ euclid::rect(rect.min_x(), rect.max_y() - radius, radius, radius),+ color,+ )?;+ self.filled_rectangle(+ layers,+ layer_num,+ euclid::rect(rect.max_x() - radius, rect.max_y() - radius, radius, radius),+ color,+ )?;+ }self.filled_rectangle(layers,diff --git a/wezterm-gui/src/ui/tokens.rs b/wezterm-gui/src/ui/tokens.rsindex 31baa844..ff043827 100644--- a/wezterm-gui/src/ui/tokens.rs+++ b/wezterm-gui/src/ui/tokens.rs@@ -23,6 +23,7 @@ pub(crate) struct UiPalette {pub muted_text: LinearRgba,pub selected_text: LinearRgba,pub scrollbar_thumb: LinearRgba,+ pub spelling_error: LinearRgba,}impl UiPalette {@@ -49,6 +50,7 @@ impl UiPalette {muted_text: rgb(142, 142, 147),selected_text: rgb(255, 255, 255),scrollbar_thumb: rgba(60, 60, 67, 0.32),+ spelling_error: rgb(215, 38, 61),},Appearance::Dark | Appearance::DarkHighContrast => Self {window_bg: rgb(25, 25, 26),@@ -71,6 +73,7 @@ impl UiPalette {muted_text: rgb(142, 142, 147),selected_text: rgb(255, 255, 255),scrollbar_thumb: rgba(142, 142, 147, 0.42),+ spelling_error: rgb(255, 69, 58),},}}diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 184b0f8d..e296d057 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -47,6 +47,11 @@ pub struct Space {pub id: SpaceId,pub name: String,pub active_project_id: Option<ProjectId>,+ /// The local Obsidian-compatible Vault shared by every Project in this+ /// Space. The Vault contents remain ordinary user-owned files; ThinkTerm+ /// only persists this binding in its own workspace store.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub note_vault: Option<SpaceVaultBinding>,#[serde(default)]pub is_default: bool,/// When set, this Space is dedicated to a wezterm mux client domain@@ -57,6 +62,13 @@ pub struct Space {pub client_domain: Option<String>,}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+pub struct SpaceVaultBinding {+ pub root: PathBuf,+ #[serde(default)]+ pub managed: bool,+}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]pub struct Project {pub id: ProjectId,@@ -69,6 +81,11 @@ pub struct Project {pub active_thread_id: Option<WorkspaceThreadId>,#[serde(default)]pub threads_collapsed: bool,+ /// Vault-relative Markdown path last opened for this Project. Projects in+ /// the same Space share a Vault but intentionally remember independent+ /// active notes.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub active_note_path: Option<String>,}#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]@@ -571,6 +588,62 @@ pub fn active_space_name(space_id: &str) -> Option<String> {.map(|space| space.name.clone())}+/// Return the Vault binding for a Space. A Space owns exactly one Vault and+/// every Project in that Space sees the same root.+pub fn space_note_vault(space_id: &str) -> Option<SpaceVaultBinding> {+ let mut store = THREAD_STORE.lock();+ if store.normalize_after_load() {+ persist_locked(&store);+ }+ store+ .spaces+ .iter()+ .find(|space| space.id == space_id)+ .and_then(|space| space.note_vault.clone())+}++/// Bind a Space to a local Vault. Managed Vaults are allowed to be created;+/// existing Vaults must already be directories. Canonicalizing here gives the+/// document registry one stable key even when a picker returns a symlinked+/// path.+pub fn set_space_note_vault(+ space_id: &str,+ root: PathBuf,+ managed: bool,+) -> Result<SpaceVaultBinding> {+ if managed {+ fs::create_dir_all(&root)+ .with_context(|| format!("create note vault {}", root.display()))?;+ }+ ensure!(+ root.is_dir(),+ "note vault is not a directory: {}",+ root.display()+ );+ let root = root+ .canonicalize()+ .with_context(|| format!("resolve note vault {}", root.display()))?;+ let binding = SpaceVaultBinding { root, managed };++ let mut store = THREAD_STORE.lock();+ store.normalize_after_load();+ let space = store+ .spaces+ .iter_mut()+ .find(|space| space.id == space_id)+ .with_context(|| format!("unknown Space {space_id}"))?;+ if space.note_vault.as_ref() != Some(&binding) {+ space.note_vault = Some(binding.clone());+ // Folder picking runs its completion on the UI thread. Serializing and+ // fsyncing the complete workspace store here made selecting a Vault+ // visibly stall before Note could even start loading. The shared+ // coalescing worker snapshots the latest store, so rapid changes still+ // persist in order without blocking input.+ schedule_workspace_thread_store_persist();+ }+ Ok(binding)+}+pub fn create_space(name: Option<String>) -> SpaceId {let mut store = THREAD_STORE.lock();store.normalize_after_load();@@ -742,6 +815,7 @@ pub fn default_project_for_space(space_id: &str) -> Project {threads: vec![],active_thread_id: None,threads_collapsed: false,+ active_note_path: None,}}@@ -1278,6 +1352,71 @@ pub fn project_name(project_id: &str) -> Option<String> {.map(|project| project.name.clone())}+pub fn active_project_id_for_space(space_id: &str) -> Option<ProjectId> {+ let mut store = THREAD_STORE.lock();+ if store.normalize_after_load() {+ persist_locked(&store);+ }+ store.active_project_id_for_space(space_id)+}++pub fn project_active_note_path(project_id: &str) -> Option<String> {+ let store = THREAD_STORE.lock();+ store+ .projects+ .iter()+ .find(|project| project.id == project_id)+ .and_then(|project| project.active_note_path.clone())+}++/// Remember a Project's active note independently from its threads. Paths are+/// persisted relative to the Space Vault so moving a Vault does not invalidate+/// every Project selection.+pub fn set_project_active_note_path(project_id: &str, path: Option<&str>) -> Result<bool> {+ let normalized = path.map(normalize_vault_markdown_path).transpose()?;+ let mut store = THREAD_STORE.lock();+ let project = store+ .projects+ .iter_mut()+ .find(|project| project.id == project_id)+ .with_context(|| format!("unknown Project {project_id}"))?;+ if project.active_note_path == normalized {+ return Ok(false);+ }+ project.active_note_path = normalized;+ // Note selection is presentation state and can change several times while+ // the user moves through a Vault. Coalesce those writes off the UI thread+ // while keeping the in-memory value immediately authoritative.+ schedule_workspace_thread_store_persist();+ Ok(true)+}++pub fn normalize_vault_markdown_path(path: &str) -> Result<String> {+ use std::path::Component;++ let trimmed = path.trim();+ ensure!(!trimmed.is_empty(), "note path is empty");+ let path = Path::new(trimmed);+ ensure!(+ path.extension()+ .and_then(|extension| extension.to_str())+ .is_some_and(|extension| extension.eq_ignore_ascii_case("md")),+ "note path must end in .md: {trimmed}"+ );+ let mut components = Vec::new();+ for component in path.components() {+ match component {+ Component::Normal(part) => components.push(part.to_string_lossy().into_owned()),+ Component::CurDir => {}+ Component::ParentDir | Component::RootDir | Component::Prefix(_) => {+ anyhow::bail!("note path must remain inside the Vault: {trimmed}")+ }+ }+ }+ ensure!(!components.is_empty(), "note path is empty");+ Ok(components.join("/"))+}+pub fn project_reveal_path(project_id: &str) -> Option<PathBuf> {let store = THREAD_STORE.lock();store.project_reveal_path(project_id)@@ -1466,6 +1605,7 @@ impl WorkspaceThreadStore {id: DEFAULT_SPACE_ID.to_string(),name: DEFAULT_SPACE_NAME.to_string(),active_project_id: self.active_project_id.clone(),+ note_vault: None,is_default: true,client_domain: None,});@@ -1564,6 +1704,7 @@ impl WorkspaceThreadStore {id: id.clone(),name,active_project_id: None,+ note_vault: None,is_default: false,client_domain,});@@ -2000,6 +2141,7 @@ impl WorkspaceThreadStore {threads: vec![],active_thread_id: None,threads_collapsed: false,+ active_note_path: None,});}@@ -2053,6 +2195,7 @@ impl WorkspaceThreadStore {threads: vec![],active_thread_id: None,threads_collapsed: false,+ active_note_path: None,};let session = WorkspaceThread::new(project_id.clone(), "main".to_string(), None);let thread_id = session.id.clone();@@ -3688,6 +3831,7 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {threads: vec![],active_thread_id: None,threads_collapsed: false,+ active_note_path: None,});}let project = store@@ -3727,6 +3871,7 @@ pub fn adopt_orphan_remote_thread_windows(space_id: &str) -> bool {threads: vec![thread],active_thread_id: Some(thread_id),threads_collapsed: false,+ active_note_path: None,});changed = true;}@@ -3793,6 +3938,7 @@ pub fn ensure_mux_domain_space(domain_name: &str) -> MuxDomainSpacePlan {threads: vec![],active_thread_id: None,threads_collapsed: false,+ active_note_path: None,});}@@ -3960,9 +4106,63 @@ mod tests {threads,active_thread_id: None,threads_collapsed: false,+ active_note_path: None,}}+ #[test]+ fn vault_binding_and_project_note_paths_round_trip() {+ let vault = SpaceVaultBinding {+ root: PathBuf::from("/tmp/ThinkTerm Notes"),+ managed: false,+ };+ let mut store = test_store();+ let space_id = store.spaces[0].id.clone();+ store.spaces[0].note_vault = Some(vault.clone());+ let mut first = test_project_in_space(+ &space_id,+ "project-first",+ "First",+ PathBuf::from("/tmp/first"),+ vec![],+ );+ first.active_note_path = Some("Design/Overview.md".to_string());+ let mut second = test_project_in_space(+ &space_id,+ "project-second",+ "Second",+ PathBuf::from("/tmp/second"),+ vec![],+ );+ second.active_note_path = Some("Daily/Today.md".to_string());+ store.projects.extend([first, second]);++ let encoded = serde_json::to_string(&store).expect("serialize store");+ let decoded: WorkspaceThreadStore =+ serde_json::from_str(&encoded).expect("deserialize store");++ assert_eq!(decoded.spaces[0].note_vault.as_ref(), Some(&vault));+ assert_eq!(+ decoded.projects[0].active_note_path.as_deref(),+ Some("Design/Overview.md")+ );+ assert_eq!(+ decoded.projects[1].active_note_path.as_deref(),+ Some("Daily/Today.md")+ );+ }++ #[test]+ fn vault_markdown_paths_are_portable_and_cannot_escape() {+ assert_eq!(+ normalize_vault_markdown_path("./Design/Overview.MD").unwrap(),+ "Design/Overview.MD"+ );+ assert!(normalize_vault_markdown_path("../outside.md").is_err());+ assert!(normalize_vault_markdown_path("/absolute.md").is_err());+ assert!(normalize_vault_markdown_path("image.png").is_err());+ }+#[test]fn normalize_makes_thread_names_unique_per_project() {let mut store = test_store();@@ -4361,6 +4561,7 @@ mod tests {threads: vec![thread],active_thread_id: None,threads_collapsed: false,+ active_note_path: None,});let state = store@@ -4395,6 +4596,7 @@ mod tests {threads: vec![thread],active_thread_id: None,threads_collapsed: false,+ active_note_path: None,});let plan = storediff --git a/window/Cargo.toml b/window/Cargo.tomlindex d33a2a0e..3ef5cb95 100644--- a/window/Cargo.toml+++ b/window/Cargo.toml@@ -102,6 +102,7 @@ core-foundation.workspace = truecore-graphics.workspace = trueforeign-types.workspace = trueobjc.workspace = true+objc2.workspace = trueobjc2-core-graphics.workspace = trueplist.workspace = trueshlex.workspace = truediff --git a/window/examples/async.rs b/window/examples/async.rsindex 419e7a20..eead961a 100644--- a/window/examples/async.rs+++ b/window/examples/async.rs@@ -88,6 +88,9 @@ impl MyWindow {| WindowEvent::DroppedUrl(_)| WindowEvent::DroppedString(_)| WindowEvent::PerformKeyAssignment(_)+ | WindowEvent::PerformContextMenuAction(_)+ | WindowEvent::NativeTextInputReplace { .. }+ | WindowEvent::ToggleWorkspaceSidebar| WindowEvent::MouseLeave| WindowEvent::SetInnerSizeCompleted => {}}diff --git a/window/src/connection.rs b/window/src/connection.rsindex e58a0e77..a505c3e7 100644--- a/window/src/connection.rs+++ b/window/src/connection.rs@@ -97,11 +97,11 @@ pub trait ConnectionOps {Some(info) => info.rect,None => {log::error!(- "Requested display {} was not found; available displays are: {:?}. \+ "Requested display {} was not found; available displays are: {:?}. \Using primary display instead",- name,- screens.by_name,- );+ name,+ screens.by_name,+ );screens.main.rect}},diff --git a/window/src/lib.rs b/window/src/lib.rsindex cdc574f2..002fd9d3 100644--- a/window/src/lib.rs+++ b/window/src/lib.rs@@ -4,6 +4,7 @@ use config::window::WindowLevel;use config::{ConfigHandle, Dimension, GeometryOrigin};use promise::Future;use std::any::Any;+use std::ops::Range;use std::path::PathBuf;use std::rc::Rc;use thiserror::Error;@@ -57,12 +58,63 @@ pub struct Dimensions {pub dpi: usize,}+#[derive(Debug, Clone, PartialEq)]+pub enum ContextMenuAction {+ KeyAssignment(config::keyassignment::KeyAssignment),+ ApplicationAction(u64),+}++#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct TextCheckCapabilities {+ pub spelling: bool,+ pub suggestions: bool,+ pub ignore: bool,+ pub learn: bool,+}++#[derive(Debug, Clone)]+pub struct TextCheckRequest {+ pub document_id: String,+ pub request_id: u64,+ pub text: String,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct TextCheckIssue {+ /// UTF-8 byte range in `TextCheckRequest::text`.+ pub range: Range<usize>,+ pub suggestions: Vec<String>,+}++#[derive(Debug, Clone)]+pub struct TextCheckResponse {+ pub request_id: u64,+ pub issues: Vec<TextCheckIssue>,+}++#[derive(Debug, Clone)]+pub struct NativeTextHit {+ pub rect: Rect,+ /// UTF-8 byte offset in `NativeTextInputSnapshot::text`.+ pub byte: usize,+}++#[derive(Debug, Clone)]+pub struct NativeTextInputSnapshot {+ pub token: u64,+ pub revision: u64,+ pub source_base: usize,+ pub text: String,+ pub selection: Range<usize>,+ pub hits: Vec<NativeTextHit>,+}+#[derive(Debug, Clone)]pub enum ContextMenuItem {Item {label: String,- icon: Option<String>,- action: config::keyassignment::KeyAssignment,+ icon: Option<ContextMenuIcon>,+ action: ContextMenuAction,checked: bool,enabled: bool,submenu: Vec<ContextMenuItem>,@@ -70,12 +122,180 @@ pub enum ContextMenuItem {Separator,}+/// Platform-neutral menu icon intent. Native macOS menus translate this to a+/// version-safe SF Symbol and fall back to the same bundled Lucide asset used+/// by ThinkTerm's Windows/Linux menu renderer.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum ContextMenuIcon {+ Application,+ Back,+ Check,+ Close,+ Code,+ Collapse,+ Copy,+ Cut,+ Delete,+ Edit,+ Expand,+ ExternalLink,+ File,+ Folder,+ FolderAdd,+ FolderRemove,+ Home,+ Info,+ MoveLeft,+ MoveRight,+ New,+ Note,+ Notification,+ Paste,+ Pin,+ Refresh,+ Redo,+ Save,+ Search,+ Server,+ Settings,+ Sidebar,+ Spellcheck,+ SplitHorizontal,+ SplitVertical,+ Stack,+ Terminal,+ Undo,+ Unpin,+ Vault,+ Warning,+ Window,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct FolderPickerOptions {+ pub title: String,+ pub prompt: String,+}++impl Default for FolderPickerOptions {+ fn default() -> Self {+ Self {+ title: "Open Project".to_string(),+ prompt: "Open".to_string(),+ }+ }+}++impl ContextMenuIcon {+ pub fn sf_symbol_name(self) -> &'static str {+ match self {+ Self::Application => "app",+ Self::Back => "chevron.left",+ Self::Check => "checkmark.circle",+ Self::Close => "xmark",+ Self::Code => "chevron.left.forwardslash.chevron.right",+ Self::Collapse => "rectangle.compress.vertical",+ Self::Copy => "doc.on.doc",+ Self::Cut => "scissors",+ Self::Delete => "trash",+ Self::Edit => "pencil",+ Self::Expand => "rectangle.expand.vertical",+ Self::ExternalLink => "arrow.up.right.square",+ Self::File => "doc",+ Self::Folder | Self::Vault => "folder",+ Self::FolderAdd => "folder.badge.plus",+ Self::FolderRemove => "folder.badge.minus",+ Self::Home => "house",+ Self::Info => "info.circle",+ Self::MoveLeft => "arrow.left",+ Self::MoveRight => "arrow.right",+ Self::New => "plus",+ Self::Note => "square.and.pencil",+ Self::Notification => "bell",+ Self::Paste => "doc.on.clipboard",+ Self::Pin => "pin",+ Self::Refresh => "arrow.clockwise",+ Self::Redo => "arrow.uturn.forward",+ Self::Save => "square.and.arrow.down",+ Self::Search => "magnifyingglass",+ Self::Server => "server.rack",+ Self::Settings => "gearshape",+ Self::Sidebar => "sidebar.leading",+ Self::Spellcheck => "textformat.abc.dottedunderline",+ Self::SplitHorizontal => "rectangle.split.2x1",+ Self::SplitVertical => "rectangle.split.1x2",+ Self::Stack => "square.stack",+ Self::Terminal => "terminal",+ Self::Undo => "arrow.uturn.backward",+ Self::Unpin => "pin.slash",+ Self::Warning => "exclamationmark.circle",+ Self::Window => "macwindow",+ }+ }++ pub fn lucide_svg(self) -> &'static [u8] {+ match self {+ Self::Application => include_bytes!("../../third_party/lucide/icons/app-window.svg"),+ Self::Back | Self::MoveLeft => {+ include_bytes!("../../third_party/lucide/icons/arrow-left.svg")+ }+ Self::Check => include_bytes!("../../third_party/lucide/icons/circle-check.svg"),+ Self::Close => include_bytes!("../../third_party/lucide/icons/x.svg"),+ Self::Code => include_bytes!("../../third_party/lucide/icons/code-xml.svg"),+ Self::Collapse => include_bytes!("../../third_party/lucide/icons/shrink.svg"),+ Self::Copy => include_bytes!("../../third_party/lucide/icons/copy.svg"),+ Self::Cut => include_bytes!("../../third_party/lucide/icons/scissors.svg"),+ Self::Delete => include_bytes!("../../third_party/lucide/icons/trash-2.svg"),+ Self::Edit => include_bytes!("../../third_party/lucide/icons/pencil.svg"),+ Self::Expand => include_bytes!("../../third_party/lucide/icons/expand.svg"),+ Self::ExternalLink => {+ include_bytes!("../../third_party/lucide/icons/external-link.svg")+ }+ Self::File => include_bytes!("../../third_party/lucide/icons/file.svg"),+ Self::Folder => include_bytes!("../../third_party/lucide/icons/folder.svg"),+ Self::FolderAdd => include_bytes!("../../third_party/lucide/icons/folder-plus.svg"),+ Self::FolderRemove => {+ include_bytes!("../../third_party/lucide/icons/folder-minus.svg")+ }+ Self::Home => include_bytes!("../../third_party/lucide/icons/house.svg"),+ Self::Info => include_bytes!("../../third_party/lucide/icons/info.svg"),+ Self::MoveRight => include_bytes!("../../third_party/lucide/icons/arrow-right.svg"),+ Self::New => include_bytes!("../../third_party/lucide/icons/plus.svg"),+ Self::Note => include_bytes!("../../third_party/lucide/icons/notebook-tabs.svg"),+ Self::Notification => include_bytes!("../../third_party/lucide/icons/bell.svg"),+ Self::Paste => include_bytes!("../../third_party/lucide/icons/clipboard-paste.svg"),+ Self::Pin => include_bytes!("../../third_party/lucide/icons/pin.svg"),+ Self::Refresh => include_bytes!("../../third_party/lucide/icons/rotate-ccw.svg"),+ Self::Redo => include_bytes!("../../third_party/lucide/icons/redo.svg"),+ Self::Save => include_bytes!("../../third_party/lucide/icons/save.svg"),+ Self::Search => include_bytes!("../../third_party/lucide/icons/search.svg"),+ Self::Server => include_bytes!("../../third_party/lucide/icons/server.svg"),+ Self::Settings => include_bytes!("../../third_party/lucide/icons/settings.svg"),+ Self::Sidebar => include_bytes!("../../third_party/lucide/icons/panel-left.svg"),+ Self::Spellcheck => include_bytes!("../../third_party/lucide/icons/spell-check.svg"),+ Self::SplitHorizontal => {+ include_bytes!("../../third_party/lucide/icons/square-split-horizontal.svg")+ }+ Self::SplitVertical => {+ include_bytes!("../../third_party/lucide/icons/square-split-vertical.svg")+ }+ Self::Stack => include_bytes!("../../third_party/lucide/icons/square-stack.svg"),+ Self::Terminal => include_bytes!("../../third_party/lucide/icons/terminal.svg"),+ Self::Undo => include_bytes!("../../third_party/lucide/icons/undo.svg"),+ Self::Unpin => include_bytes!("../../third_party/lucide/icons/pin-off.svg"),+ Self::Vault => include_bytes!("../../third_party/lucide/icons/folder-tree.svg"),+ Self::Warning => include_bytes!("../../third_party/lucide/icons/circle-alert.svg"),+ Self::Window => include_bytes!("../../third_party/lucide/icons/panels-top-left.svg"),+ }+ }+}+impl ContextMenuItem {pub fn item(label: impl Into<String>, action: config::keyassignment::KeyAssignment) -> Self {Self::Item {label: label.into(),icon: None,- action,+ action: ContextMenuAction::KeyAssignment(action),checked: false,enabled: true,submenu: vec![],@@ -84,13 +304,24 @@ impl ContextMenuItem {pub fn item_with_icon(label: impl Into<String>,- icon: impl Into<String>,+ icon: ContextMenuIcon,action: config::keyassignment::KeyAssignment,) -> Self {Self::Item {label: label.into(),- icon: Some(icon.into()),- action,+ icon: Some(icon),+ action: ContextMenuAction::KeyAssignment(action),+ checked: false,+ enabled: true,+ submenu: vec![],+ }+ }++ pub fn application_item(label: impl Into<String>, action_id: u64) -> Self {+ Self::Item {+ label: label.into(),+ icon: None,+ action: ContextMenuAction::ApplicationAction(action_id),checked: false,enabled: true,submenu: vec![],@@ -104,6 +335,13 @@ impl ContextMenuItem {self}+ pub fn with_icon(mut self, icon_value: ContextMenuIcon) -> Self {+ if let Self::Item { icon, .. } = &mut self {+ *icon = Some(icon_value);+ }+ self+ }+pub fn checked(mut self, checked_value: bool) -> Self {if let Self::Item { checked, .. } = &mut self {*checked = checked_value;@@ -115,7 +353,22 @@ impl ContextMenuItem {Self::Item {label: label.into(),icon: None,- action: config::keyassignment::KeyAssignment::Nop,+ action: ContextMenuAction::KeyAssignment(config::keyassignment::KeyAssignment::Nop),+ checked: false,+ enabled: true,+ submenu: items,+ }+ }++ pub fn submenu_with_icon(+ label: impl Into<String>,+ icon: ContextMenuIcon,+ items: Vec<ContextMenuItem>,+ ) -> Self {+ Self::Item {+ label: label.into(),+ icon: Some(icon),+ action: ContextMenuAction::KeyAssignment(config::keyassignment::KeyAssignment::Nop),checked: false,enabled: true,submenu: items,@@ -250,6 +503,13 @@ pub enum WindowEvent {AdviseDeadKeyStatus(DeadKeyStatus),+ NativeTextInputReplace {+ token: u64,+ revision: u64,+ source_range: Range<usize>,+ text: String,+ },+/// Called to handle a raw key event, prior to any dead key,/// keymap composition or other higher level treatment./// If you handle this key event, you must call@@ -283,6 +543,9 @@ pub enum WindowEvent {/// Called by menubar dispatching stuff on some systemsPerformKeyAssignment(config::keyassignment::KeyAssignment),+ /// Dispatches an application-private action selected from a native menu.+ PerformContextMenuAction(u64),+AdviseModifiersLedStatus(Modifiers, KeyboardLedStatus),}@@ -349,6 +612,14 @@ pub trait WindowOps {callback(None);}+ fn pick_folder_async_with_options(+ &self,+ _options: FolderPickerOptions,+ callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>,+ ) {+ self.pick_folder_async(callback);+ }+/// Show a native picker for choosing an application (macOS: .app bundle,/// Windows: .exe, Linux: .desktop entry or executable).fn pick_app_async(&self, callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {@@ -395,6 +666,27 @@ pub trait WindowOps {/// the platform specific input method editorfn set_text_cursor_position(&self, _cursor: Rect) {}+ /// Exposes bounded custom-editor text to native text input services.+ fn set_native_text_input_snapshot(&self, _snapshot: Option<NativeTextInputSnapshot>) {}++ /// Show the platform's dictionary/definition UI for a piece of text.+ fn show_text_definition(&self, _text: &str, _anchor: Rect) {}++ fn text_check_capabilities(&self) -> TextCheckCapabilities {+ TextCheckCapabilities::default()+ }++ fn request_text_check(&self, request: TextCheckRequest) -> Future<TextCheckResponse> {+ Future::ok(TextCheckResponse {+ request_id: request.request_id,+ issues: vec![],+ })+ }++ fn ignore_spelling_word(&self, _document_id: &str, _word: &str) {}++ fn learn_spelling_word(&self, _word: &str) {}+/// Initiate textual transfer from the clipboardfn get_clipboard(&self, clipboard: Clipboard) -> Future<String>;diff --git a/window/src/os/macos/app.rs b/window/src/os/macos/app.rsindex d5501594..58d9097e 100644--- a/window/src/os/macos/app.rs+++ b/window/src/os/macos/app.rs@@ -151,6 +151,7 @@ extern "C" fn wezterm_perform_key_assignment(conn.dispatch_app_event(ApplicationEvent::PerformKeyAssignment(action));}}+ Some(RepresentedItem::ContextMenuAction(_)) => {}None => {}}}diff --git a/window/src/os/macos/menu.rs b/window/src/os/macos/menu.rsindex 04e67652..e235c5de 100644--- a/window/src/os/macos/menu.rs+++ b/window/src/os/macos/menu.rs@@ -1,5 +1,6 @@use crate::macos::{nsstring, nsstring_to_str};use crate::superclass;+use crate::{ContextMenuAction, ContextMenuIcon};pub use cocoa::appkit::NSEventModifierFlags;use cocoa::appkit::{NSApp, NSApplication, NSMenu, NSMenuItem};pub use cocoa::base::SEL;@@ -191,6 +192,7 @@ pub struct MenuItem {#[derive(Clone, Debug, PartialEq)]pub enum RepresentedItem {KeyAssignment(KeyAssignment),+ ContextMenuAction(ContextMenuAction),}impl RepresentedItem {@@ -279,7 +281,7 @@ impl MenuItem {}}- pub fn set_system_symbol_image(&self, symbol_name: &str) {+ pub fn set_system_symbol_image(&self, symbol_name: &str) -> bool {unsafe {let ns_image_cls = class!(NSImage);let supports_system_symbols: BOOL = msg_send![@@ -288,7 +290,7 @@ impl MenuItem {];if supports_system_symbols == NO {- return;+ return false;}let image: id = msg_send![@@ -298,11 +300,37 @@ impl MenuItem {];if image.is_null() {- return;+ return false;}let () = msg_send![image, setTemplate:YES];let () = msg_send![*self.item, setImage:image];+ true+ }+ }++ pub fn set_context_menu_icon(&self, icon: ContextMenuIcon) {+ if self.set_system_symbol_image(icon.sf_symbol_name()) {+ return;+ }+ unsafe {+ let bytes = icon.lucide_svg();+ let data: id = msg_send![+ class!(NSData),+ dataWithBytes: bytes.as_ptr()+ length: bytes.len()+ ];+ if data.is_null() {+ return;+ }+ let image: id = msg_send![class!(NSImage), alloc];+ let image: id = msg_send![image, initWithData:data];+ if image.is_null() {+ return;+ }+ let image = StrongPtr::new(image);+ let () = msg_send![*image, setTemplate:YES];+ let () = msg_send![*self.item, setImage:*image];}}diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rsindex c42fb228..2fe76ec2 100644--- a/window/src/os/macos/window.rs+++ b/window/src/os/macos/window.rs@@ -9,11 +9,12 @@ use crate::connection::ConnectionOps;use crate::os::macos::menu::{Menu, MenuItem, RepresentedItem};use crate::parameters::{Border, Parameters, TitleBar};use crate::{- Clipboard, Connection, ContextMenuItem, DeadKeyStatus, Dimensions, Handled, Image, KeyCode,- KeyEvent, Modifiers, MouseButtons, MouseCursor, MouseEvent, MouseEventKind, MousePress, Point,- PreciseScrollDelta, RawKeyEvent, Rect, RequestedWindowGeometry, ResizeIncrement,- ResolvedGeometry, ScreenPoint, ScrollPhase, Size, ULength, WindowDecorations, WindowEvent,- WindowEventSender, WindowOps, WindowState,+ Clipboard, Connection, ContextMenuItem, DeadKeyStatus, Dimensions, FolderPickerOptions,+ Handled, Image, KeyCode, KeyEvent, Modifiers, MouseButtons, MouseCursor, MouseEvent,+ MouseEventKind, MousePress, NativeTextInputSnapshot, Point, PreciseScrollDelta, RawKeyEvent,+ Rect, RequestedWindowGeometry, ResizeIncrement, ResolvedGeometry, ScreenPoint, ScrollPhase,+ Size, TextCheckCapabilities, TextCheckIssue, TextCheckRequest, TextCheckResponse, ULength,+ WindowDecorations, WindowEvent, WindowEventSender, WindowOps, WindowState,};use anyhow::{anyhow, bail, ensure};use async_trait::async_trait;@@ -42,7 +43,7 @@ use objc::declare::ClassDecl;use objc::rc::{StrongPtr, WeakPtr};use objc::runtime::{Class, Object, Protocol, Sel};use objc::*;-use promise::Future;+use promise::{Future, Promise};use raw_window_handle::{AppKitDisplayHandle, AppKitWindowHandle, DisplayHandle, HandleError, HasDisplayHandle,HasWindowHandle, RawDisplayHandle, RawWindowHandle, WindowHandle,@@ -50,6 +51,7 @@ use raw_window_handle::{use std::any::Any;use std::cell::{Cell, RefCell};use std::ffi::{c_void, CStr};+use std::hash::{DefaultHasher, Hash, Hasher};use std::path::{Path, PathBuf};use std::ptr::NonNull;use std::rc::Rc;@@ -78,6 +80,56 @@ fn thinkterm_perf_enabled() -> bool {})}+fn spell_document_tag(document_id: &str) -> NSInteger {+ let mut hasher = DefaultHasher::new();+ document_id.hash(&mut hasher);+ (hasher.finish() & i64::MAX as u64).max(1) as NSInteger+}++fn byte_offset_for_utf16(text: &str, target: usize) -> usize {+ if target == 0 {+ return 0;+ }+ let mut utf16 = 0usize;+ for (byte, ch) in text.char_indices() {+ let next = utf16 + ch.len_utf16();+ if next > target {+ return byte;+ }+ utf16 = next;+ if utf16 == target {+ return byte + ch.len_utf8();+ }+ }+ text.len()+}++fn utf16_offset_for_byte(text: &str, byte: usize) -> usize {+ let byte = byte.min(text.len());+ let mut boundary = byte;+ while boundary > 0 && !text.is_char_boundary(boundary) {+ boundary -= 1;+ }+ text[..boundary].encode_utf16().count()+}++#[cfg(test)]+mod native_text_range_tests {+ use super::{byte_offset_for_utf16, utf16_offset_for_byte};++ #[test]+ fn utf8_and_utf16_offsets_round_trip_at_character_boundaries() {+ let text = "a😀你e\u{301}";+ for (byte, _) in text+ .char_indices()+ .chain(std::iter::once((text.len(), '\0')))+ {+ let utf16 = utf16_offset_for_byte(text, byte);+ assert_eq!(byte_offset_for_utf16(text, utf16), byte);+ }+ }+}+fn macos_current_screen_max_fps() -> Option<usize> {unsafe {let screen = NSScreen::mainScreen(nil);@@ -618,6 +670,7 @@ impl Window {ime_last_event: None,live_resizing: false,ime_text: String::new(),+ native_text_input_snapshot: None,}));let window: id = msg_send![get_window_class(), alloc];@@ -907,6 +960,14 @@ impl WindowOps for Window {}fn pick_folder_async(&self, callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {+ self.pick_folder_async_with_options(FolderPickerOptions::default(), callback);+ }++ fn pick_folder_async_with_options(+ &self,+ options: FolderPickerOptions,+ callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>,+ ) {unsafe {let _pool = NSAutoreleasePool::new(nil);let panel: id = msg_send![class!(NSOpenPanel), openPanel];@@ -916,8 +977,8 @@ impl WindowOps for Window {let () = msg_send![*panel, setAllowsMultipleSelection: NO];let () = msg_send![*panel, setCanCreateDirectories: YES];let () = msg_send![*panel, setResolvesAliases: YES];- let title = nsstring("Open Project");- let prompt = nsstring("Open");+ let title = nsstring(&options.title);+ let prompt = nsstring(&options.prompt);let () = msg_send![*panel, setTitle: *title];let () = msg_send![*panel, setPrompt: *prompt];@@ -1089,6 +1150,60 @@ impl WindowOps for Window {});}+ fn set_native_text_input_snapshot(&self, snapshot: Option<NativeTextInputSnapshot>) {+ Connection::with_window_inner(self.id, move |inner| {+ inner.set_native_text_input_snapshot(snapshot);+ Ok(())+ });+ }++ fn show_text_definition(&self, text: &str, anchor: Rect) {+ let text = text.to_string();+ Connection::with_window_inner(self.id, move |inner| {+ inner.show_text_definition(&text, anchor);+ Ok(())+ });+ }++ fn text_check_capabilities(&self) -> TextCheckCapabilities {+ TextCheckCapabilities {+ spelling: true,+ suggestions: true,+ ignore: true,+ learn: true,+ }+ }++ fn request_text_check(&self, request: TextCheckRequest) -> Future<TextCheckResponse> {+ let mut promise = Promise::new();+ let future = promise+ .get_future()+ .expect("new text-check promise must have a future");+ let promise = Arc::new(Mutex::new(Some(promise)));+ Connection::with_window_inner(self.id, move |inner| {+ inner.request_text_check(request, promise);+ Ok(())+ });+ future+ }++ fn ignore_spelling_word(&self, document_id: &str, word: &str) {+ let document_id = document_id.to_string();+ let word = word.to_string();+ Connection::with_window_inner(self.id, move |inner| {+ inner.ignore_spelling_word(&document_id, &word);+ Ok(())+ });+ }++ fn learn_spelling_word(&self, word: &str) {+ let word = word.to_string();+ Connection::with_window_inner(self.id, move |inner| {+ inner.learn_spelling_word(&word);+ Ok(())+ });+ }+fn get_clipboard(&self, _clipboard: Clipboard) -> Future<String> {Future::result(ClipboardContext::new()@@ -1537,7 +1652,7 @@ impl WindowInner {"",);if let Some(icon) = icon {- menu_item.set_system_symbol_image(&icon);+ menu_item.set_context_menu_icon(icon);}menu_item.set_checked(checked);menu_item.set_enabled(enabled);@@ -1550,7 +1665,8 @@ impl WindowInner {}} else {menu_item.set_target(view);- menu_item.set_represented_item(RepresentedItem::KeyAssignment(action));+ menu_item+ .set_represented_item(RepresentedItem::ContextMenuAction(action));menu.add_item(&menu_item);has_items = true;}@@ -1662,6 +1778,150 @@ impl WindowInner {}}+ fn set_native_text_input_snapshot(&mut self, snapshot: Option<NativeTextInputSnapshot>) {+ if let Some(window_view) = WindowView::get_this(unsafe { &**self.view }) {+ window_view.inner.borrow_mut().native_text_input_snapshot = snapshot;+ }+ if self.config.use_ime {+ unsafe {+ let input_context: id = msg_send![&**self.view, inputContext];+ let () = msg_send![input_context, invalidateCharacterCoordinates];+ }+ }+ }++ fn show_text_definition(&mut self, text: &str, anchor: Rect) {+ if text.trim().is_empty() {+ return;+ }+ unsafe {+ let frame = NSView::frame(*self.view as *mut _);+ let backing_frame = NSView::convertRectToBacking(*self.view as *mut _, frame);+ let scale = if frame.size.width > 0.0 {+ backing_frame.size.width / frame.size.width+ } else {+ 1.0+ };+ let attributed: id = msg_send![class!(NSAttributedString), alloc];+ let attributed: id = msg_send![attributed, initWithString:*nsstring(text)];+ let point = NSPoint::new(+ anchor.origin.x as f64 / scale,+ anchor.origin.y as f64 / scale,+ );+ let (): () = msg_send![+ &**self.view,+ showDefinitionForAttributedString: attributed+ atPoint: point+ ];+ let (): () = msg_send![attributed, release];+ }+ }++ fn request_text_check(+ &mut self,+ request: TextCheckRequest,+ promise: Arc<Mutex<Option<Promise<TextCheckResponse>>>>,+ ) {+ unsafe {+ let _pool = NSAutoreleasePool::new(nil);+ let checker: id = msg_send![class!(NSSpellChecker), sharedSpellChecker];+ let ns_text = nsstring(&request.text);+ let ns_text_for_block = ns_text.clone();+ let request_text = request.text.clone();+ let request_id = request.request_id;+ let document_tag = spell_document_tag(&request.document_id);+ let promise_for_block = Arc::clone(&promise);+ let block = RcBlock::new(+ move |_sequence: NSInteger,+ results: *mut objc2::runtime::AnyObject,+ _orthography: *mut objc2::runtime::AnyObject,+ _word_count: NSInteger| {+ let results = results.cast::<Object>();+ let mut issues = Vec::new();+ if results != nil {+ let count: NSUInteger = msg_send![results, count];+ for index in 0..count {+ let result: id = msg_send![results, objectAtIndex:index];+ let range: NSRange = msg_send![result, range];+ let utf16_start = range.0.location as usize;+ let utf16_end = utf16_start.saturating_add(range.0.length as usize);+ let start = byte_offset_for_utf16(&request_text, utf16_start);+ let end = byte_offset_for_utf16(&request_text, utf16_end).max(start);+ if start == end || end > request_text.len() {+ continue;+ }++ let guesses: id = msg_send![+ checker,+ guessesForWordRange: range+ inString: *ns_text_for_block+ language: nil+ inSpellDocumentWithTag: document_tag+ ];+ let mut suggestions = Vec::new();+ if guesses != nil {+ let guess_count: NSUInteger = msg_send![guesses, count];+ for guess_index in 0..guess_count.min(5) {+ let guess: id = msg_send![guesses, objectAtIndex:guess_index];+ let guess = nsstring_to_str(guess).to_string();+ if !suggestions.contains(&guess) {+ suggestions.push(guess);+ }+ }+ }+ issues.push(TextCheckIssue {+ range: start..end,+ suggestions,+ });+ }+ }+ if let Ok(mut promise) = promise_for_block.lock() {+ if let Some(mut promise) = promise.take() {+ promise.ok(TextCheckResponse { request_id, issues });+ }+ }+ },+ );+ const NS_TEXT_CHECKING_TYPE_SPELLING: NSUInteger = 1 << 1;+ let full_range = NSRange::new(0, request.text.encode_utf16().count() as u64);+ let _: NSInteger = msg_send![+ checker,+ requestCheckingOfString: *ns_text+ range: full_range+ types: NS_TEXT_CHECKING_TYPE_SPELLING+ options: nil+ inSpellDocumentWithTag: document_tag+ completionHandler: &*block+ ];+ }+ }++ fn ignore_spelling_word(&mut self, document_id: &str, word: &str) {+ if word.trim().is_empty() {+ return;+ }+ unsafe {+ let checker: id = msg_send![class!(NSSpellChecker), sharedSpellChecker];+ let word = nsstring(word);+ let (): () = msg_send![+ checker,+ ignoreWord: *word+ inSpellDocumentWithTag: spell_document_tag(document_id)+ ];+ }+ }++ fn learn_spelling_word(&mut self, word: &str) {+ if word.trim().is_empty() {+ return;+ }+ unsafe {+ let checker: id = msg_send![class!(NSSpellChecker), sharedSpellChecker];+ let word = nsstring(word);+ let (): () = msg_send![checker, learnWord: *word];+ }+ }+fn is_zoomed(&self) -> bool {unsafe { msg_send![*self.window, isZoomed] }}@@ -2064,6 +2324,7 @@ struct Inner {live_resizing: bool,ime_text: String,+ native_text_input_snapshot: Option<NativeTextInputSnapshot>,}#[repr(C)]@@ -2512,15 +2773,29 @@ impl WindowView {if inner.ime_text.is_empty() {NSRange::new(NSNotFound as _, 0)} else {- NSRange::new(0, inner.ime_text.len() as u64)+ let start = inner+ .native_text_input_snapshot+ .as_ref()+ .map(|snapshot| utf16_offset_for_byte(&snapshot.text, snapshot.selection.start))+ .unwrap_or(0);+ NSRange::new(start as u64, inner.ime_text.encode_utf16().count() as u64)}} else {NSRange::new(NSNotFound as _, 0)}}- extern "C" fn selected_range(_this: &mut Object, _sel: Sel) -> NSRange {- NSRange::new(NSNotFound as _, 0)+ extern "C" fn selected_range(this: &mut Object, _sel: Sel) -> NSRange {+ let Some(myself) = Self::get_this(this) else {+ return NSRange::new(NSNotFound as _, 0);+ };+ let inner = myself.inner.borrow();+ let Some(snapshot) = inner.native_text_input_snapshot.as_ref() else {+ return NSRange::new(NSNotFound as _, 0);+ };+ let start = utf16_offset_for_byte(&snapshot.text, snapshot.selection.start);+ let end = utf16_offset_for_byte(&snapshot.text, snapshot.selection.end);+ NSRange::new(start as u64, end.saturating_sub(start) as u64)}// Called by the IME when inserting composed text and/or emoji@@ -2539,6 +2814,40 @@ impl WindowView {if let Some(myself) = Self::get_this(this) {let mut inner = myself.inner.borrow_mut();+ if let Some(snapshot) = inner.native_text_input_snapshot.clone() {+ let relative = if replacement_range.0.location == NSNotFound as u64 {+ snapshot.selection.clone()+ } else {+ let start = byte_offset_for_utf16(+ &snapshot.text,+ replacement_range.0.location as usize,+ );+ let end = byte_offset_for_utf16(+ &snapshot.text,+ replacement_range+ .0+ .location+ .saturating_add(replacement_range.0.length)+ as usize,+ );+ start..end.max(start)+ };+ inner.ime_text.clear();+ inner+ .events+ .dispatch(WindowEvent::AdviseDeadKeyStatus(DeadKeyStatus::None));+ inner.events.dispatch(WindowEvent::NativeTextInputReplace {+ token: snapshot.token,+ revision: snapshot.revision,+ source_range: snapshot.source_base + relative.start+ ..snapshot.source_base + relative.end,+ text: s.to_string(),+ });+ inner.ime_last_event.take();+ inner.ime_state = ImeDisposition::Acted;+ return;+ }+let key_is_down = inner.key_is_down.take().unwrap_or(true);let key = KeyCode::composed(s);@@ -2622,25 +2931,70 @@ impl WindowView {}extern "C" fn attributed_substring_for_proposed_range(- _this: &mut Object,+ this: &mut Object,_sel: Sel,- _proposed_range: NSRange,- _actual_range: NSRangePointer,+ proposed_range: NSRange,+ actual_range: NSRangePointer,) -> id {- log::trace!(- "attributedSubstringForProposedRange {:?} {:?}",- _proposed_range,- _actual_range- );- nil+ let Some(myself) = Self::get_this(this) else {+ return nil;+ };+ let inner = myself.inner.borrow();+ let Some(snapshot) = inner.native_text_input_snapshot.as_ref() else {+ return nil;+ };+ let total = snapshot.text.encode_utf16().count();+ let start_utf16 = (proposed_range.0.location as usize).min(total);+ let end_utf16 = start_utf16+ .saturating_add(proposed_range.0.length as usize)+ .min(total);+ let start = byte_offset_for_utf16(&snapshot.text, start_utf16);+ let end = byte_offset_for_utf16(&snapshot.text, end_utf16).max(start);+ if !actual_range.0.is_null() {+ unsafe {+ *actual_range.0 = NSRange::new(+ start_utf16 as u64,+ end_utf16.saturating_sub(start_utf16) as u64,+ );+ }+ }+ let substring = nsstring(&snapshot.text[start..end]);+ unsafe {+ let attributed: id = msg_send![class!(NSAttributedString), alloc];+ let attributed: id = msg_send![attributed, initWithString:*substring];+ let attributed: id = msg_send![attributed, autorelease];+ attributed+ }}extern "C" fn character_index_for_point(- _this: &mut Object,+ this: &mut Object,_sel: Sel,- _point: NSPoint,+ point: NSPoint,) -> NSUInteger {- NSNotFound as _+ let Some(myself) = Self::get_this(this) else {+ return NSNotFound as _;+ };+ let inner = myself.inner.borrow();+ let Some(snapshot) = inner.native_text_input_snapshot.as_ref() else {+ return NSNotFound as _;+ };+ let window: id = unsafe { msg_send![this, window] };+ let window_point: NSPoint = unsafe { msg_send![window, convertPointFromScreen:point] };+ let view_point: NSPoint =+ unsafe { msg_send![this, convertPoint:window_point fromView:nil] };+ let view_rect = NSRect::new(view_point, NSSize::new(1.0, 1.0));+ let backing: NSRect = unsafe { msg_send![this, convertRectToBacking:view_rect] };+ let hit = snapshot.hits.iter().min_by(|a, b| {+ let distance = |hit: &crate::NativeTextHit| {+ let cx = hit.rect.origin.x as f64 + hit.rect.size.width as f64 / 2.0;+ let cy = hit.rect.origin.y as f64 + hit.rect.size.height as f64 / 2.0;+ (cx - backing.origin.x).powi(2) + (cy - backing.origin.y).powi(2)+ };+ distance(a).total_cmp(&distance(b))+ });+ hit.map(|hit| utf16_offset_for_byte(&snapshot.text, hit.byte) as NSUInteger)+ .unwrap_or(NSNotFound as _)}extern "C" fn first_rect_for_character_range(@@ -2663,13 +3017,29 @@ impl WindowView {let scale = frame.size.width / backing_frame.size.width;if let Some(this) = Self::get_this(this) {- let cursor_pos = this- .inner- .borrow()- .text_cursor_position+ let inner = this.inner.borrow();+ let target = inner+ .native_text_input_snapshot+ .as_ref()+ .and_then(|snapshot| {+ let byte = byte_offset_for_utf16(&snapshot.text, range.0.location as usize);+ snapshot+ .hits+ .iter()+ .min_by_key(|hit| hit.byte.abs_diff(byte))+ .map(|hit| hit.rect)+ });+ let cursor_pos = target+ .unwrap_or(inner.text_cursor_position).to_f64().scale(scale, scale);+ if !actual.0.is_null() {+ unsafe {+ *actual.0 = range;+ }+ }+NSRect::new(NSPoint::new(content.origin.x + cursor_pos.min_x(),@@ -2874,6 +3244,19 @@ impl WindowView {.dispatch(WindowEvent::PerformKeyAssignment(action));}}+ Some(RepresentedItem::ContextMenuAction(action)) => {+ if let Some(this) = Self::get_this(this) {+ let event = match action {+ crate::ContextMenuAction::KeyAssignment(action) => {+ WindowEvent::PerformKeyAssignment(action)+ }+ crate::ContextMenuAction::ApplicationAction(action_id) => {+ WindowEvent::PerformContextMenuAction(action_id)+ }+ };+ this.inner.borrow_mut().events.dispatch(event);+ }+ }None => {}}}@@ -3069,15 +3452,31 @@ impl WindowView {horz_delta = horz_delta.trunc();}- if vert_delta.abs() < 1.0 && horz_delta.abs() < 1.0 {+ // Precise devices report pixel deltas. Always dispatch those events,+ // even when the legacy line accumulator has not reached a whole line;+ // pixel-scrolling surfaces (Files/Note/sidebars) consume the precise+ // payload directly while terminal grids keep using the integer kind.+ if vert_delta.abs() < 1.0 && horz_delta.abs() < 1.0 && precise_scroll_delta.is_none() {return;}- let vertical_is_dominant = vert_delta.abs() > horz_delta.abs();+ let vertical_is_dominant = if vert_delta.abs() >= 1.0 || horz_delta.abs() >= 1.0 {+ vert_delta.abs() > horz_delta.abs()+ } else {+ raw_vert_delta.abs() > raw_horz_delta.abs()+ };let kind = if vertical_is_dominant {- MouseEventKind::VertWheel(round_away_from_zero(vert_delta))+ MouseEventKind::VertWheel(if vert_delta.abs() >= 1.0 {+ round_away_from_zero(vert_delta)+ } else {+ 0+ })} else {- MouseEventKind::HorzWheel(round_away_from_zero(horz_delta))+ MouseEventKind::HorzWheel(if horz_delta.abs() >= 1.0 {+ round_away_from_zero(horz_delta)+ } else {+ 0+ })};if thinkterm_perf_enabled() {log::info!(diff --git a/window/src/os/wayland/window.rs b/window/src/os/wayland/window.rsindex e9a43b97..72f742fd 100644--- a/window/src/os/wayland/window.rs+++ b/window/src/os/wayland/window.rs@@ -47,7 +47,7 @@ use wayland_protocols_plasma::blur::client::org_kde_kwin_blur_manager::OrgKdeKwiuse wezterm_font::FontConfiguration;use wezterm_input_types::{KeyboardLedStatus, Modifiers, MouseButtons, MouseEvent, MouseEventKind, MousePress,- ScreenPoint, WindowDecorations,+ PreciseScrollDelta, ScreenPoint, WindowDecorations,};use crate::wayland::WaylandConnection;@@ -772,7 +772,7 @@ impl WaylandWindowInner {let scaled_x = (value_x * factor) + self.hscroll_remainder;let discrete_x = scaled_x.trunc();self.hscroll_remainder = scaled_x - discrete_x;- if discrete_x != 0. {+ if scaled_x.abs() > f64::EPSILON {let event = MouseEvent {kind: MouseEventKind::HorzWheel(-discrete_x as i16),coords: self.last_mouse_coords,@@ -782,7 +782,10 @@ impl WaylandWindowInner {),mouse_buttons: self.mouse_buttons,modifiers: self.modifiers,- precise_scroll_delta: None,+ precise_scroll_delta: Some(PreciseScrollDelta {+ x: -scaled_x as f32,+ y: 0.0,+ }),scroll_phase: None,momentum_phase: None,};@@ -795,7 +798,7 @@ impl WaylandWindowInner {let scaled_y = (value_y * factor) + self.vscroll_remainder;let discrete_y = scaled_y.trunc();self.vscroll_remainder = scaled_y - discrete_y;- if discrete_y != 0. {+ if scaled_y.abs() > f64::EPSILON {let event = MouseEvent {kind: MouseEventKind::VertWheel(-discrete_y as i16),coords: self.last_mouse_coords,@@ -805,7 +808,10 @@ impl WaylandWindowInner {),mouse_buttons: self.mouse_buttons,modifiers: self.modifiers,- precise_scroll_delta: None,+ precise_scroll_delta: Some(PreciseScrollDelta {+ x: 0.0,+ y: -scaled_y as f32,+ }),scroll_phase: None,momentum_phase: None,};diff --git a/window/src/os/windows/window.rs b/window/src/os/windows/window.rsindex 02eb62b2..031e562d 100644--- a/window/src/os/windows/window.rs+++ b/window/src/os/windows/window.rs@@ -2,10 +2,10 @@ use super::*;use crate::connection::ConnectionOps;use crate::parameters::{self, Parameters};use crate::{- Appearance, Clipboard, DeadKeyStatus, Dimensions, Handled, KeyCode, KeyEvent, Modifiers,- MouseButtons, MouseCursor, MouseEvent, MouseEventKind, MousePress, Point, RawKeyEvent, Rect,- RequestedWindowGeometry, ResolvedGeometry, ScreenPoint, ScreenRect, ULength, WindowDecorations,- WindowEvent, WindowEventSender, WindowOps, WindowState,+ Appearance, Clipboard, DeadKeyStatus, Dimensions, FolderPickerOptions, Handled, KeyCode,+ KeyEvent, Modifiers, MouseButtons, MouseCursor, MouseEvent, MouseEventKind, MousePress, Point,+ RawKeyEvent, Rect, RequestedWindowGeometry, ResolvedGeometry, ScreenPoint, ScreenRect, ULength,+ WindowDecorations, WindowEvent, WindowEventSender, WindowOps, WindowState,};use anyhow::{bail, Context};use async_trait::async_trait;@@ -177,7 +177,10 @@ unsafe fn pathbuf_from_shell_string(raw_path: LPWSTR) -> Option<PathBuf> {Some(PathBuf::from(path))}-unsafe fn pick_folder_dialog(hwnd: HWND) -> anyhow::Result<Option<PathBuf>> {+unsafe fn pick_folder_dialog(+ hwnd: HWND,+ picker_options: &FolderPickerOptions,+) -> anyhow::Result<Option<PathBuf>> {let coinit = CoInitializeEx(null_mut(),COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE,@@ -200,8 +203,8 @@ unsafe fn pick_folder_dialog(hwnd: HWND) -> anyhow::Result<Option<PathBuf>> {"CoCreateInstance(FileOpenDialog)",)?;- let title = wide_null("Open Project");- let open = wide_null("Open");+ let title = wide_null(&picker_options.title);+ let open = wide_null(&picker_options.prompt);let mut selected_path = None;let mut result_item: *mut IShellItem = null_mut();let mut raw_path: LPWSTR = null_mut();@@ -1082,10 +1085,18 @@ impl WindowOps for Window {}fn pick_folder_async(&self, callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {+ self.pick_folder_async_with_options(FolderPickerOptions::default(), callback);+ }++ fn pick_folder_async_with_options(+ &self,+ options: FolderPickerOptions,+ callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>,+ ) {let hwnd = self.0 .0;promise::spawn::spawn(async move {let path = unsafe {- match pick_folder_dialog(hwnd) {+ match pick_folder_dialog(hwnd, &options) {Ok(path) => path,Err(err) => {log::warn!("failed to show folder picker: {err:#}");diff --git a/window/src/os/x11/window.rs b/window/src/os/x11/window.rsindex be4d4b33..80e07535 100644--- a/window/src/os/x11/window.rs+++ b/window/src/os/x11/window.rs@@ -576,7 +576,9 @@ impl XWindowInner {self.drag_and_drop.src_window = Some(srcwin);let moretypes = data[1] & 0x01 != 0;let xdndversion = data[1] >> 24 as u8;- log::trace!("ClientMessage {msgtype_name}, Version {xdndversion}, more than 3 types: {moretypes}");+ log::trace!(+ "ClientMessage {msgtype_name}, Version {xdndversion}, more than 3 types: {moretypes}"+ );if !moretypes {self.drag_and_drop.src_types = data[2..].into_iter()@@ -622,7 +624,9 @@ impl XWindowInner {conn.atom_name(self.drag_and_drop.target_type));} else if self.drag_and_drop.src_window != Some(srcwin) {- log::error!("ClientMessage {msgtype_name} received, but no Xdnd in progress or source window mismatch");+ log::error!(+ "ClientMessage {msgtype_name} received, but no Xdnd in progress or source window mismatch"+ );} else if msgtype == conn.atom_xdndposition {self.drag_and_drop.time = data[3];let (x, y) = (data[2] >> 16 as u16, data[2] as u16);diff --git a/window/src/os/x_and_wayland.rs b/window/src/os/x_and_wayland.rsindex dea1188e..795368c4 100644--- a/window/src/os/x_and_wayland.rs+++ b/window/src/os/x_and_wayland.rs@@ -9,8 +9,8 @@ use crate::os::x11::connection::XConnection;use crate::os::x11::window::XWindow;use crate::screen::Screens;use crate::{- Appearance, Clipboard, MouseCursor, Rect, RequestedWindowGeometry, ResizeIncrement,- ScreenPoint, WindowEvent, WindowOps,+ Appearance, Clipboard, FolderPickerOptions, MouseCursor, Rect, RequestedWindowGeometry,+ ResizeIncrement, ScreenPoint, WindowEvent, WindowOps,};use async_trait::async_trait;use config::ConfigHandle;@@ -311,6 +311,14 @@ impl WindowOps for Window {crate::os::xdg_desktop_portal::pick_folder_async(callback);}+ fn pick_folder_async_with_options(+ &self,+ options: FolderPickerOptions,+ callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>,+ ) {+ crate::os::xdg_desktop_portal::pick_folder_async_with_options(options, callback);+ }+fn pick_app_async(&self, callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {crate::os::xdg_desktop_portal::pick_app_async(callback);}diff --git a/window/src/os/xdg_desktop_portal.rs b/window/src/os/xdg_desktop_portal.rsindex f77d3f1b..7ab855ef 100644--- a/window/src/os/xdg_desktop_portal.rs+++ b/window/src/os/xdg_desktop_portal.rs@@ -185,18 +185,19 @@ fn first_file_uri_to_path(.map_err(|()| anyhow::anyhow!("portal uri is not a file path: {uri:?}"))}-pub async fn pick_folder() -> anyhow::Result<Option<PathBuf>> {+pub async fn pick_folder(options: crate::FolderPickerOptions) -> anyhow::Result<Option<PathBuf>> {let connection = zbus::ConnectionBuilder::session()?.build().await?;let proxy = PortalFileChooserProxy::new(&connection).await.context("make file chooser proxy")?;- let mut options = HashMap::new();- options.insert("directory", Value::from(true));- options.insert("modal", Value::from(true));+ let mut portal_options = HashMap::new();+ portal_options.insert("directory", Value::from(true));+ portal_options.insert("modal", Value::from(true));+ portal_options.insert("accept_label", Value::from(options.prompt.as_str()));let handle = proxy- .OpenFile("", "Open Project", options)+ .OpenFile("", &options.title, portal_options).or(async {async_io::Timer::after(std::time::Duration::from_secs(1)).await;Err(std::io::Error::new(@@ -234,8 +235,15 @@ pub async fn pick_folder() -> anyhow::Result<Option<PathBuf>> {}pub fn pick_folder_async(callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>) {+ pick_folder_async_with_options(crate::FolderPickerOptions::default(), callback);+}++pub fn pick_folder_async_with_options(+ options: crate::FolderPickerOptions,+ callback: Box<dyn FnOnce(Option<PathBuf>) + 'static>,+) {promise::spawn::spawn(async move {- let path = match pick_folder().await {+ let path = match pick_folder(options).await {Ok(path) => path,Err(err) => {log::warn!("failed to show xdg-desktop-portal folder picker: {err:#}");