//! The file viewer window. Double-clicking a Markdown, source, plain-text or //! image file in the Files panel opens it in a native window of its own (an //! egui deferred viewport), or in a new tab of that window if it's already //! open: Markdown rendered by `egui_commonmark` (see `crate::markdown`), //! source highlighted by `syntect`, plain text as is, images decoded by the //! `image` crate. The tab in front re-reads its file when it changes on disk, //! so the window can sit beside an editor as a live preview. Text files open //! read-only; the toolbar can switch them to a small editor (see `editor`), //! which a language server helps with source (see `lsp`). The window's UI //! is `crate::ui::viewer`. use std::{ ffi::OsStr, fs::{self, File}, io::{self, Read}, path::{Path, PathBuf}, sync::{ Arc, Mutex, MutexGuard, mpsc::{self, Receiver, TryRecvError}, }, thread, time::{Duration, Instant, SystemTime}, }; use egui::{ ColorImage, Context, Id, TextureFilter, TextureHandle, TextureOptions, ViewportCommand, ViewportId, }; use egui_commonmark::CommonMarkCache; use image::{ DynamicImage, ImageDecoder, ImageReader, ImageResult, imageops::FilterType, metadata::Orientation, }; use crate::{ files::open_with_default_app, markdown::{self, Block, is_markdown}, placement::Placement, ui::{ scratchpad::ScratchpadTab, viewer::{self as view, goto, search, selection}, }, }; pub(crate) mod comment; pub(crate) mod editor; pub(crate) mod lsp; pub(crate) mod syntax; pub use lsp::{LanguageServer, LspSettings, language_servers}; /// A file to open in a tab: in edit mode if `edit`, at `jump` if given. pub(crate) struct Open { pub(crate) path: PathBuf, pub(crate) edit: bool, pub(crate) jump: Option, } /// Extensions (lowercase) of plain-text files. A `.lock` file that `syntax` /// recognizes by name is highlighted instead. const TEXT_EXTENSIONS: [&str; 4] = ["txt", "log", "dat", "lock"]; /// Names (lowercase) of plain-text files that have no extension, or none as /// far as `Path::extension` is concerned: a leading dot starts the name. const TEXT_FILE_NAMES: [&str; 3] = [".gitignore", ".gitattributes", "license"]; /// Extensions (lowercase) of images: the formats enabled on the `image` crate /// in Cargo.toml. const IMAGE_EXTENSIONS: [&str; 5] = ["png", "jpg", "jpeg", "jfif", "bmp"]; /// Zoomed in, image pixels show as crisp squares rather than a blur, as in /// most image viewers. const IMAGE_TEXTURE: TextureOptions = TextureOptions { magnification: TextureFilter::Nearest, ..TextureOptions::LINEAR }; /// The longest side, in pixels, the Files panel's preview (see /// [ImagePreview]) scales an image down to: plenty for a pane at the bottom /// of a side panel, and quick to upload. const PREVIEW_MAX_SIDE: u32 = 2048; /// How often the tab in front checks its file's modification time. The /// others check when they come to the front. pub(crate) const RELOAD_POLL: Duration = Duration::from_secs(1); /// How much of a file a tab reads. The viewer draws on the UI thread, so /// laying out a huge log would stall the whole app; the rest is left to /// "Open with OS default". pub(crate) const MAX_BYTES: u64 = 1 << 20; /// The viewer window's viewport. There's only ever one: files open in its /// tabs. pub(crate) fn window_id() -> ViewportId { ViewportId::from_hash_of("file_viewer") } /// Whether `path` is a file type the viewer shows, so a double-click views it /// here rather than handing it to the OS's default program. pub fn can_view(path: &Path) -> bool { is_markdown(path) || is_text(path) || is_image(path) || syntax::language(path).is_some() } fn lowercase(s: &OsStr) -> String { s.to_string_lossy().to_lowercase() } fn is_text(path: &Path) -> bool { path.extension() .map(lowercase) .is_some_and(|e| TEXT_EXTENSIONS.contains(&e.as_str())) || path .file_name() .map(lowercase) .is_some_and(|n| TEXT_FILE_NAMES.contains(&n.as_str())) } pub fn is_image(path: &Path) -> bool { path.extension() .map(lowercase) .is_some_and(|e| IMAGE_EXTENSIONS.contains(&e.as_str())) } /// How a tab renders its file. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum Kind { Markdown, /// Source text, with its canonical syntax extension. Code(&'static str), /// Plain text, in the monospace font. Text, Image, } impl Kind { fn of(path: &Path) -> Self { if is_markdown(path) { Self::Markdown } else if is_image(path) { Self::Image } else if let Some(language) = syntax::language(path) { Self::Code(language) } else { Self::Text } } fn name(self) -> &'static str { match self { Self::Markdown => "Markdown", Self::Code(_) => "Code", Self::Text => "Text", Self::Image => "Image", } } } /// The viewer window and its tabs. Shared with the window's render callback, /// which egui calls outside the main window's pass, hence the `Arc`. /// Everything runs on the UI thread, so the lock is never contended. #[derive(Default)] pub struct FileViewers { pub(crate) inner: Arc>, } #[derive(Default)] pub(crate) struct Inner { /// The window's tabs, left to right. The window is open while there are /// any. pub(crate) docs: Vec, /// Index into `docs` of the tab in front. pub(crate) active: usize, /// The tab in front last pass, to notice another one coming forward. pub(crate) shown: Option, /// Files to open (or bring to the front and reload, if already open) at /// the end of the main window's next pass. Queued rather than opened /// directly so the Files panel, links clicked in the viewer and go to /// definition share one path. pub(crate) to_open: Vec, /// The language servers of the tabs in edit mode. pub(crate) servers: lsp::Servers, /// Where the window opened. Fixed while it's open: egui moves a window /// whose builder changes. pub(crate) opened_at: Option, /// Where the window last moved or resized to: it opens there next time. /// Saved between runs. pub(crate) placement: Option, /// One Markdown cache for every tab: building it loads syntect's syntax /// and theme sets, so it's created on the first Markdown open, not at /// startup. pub(crate) cache: Option, /// Source of unique tab ids. next_id: u64, /// The bookmark shortcut was pressed in the viewer window, for the main /// window's next pass to act on (see [FileViewers::take_bookmark_key]). pub(crate) bookmark_key: bool, /// The viewer window was closed while tabs have unsaved edits. pub(crate) close_pending: bool, /// The main window was closed while tabs have unsaved edits. pub(crate) quit_pending: bool, } /// One viewer tab: a file, and how it's shown. pub(crate) struct Doc { /// Unique to the tab. egui keeps widget state (scroll positions, the find /// box, the editor's caret) in context-wide memory, so ids salted with it /// give each tab its own. pub(crate) id: Id, pub(crate) path: PathBuf, pub(crate) kind: Kind, /// The file's contents, or why they couldn't be read. pub(crate) content: Result, /// The file's size, when `content` holds only the start of it. pub(crate) truncated: Option, /// Markdown `content` split at its `
` blocks; see /// [markdown::split_details]. Empty for plain text and images. pub(crate) blocks: Vec, /// Which of those `
` sections are open, by index. pub(crate) details_open: Vec, /// Source or plain text laid out (source highlighted incrementally); a /// reload re-highlights only the lines that changed. pub(crate) layout: syntax::Source, /// How many lines text `content` has: what the line numbers count up to. pub(crate) lines: usize, /// An image being decoded on a background thread. decoding: Option, pub(crate) zoom: Zoom, /// Modification time of the file as last read, to notice edits. modified: Option, last_poll: Instant, /// When it last came to the front: a folder tab brings forward its /// file in front last. pub(crate) fronted: Instant, /// Cleared when the user closes the tab; it's dropped at the start of the /// next pass. open: bool, /// A one-off message in the toolbar, e.g. a link whose target is missing. pub(crate) notice: Option, /// Find, for text: the toolbar's second row. pub(crate) search: search::Search, pub(crate) goto: goto::GoTo, /// Present only in edit mode; automatic reloads leave it alone. pub(crate) editor: Option, /// What Tab inserts in edit mode, picked in the toolbar: a tab, or 4 /// spaces as the file opens. pub(crate) tab: ScratchpadTab, /// An action waiting for Save / Discard / Cancel on an unsaved draft. pub(crate) pending: Option, pub(crate) selection: selection::Markdown, } #[derive(Clone, Copy)] pub(crate) enum Action { View, Reload, Close, OpenExternal, } /// What a tab shows. pub(crate) enum Content { /// Markdown, source or plain text: at most [MAX_BYTES] of the file. Text(Arc), Image(Picture), /// An image whose first decode hasn't finished yet. Loading, } /// An image decode running on a background thread; see [spawn_decode]. struct Decoding { rx: Receiver>, /// Set when the file changed, or the tab moved on to another image, /// after this decode began: its result is dropped and the current file /// decoded afresh. stale: bool, } /// An image, uploaded for drawing. pub(crate) struct Picture { pub(crate) texture: TextureHandle, /// The image's own size in pixels. Bigger than the texture when that had /// to be scaled down to the GPU's largest texture size. pub(crate) size: [u32; 2], } /// How an image tab is zoomed. #[derive(Default)] pub(crate) struct Zoom { /// Screen pixels per image pixel, as the user set it. `None` fits the /// image to the tab: shrunk if it's bigger, actual size if not. pub(crate) set: Option, /// The scale the image was last drawn at, for the toolbar. pub(crate) shown: f32, } impl Doc { fn new(ctx: &Context, id: Id, path: PathBuf, kind: Kind) -> Self { let mut doc = Self { id, path, kind, content: Ok(Content::Loading), truncated: None, blocks: Vec::new(), details_open: Vec::new(), layout: syntax::Source::default(), lines: 0, decoding: None, zoom: Zoom::default(), modified: None, last_poll: Instant::now(), fronted: Instant::now(), open: true, notice: None, search: search::Search::default(), goto: goto::GoTo::default(), editor: None, tab: ScratchpadTab::Spaces, pending: None, selection: selection::Markdown::default(), }; doc.reload(ctx); doc } fn reload(&mut self, ctx: &Context) { self.modified = modified_time(&self.path); self.last_poll = Instant::now(); if self.kind == Kind::Image { // The current picture stays up until the new one is ready. One // decode at a time, so holding an arrow key over big photos // doesn't pile up threads: one already running is redone when // it finishes. match &mut self.decoding { Some(decoding) => decoding.stale = true, None => self.start_decode(ctx), } return; } let read = read_text(&self.path); self.selection = selection::Markdown::default(); self.truncated = read.as_ref().ok().and_then(|(_, size)| *size); self.lines = read.as_ref().map_or(0, |(text, _)| { text.bytes().filter(|&b| b == b'\n').count() + 1 }); self.blocks = match (&read, self.kind) { (Ok((text, _)), Kind::Markdown) => markdown::split_details(text), _ => Vec::new(), }; self.content = read .map(|(text, _)| Content::Text(text.into())) .map_err(|e| format!("Couldn't read {}: {e}", self.path.display())); } /// Re-read the file if its modification time changed since it was read. /// Polled at most once per [RELOAD_POLL]. pub(crate) fn reload_if_changed(&mut self, ctx: &Context) { if self.editor.is_some() { return; } if self.last_poll.elapsed() < RELOAD_POLL { return; } self.last_poll = Instant::now(); if modified_time(&self.path) != self.modified { self.reload(ctx); } } fn start_decode(&mut self, ctx: &Context) { let max_side = ctx.input(|i| i.max_texture_side) as u32; self.decoding = Some(Decoding { rx: spawn_decode(ctx, window_id(), self.path.clone(), max_side), stale: false, }); } /// Show the image from [spawn_decode], once it's ready. pub(crate) fn receive_image(&mut self, ctx: &Context) { let Some(decoding) = &self.decoding else { return; }; let decoded = match decoding.rx.try_recv() { Ok(decoded) => decoded, Err(TryRecvError::Empty) => return, // The decoder panicked. Err(TryRecvError::Disconnected) => { Err(format!("Couldn't decode {}", self.path.display())) } }; if decoding.stale { self.start_decode(ctx); return; } self.decoding = None; self.content = decoded.map(|d| { Content::Image(Picture { texture: ctx.load_texture(self.path.to_string_lossy(), d.pixels, IMAGE_TEXTURE), size: d.size, }) }); } /// Show the image `step` places after this one in its folder (before /// it, if negative); see [neighbor_image]. pub(crate) fn navigate(&mut self, ctx: &Context, step: isize) { let Some(path) = neighbor_image(&self.path, step) else { return; }; if path == self.path { return; } self.path = path; self.zoom = Zoom::default(); self.notice = None; self.reload(ctx); } /// The folder holding the file: what the folder tabs group it by. pub(crate) fn folder(&self) -> &Path { self.path.parent().unwrap_or(Path::new("")) } /// The window's title while this tab is in front. pub(crate) fn title(&self) -> String { let name = name(&self.path); let changed = if self.dirty() { " *" } else { "" }; let mode = if self.editor.is_some() { "Edit" } else { self.kind.name() }; format!("{name}{changed} - {mode}") } pub(crate) fn dirty(&self) -> bool { self.editor.as_ref().is_some_and(editor::Editor::dirty) } /// Save's label: Overwrite once it found the file changed on disk. pub(crate) fn save_label(&self) -> &'static str { if self.editor.as_ref().is_some_and(editor::Editor::conflict) { "Overwrite" } else { "Save" } } /// Whether edit mode is available: the whole of a text file is loaded. pub(crate) fn can_edit(&self) -> bool { self.kind != Kind::Image && self.truncated.is_none() && matches!(self.content, Ok(Content::Text(_))) } pub(crate) fn start_editing(&mut self, ctx: &Context) { match editor::Editor::load(&self.path) { Ok(editor) => { self.editor = Some(editor); view::editor::reset(ctx, self.id); self.notice = None; } Err(e) => self.notice = Some(e), } ctx.request_repaint(); } pub(crate) fn save(&mut self, ctx: &Context) -> bool { let Some(editor) = &mut self.editor else { return true; }; match editor.save(&self.path) { Ok(()) => { self.reload(ctx); self.notice = None; ctx.memory_mut(|m| m.request_focus(view::editor::id(self.id))); ctx.request_repaint(); true } Err(e) => { self.notice = Some(e); false } } } pub(crate) fn request(&mut self, ctx: &Context, action: Action) { if self.dirty() { self.pending = Some(action); } else { self.perform(ctx, action); } } pub(crate) fn perform(&mut self, ctx: &Context, action: Action) { self.pending = None; match action { Action::View => { self.editor = None; self.reload(ctx); self.notice = None; } Action::Reload => { let editing = self.editor.take().is_some(); self.reload(ctx); self.notice = None; if editing { self.start_editing(ctx); } } Action::Close => self.open = false, Action::OpenExternal => match open_with_default_app(&self.path) { Ok(()) => self.open = false, Err(e) => self.notice = Some(format!("Couldn't open: {e}")), }, } ctx.request_repaint(); ctx.request_repaint_of(ViewportId::ROOT); } } /// The last component of `path`, or all of it if it has none (e.g. `C:\`). pub(crate) fn name(path: &Path) -> String { path.file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_else(|| path.display().to_string()) } fn modified_time(path: &Path) -> Option { fs::metadata(path).and_then(|m| m.modified()).ok() } /// The image `step` places after `path` in its folder (before it, if /// negative), in the Files panel's order: by name, ignoring case. Wraps /// around at the ends. `path` itself needn't still exist. fn neighbor_image(path: &Path, step: isize) -> Option { let key = |p: &Path| { let name = p.file_name().unwrap_or_default().to_string_lossy(); // Then by exact name, so names differing only in case keep an order. (name.to_lowercase(), name.into_owned()) }; let mut images: Vec = fs::read_dir(path.parent()?) .ok()? .flatten() .filter(|e| e.file_type().is_ok_and(|t| !t.is_dir())) .map(|e| e.path()) .filter(|p| is_image(p)) .collect(); if images.is_empty() { return None; } images.sort_by_cached_key(|p| key(p)); let target = match images.binary_search_by_key(&key(path), |p| key(p)) { Ok(i) => i as isize + step, // Gone from the folder: `i` is where it was. Err(i) => i as isize + step - isize::from(step > 0), }; let i = target.rem_euclid(images.len() as isize) as usize; Some(images.swap_remove(i)) } /// Read the text file at `path`. A file bigger than [MAX_BYTES] is cut at /// the last line break within that, and its size returned alongside. fn read_text(path: &Path) -> io::Result<(String, Option)> { let mut bytes = Vec::new(); File::open(path)? .take(MAX_BYTES + 1) .read_to_end(&mut bytes)?; if bytes.len() as u64 <= MAX_BYTES { return Ok((decode(&bytes), None)); } bytes.truncate(MAX_BYTES as usize); let mut text = decode(&bytes); // Drop the partial last line, and with it any character cut in two. if let Some(end) = text.rfind('\n') { text.truncate(end + 1); } let size = fs::metadata(path).map_or(MAX_BYTES, |m| m.len()); Ok((text, Some(size))) } /// A text file's contents: UTF-16 if it starts with a UTF-16 byte order mark /// (as Windows PowerShell's `>` writes), otherwise UTF-8. Lossy, so a stray /// bad byte doesn't hide the whole file. fn decode(bytes: &[u8]) -> String { let utf16 = |rest: &[u8], from_bytes: fn([u8; 2]) -> u16| { let units = rest.as_chunks::<2>().0.iter().map(|&c| from_bytes(c)); char::decode_utf16(units) .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)) .collect() }; match bytes { [0xFF, 0xFE, rest @ ..] => utf16(rest, u16::from_le_bytes), [0xFE, 0xFF, rest @ ..] => utf16(rest, u16::from_be_bytes), _ => { let text = String::from_utf8_lossy(bytes); text.strip_prefix('\u{feff}').unwrap_or(&text).to_string() } } } /// An image decoded by [decode_image], ready to upload. struct Decoded { pixels: ColorImage, /// The image's own size, before any scaling down. size: [u32; 2], } /// Decode the image at `path` on a background thread, scaled down if a side /// is longer than `max_side`, then repaint window `id` to show it: a big /// photo takes long enough to stall every window. fn spawn_decode( ctx: &Context, id: ViewportId, path: PathBuf, max_side: u32, ) -> Receiver> { let (tx, rx) = mpsc::channel(); let ctx = ctx.clone(); thread::spawn(move || { let decoded = decode_image(&path, max_side) .map_err(|e| format!("Couldn't read {}: {e}", path.display())); // Fails if the window closed meanwhile: nobody's waiting. if tx.send(decoded).is_ok() { ctx.request_repaint_of(id); } }); rx } /// Decode the image at `path`, its format sniffed from the contents rather /// than the extension. It's turned upright per its EXIF orientation, as phone /// photos need, and scaled down if a side is longer than `max_side`. fn decode_image(path: &Path, max_side: u32) -> ImageResult { let mut decoder = ImageReader::open(path)? .with_guessed_format()? .into_decoder()?; // A malformed EXIF block isn't worth refusing the picture over. let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms); let mut image = DynamicImage::from_decoder(decoder)?; image.apply_orientation(orientation); let size = [image.width(), image.height()]; if size[0].max(size[1]) > max_side { image = image.resize(max_side, max_side, FilterType::Triangle); } let rgba = image.into_rgba8(); let pixels = ColorImage::from_rgba_unmultiplied( [rgba.width() as usize, rgba.height() as usize], rgba.as_raw(), ); Ok(Decoded { pixels, size }) } /// The Files panel's preview of the selected image, under its details. /// Decoded in the background like a viewer tab's image, but scaled down /// to at most [PREVIEW_MAX_SIDE]. #[derive(Default)] pub struct ImagePreview { /// The image previewed, and its modification time as selected, so an /// edit (which re-reads the selection's details) re-reads it too. `None` /// when the selection isn't an image. pub(crate) file: Option<(PathBuf, Option)>, /// `file`'s picture, or why it couldn't be read. `None` until decoded. pub(crate) picture: Option>, decoding: Option, } impl ImagePreview { /// Preview `file`, an image's path and modification time, or nothing. /// Call every pass: a new file starts decoding, and a finished decode is /// picked up. pub fn set(&mut self, ctx: &Context, file: Option<(&Path, Option)>) { let current = self.file.as_ref().map(|(p, m)| (p.as_path(), *m)); if current != file { self.file = file.map(|(p, m)| (p.to_path_buf(), m)); self.picture = None; // One decode at a time, as in a viewer tab, so arrowing // through a folder of photos doesn't pile up threads: one already // running is redone when it finishes. match &mut self.decoding { Some(decoding) => decoding.stale = true, None => self.start_decode(ctx), } } self.receive(ctx); } fn start_decode(&mut self, ctx: &Context) { let Some((path, _)) = &self.file else { return; }; let max_side = ctx.input(|i| i.max_texture_side) as u32; let rx = spawn_decode( ctx, ctx.viewport_id(), path.clone(), max_side.min(PREVIEW_MAX_SIDE), ); self.decoding = Some(Decoding { rx, stale: false }); } /// Show the picture from [spawn_decode], once it's ready. fn receive(&mut self, ctx: &Context) { let Some(decoding) = &self.decoding else { return; }; let decoded = match decoding.rx.try_recv() { Ok(decoded) => decoded, Err(TryRecvError::Empty) => return, // The decoder panicked. Err(TryRecvError::Disconnected) => Err("Couldn't decode the image".to_owned()), }; let stale = decoding.stale; self.decoding = None; if stale { self.start_decode(ctx); return; } self.picture = Some(decoded.map(|d| Picture { texture: ctx.load_texture("file_preview", d.pixels, IMAGE_TEXTURE), size: d.size, })); } /// The previewed image's size in pixels, once it's decoded. pub fn size(&self) -> Option<[u32; 2]> { match &self.picture { Some(Ok(picture)) => Some(picture.size), _ => None, } } } impl FileViewers { /// Open `path` in a new tab of the viewer window, opening the window if /// need be; or if it's already open in a tab, bring that to the front and /// reload it. Takes effect in [Self::show], later this pass. pub fn open(&self, path: PathBuf) { self.lock().to_open.push(Open { path, edit: false, jump: None, }); } /// As [Self::open], in edit mode when the file allows it. pub fn edit(&self, path: PathBuf) { self.lock().to_open.push(Open { path, edit: true, jump: None, }); } /// The language server settings, for the Settings window and saving. pub fn lsp_settings(&self) -> LspSettings { self.lock().servers.settings().clone() } /// Apply changed language server settings: servers whose command /// changed are replaced. pub fn set_lsp_settings(&self, settings: LspSettings) { self.lock().servers.set_settings(settings); } /// Whether [TOGGLE_BOOKMARK](crate::ui::terminal::TOGGLE_BOOKMARK) was pressed in the viewer window since last /// asked, so it works from there as from the main one. pub fn take_bookmark_key(&self) -> bool { std::mem::take(&mut self.lock().bookmark_key) } /// Where the window opens: where it was last moved or resized to. pub fn placement(&self) -> Option { self.lock().placement } /// Set where the window opens, e.g. as saved by the last run. pub fn set_placement(&self, placement: Option) { self.lock().placement = placement; } pub(crate) fn lock(&self) -> MutexGuard<'_, Inner> { lock(&self.inner) } } /// A panic mid-render can't leave [Inner] half-updated in a way that matters, /// so recover from poisoning rather than taking every window down with it. pub(crate) fn lock(inner: &Mutex) -> MutexGuard<'_, Inner> { inner.lock().unwrap_or_else(|e| e.into_inner()) } impl Inner { /// Close every tab, and with them the window. pub(crate) fn close_all(&mut self, ctx: &Context) { for doc in &mut self.docs { doc.open = false; } self.close_pending = false; // Its pass stops showing the window. ctx.request_repaint_of(ViewportId::ROOT); } /// Drop the tabs closed since last pass. The tab in front stays there; /// if it closed, the nearest one after it takes its place, or before /// it if it was last: in its folder if any are left there. pub(crate) fn drop_closed(&mut self) { if self.docs.iter().all(|d| d.open) { return; } let front = self.docs.get(self.active).and_then(|doc| { if doc.open { return Some(doc.id); } let after = self.docs[self.active..].iter().filter(|d| d.open); let before = self.docs[..self.active].iter().rev().filter(|d| d.open); let same = |d: &&Doc| d.folder() == doc.folder(); let next = (after.clone().find(same)) .or_else(|| before.clone().find(same)) .or_else(|| after.clone().next()) .or_else(|| before.clone().next()); next.map(|d| d.id) }); self.docs.retain(|d| d.open); self.active = front .and_then(|id| self.docs.iter().position(|d| d.id == id)) .unwrap_or(0); } pub(crate) fn open_now(&mut self, ctx: &Context, open: Open) { let Open { path, edit, jump } = open; let kind = Kind::of(&path); // Compare canonical paths so `./README.md` and `docs/../README.md` // find the same tab. let path = fs::canonicalize(&path).map(strip_verbatim).unwrap_or(path); if self.docs.is_empty() { self.opened_at = self.placement.map(|p| p.on_screen(ctx)); } else { // Focus alone leaves a minimized window minimized. ctx.send_viewport_cmd_to(window_id(), ViewportCommand::Minimized(false)); ctx.send_viewport_cmd_to(window_id(), ViewportCommand::Focus); ctx.request_repaint_of(window_id()); } if let Some(i) = self.docs.iter().position(|d| d.path == path && d.open) { let doc = &mut self.docs[i]; if doc.editor.is_none() { doc.reload(ctx); if edit && doc.can_edit() { doc.start_editing(ctx); } } if let Some(jump) = jump { doc.reveal(ctx, &jump); } self.active = i; return; } let id = Id::new(("file_viewer_tab", self.next_id)); self.next_id += 1; let mut doc = Doc::new(ctx, id, path, kind); if edit && doc.can_edit() { doc.start_editing(ctx); } if let Some(jump) = jump { doc.reveal(ctx, &jump); } // After its folder's other tabs, so each folder's stay together. let at = self .docs .iter() .rposition(|d| d.folder() == doc.folder()) .map_or(self.docs.len(), |i| i + 1); self.docs.insert(at, doc); self.active = at; } } /// Open `path`, a local file linked from `doc`: in a tab of its own if /// it's a type the viewer shows, otherwise (e.g. a folder) with its /// default program. pub(crate) fn open_link(doc: &mut Doc, path: PathBuf, to_open: &mut Vec, ctx: &Context) { if !path.exists() { doc.notice = Some(format!("Link target not found: {}", path.display())); } else if can_view(&path) { to_open.push(Open { path, edit: false, jump: None, }); // The main window's pass is what opens it. ctx.request_repaint_of(ViewportId::ROOT); } else if let Err(e) = open_with_default_app(&path) { doc.notice = Some(format!("Couldn't open {}: {e}", path.display())); } } /// `fs::canonicalize` on Windows returns `\\?\C:\...` paths, which display /// badly and which some programs refuse. Drop the prefix when it's a plain /// drive path. fn strip_verbatim(path: PathBuf) -> PathBuf { let s = path.to_string_lossy(); match s.strip_prefix(r"\\?\") { Some(rest) if !rest.starts_with("UNC\\") => PathBuf::from(rest), _ => path, } }