Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

12.2 KB
Raw Blame
//! A bookmarks bar as browsers have one, under the address bar (Settings › Appearance › "Bookmarks bar", issue 694). A bookmark is a folder or a file of this PC, or a web address; bookmarks can be grouped in folders, which open
//! as menus. The bar is kept in `bookmarks.json` beside `settings.toml`, and it is imported from and exported to the Netscape bookmark
//! file that browsers write (Chrome, Edge, Firefox) and that Clover, the tabs-for-Explorer extension, wrote too.

use std::path::{Path, PathBuf};

use gpui_kit::*;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Bookmark {
    /// A folder or a file (a path), or a web address.
    Link { name: String, target: String },
    /// A group of bookmarks: a menu on the bar.
    Folder { name: String, children: Vec<Bookmark> },
}

impl Bookmark {
    pub fn name(&self) -> &str {
        match self {
            Bookmark::Link { name, .. } | Bookmark::Folder { name, .. } => name,
        }
    }

    /// The bookmark of a folder or file of this PC, under its own name.
    pub fn for_path(path: &Path) -> Self {
        let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.to_string_lossy().into_owned());
        Bookmark::Link { name, target: path.to_string_lossy().into_owned() }
    }
}

/// Where a link leads: a path of this PC, or (`None`) a web address for the browser.
pub fn local_path(target: &str) -> Option<PathBuf> {
    let t = target.trim();
    let b = t.as_bytes();
    let is_path = (b.len() >= 2 && b[1] == b':' && b[0].is_ascii_alphabetic()) || t.starts_with("\\\\");
    is_path.then(|| PathBuf::from(t))
}

/// The bar's bookmarks, read from the file once and kept here while the app runs.
pub struct Bookmarks(pub Vec<Bookmark>);

impl Global for Bookmarks {}

fn file() -> Option<PathBuf> {
    crate::settings::app_dir().map(|d| d.join("bookmarks.json"))
}

/// The bar's bookmarks (read from the file the first time).
pub fn items(cx: &mut App) -> Vec<Bookmark> {
    if !cx.has_global::<Bookmarks>() {
        let read = file().and_then(|f| std::fs::read_to_string(f).ok()).and_then(|t| serde_json::from_str::<Vec<Bookmark>>(&t).ok());
        cx.set_global(Bookmarks(read.unwrap_or_default()));
    }
    cx.global::<Bookmarks>().0.clone()
}

/// Changes the bar's bookmarks, writes them to the file (off this thread) and draws the windows again.
pub fn update(cx: &mut App, f: impl FnOnce(&mut Vec<Bookmark>)) {
    let mut list = items(cx);
    f(&mut list);
    cx.set_global(Bookmarks(list.clone()));
    if let Some(path) = file() {
        std::thread::spawn(move || {
            if let Ok(text) = serde_json::to_string_pretty(&list) {
                let _ = std::fs::write(path, text);
            }
        });
    }
    cx.refresh_windows();
}

// ---- The Netscape bookmark file ("bookmarks.html")

fn unescape(s: &str) -> String {
    s.trim().replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&#39;", "'").replace("&amp;", "&")
}

fn escape(s: &str) -> String {
    s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}

/// The value of attribute `name` in the text of a tag (`A HREF="…" ADD_DATE="…"`), whatever its case.
fn attr(tag: &str, name: &str) -> Option<String> {
    let lower = tag.to_ascii_lowercase();
    let at = lower.find(&format!("{name}=\""))? + name.len() + 2;
    let end = tag[at..].find('"')? + at;
    Some(tag[at..end].to_string())
}

fn percent_decode(s: &str) -> String {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' && i + 2 < b.len() {
            if let Ok(v) = u8::from_str_radix(std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or(""), 16) {
                out.push(v);
                i += 3;
                continue;
            }
        }
        out.push(b[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

fn percent_encode_path(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' | '/' | ':' | '(' | ')' | '!' | '$' | '\'' | '*' | ',' | ';' | '=' | '@' | '+' => out.push(c),
            _ => {
                let mut buf = [0u8; 4];
                for byte in c.encode_utf8(&mut buf).bytes() {
                    out.push_str(&format!("%{byte:02X}"));
                }
            }
        }
    }
    out
}

/// A bookmark file's address as a link's target: `file:///E:/Juegos/Mi%20carpeta` is the path `E:\Juegos\Mi carpeta`.
fn target_of(href: &str) -> String {
    let h = href.trim();
    match h.strip_prefix("file:///").or_else(|| h.strip_prefix("FILE:///")) {
        Some(rest) => percent_decode(rest).replace('/', "\\"),
        None => match h.strip_prefix("file://") {
            // a share: file://server/share
            Some(rest) => format!("\\\\{}", percent_decode(rest).replace('/', "\\")),
            None => h.to_string(),
        },
    }
}

fn href_of(target: &str) -> String {
    match local_path(target) {
        Some(p) => {
            let s = p.to_string_lossy().replace('\\', "/");
            match s.strip_prefix("//") {
                Some(share) => format!("file://{}", percent_encode_path(share)),
                None => format!("file:///{}", percent_encode_path(&s)),
            }
        }
        None => target.to_string(),
    }
}

/// The bookmarks of a Netscape bookmark file. The bar is the folder the file marks as the toolbar's
/// (`PERSONAL_TOOLBAR_FOLDER="true"`), as browsers read it; whatever else the file has follows it, its folders as folders.
pub fn parse_html(text: &str) -> Vec<Bookmark> {
    let lower = text.to_ascii_lowercase();
    // open folders: (name, children, is the toolbar's)
    let mut stack: Vec<(String, Vec<Bookmark>, bool)> = vec![(String::new(), Vec::new(), false)];
    let mut header: Option<(String, bool)> = None;
    let mut toolbar: Option<Vec<Bookmark>> = None;
    let mut i = 0;
    while let Some(off) = lower[i..].find('<') {
        let start = i + off;
        let Some(len) = lower[start..].find('>') else { break };
        let end = start + len;
        let tag = &lower[start + 1..end];
        let raw = &text[start + 1..end];
        i = end + 1;
        if tag.starts_with("h3") {
            let close = lower[i..].find("</h3>").map_or(i, |o| i + o);
            header = Some((unescape(&text[i..close]), tag.contains("personal_toolbar_folder=\"true\"")));
            i = close;
        } else if tag == "a" || tag.starts_with("a ") {
            let close = lower[i..].find("</a>").map_or(i, |o| i + o);
            let name = unescape(&text[i..close]);
            if let Some(href) = attr(raw, "href") {
                // (an address in the file is written as HTML: `&amp;` for `&`)
                let target = target_of(&unescape(&href));
                let name = if name.is_empty() { target.clone() } else { name };
                if let Some(top) = stack.last_mut() {
                    top.1.push(Bookmark::Link { name, target });
                }
            }
            i = close;
        } else if tag.starts_with("dl") {
            // a folder's list; the file's own outer list has no header
            let (name, is_toolbar) = header.take().unwrap_or_default();
            stack.push((name, Vec::new(), is_toolbar));
        } else if tag.starts_with("/dl") && stack.len() > 1 {
            let (name, children, is_toolbar) = stack.pop().unwrap_or_default();
            if is_toolbar && toolbar.is_none() {
                toolbar = Some(children);
            } else if name.is_empty() {
                // the outer list: its items are the root's
                if let Some(top) = stack.last_mut() {
                    top.1.extend(children);
                }
            } else if let Some(top) = stack.last_mut() {
                top.1.push(Bookmark::Folder { name, children });
            }
        }
    }
    // (a list left open at the end of the file counts as closed)
    while stack.len() > 1 {
        let (name, children, is_toolbar) = stack.pop().unwrap_or_default();
        if is_toolbar && toolbar.is_none() {
            toolbar = Some(children);
        } else if let Some(top) = stack.last_mut() {
            if name.is_empty() {
                top.1.extend(children);
            } else {
                top.1.push(Bookmark::Folder { name, children });
            }
        }
    }
    let rest = stack.pop().map(|s| s.1).unwrap_or_default();
    let mut out = toolbar.unwrap_or_default();
    out.extend(rest);
    out
}

/// The bar as a Netscape bookmark file, its bookmarks in the toolbar's folder: browsers (and Clover) read it back as their bar.
pub fn to_html(items: &[Bookmark]) -> String {
    fn write(out: &mut String, items: &[Bookmark], depth: usize) {
        let pad = "    ".repeat(depth);
        for b in items {
            match b {
                Bookmark::Link { name, target } => {
                    out.push_str(&format!("{pad}<DT><A HREF=\"{}\">{}</A>\n", escape(&href_of(target)), escape(name)));
                }
                Bookmark::Folder { name, children } => {
                    out.push_str(&format!("{pad}<DT><H3>{}</H3>\n{pad}<DL><p>\n", escape(name)));
                    write(out, children, depth + 1);
                    out.push_str(&format!("{pad}</DL><p>\n"));
                }
            }
        }
    }
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
    let mut out = String::from(
        "<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<!-- This is an automatically generated file.\n     It will be read and overwritten.\n     DO NOT EDIT! -->\n<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">\n<TITLE>Bookmarks</TITLE>\n<H1>Bookmarks</H1>\n<DL><p>\n",
    );
    out.push_str(&format!("    <DT><H3 ADD_DATE=\"{now}\" LAST_MODIFIED=\"{now}\" PERSONAL_TOOLBAR_FOLDER=\"true\">Bookmarks</H3>\n    <DL><p>\n"));
    write(&mut out, items, 2);
    out.push_str("    </DL><p>\n</DL><p>\n");
    out
}

#[cfg(test)]
mod tests {
    // (not `super::*`: GPUI's own `test` attribute would come with it and stand for the standard one)
    use super::{Bookmark, parse_html, to_html};

    const SAMPLE: &str = r#"<!DOCTYPE NETSCAPE-Bookmark-file-1>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
<TITLE>Bookmarks</TITLE>
<H1>Bookmarks</H1>
<DL><p>
    <DT><H3 ADD_DATE="1498714413" LAST_MODIFIED="1552072263" PERSONAL_TOOLBAR_FOLDER="true">Bookmarks</H3>
    <DL><p>
        <DT><A HREF="file:///D:/Projects/My%20Folder" ADD_DATE="1498714479" ICON="data:image/png;base64,AAAA">My Folder</A>
        <DT><H3>More</H3>
        <DL><p>
            <DT><A HREF="https://example.com/a?b=1&amp;c=2">Web &amp; more</A>
        </DL><p>
    </DL><p>
    <DT><A HREF="file:///C:/Tools">Tools</A>
</DL><p>
"#;

    #[test]
    fn reads_the_toolbar_folder_first_then_the_rest() {
        let items = parse_html(SAMPLE);
        assert_eq!(
            items,
            vec![
                Bookmark::Link { name: "My Folder".into(), target: r"D:\Projects\My Folder".into() },
                Bookmark::Folder {
                    name: "More".into(),
                    children: vec![Bookmark::Link { name: "Web & more".into(), target: "https://example.com/a?b=1&c=2".into() }]
                },
                Bookmark::Link { name: "Tools".into(), target: r"C:\Tools".into() },
            ]
        );
    }

    /// A real bookmark file, when `BOOKMARKS_FILE` names one (a browser's export).
    #[test]
    fn reads_a_real_file() {
        let Some(path) = std::env::var_os("BOOKMARKS_FILE") else { return };
        let text = std::fs::read_to_string(path).unwrap();
        let items = parse_html(text.trim_start_matches('\u{feff}'));
        for b in &items {
            println!("{b:?}");
        }
        assert!(!items.is_empty());
        assert_eq!(parse_html(&to_html(&items)), items);
    }

    #[test]
    fn writes_what_it_reads_back() {
        let items = parse_html(SAMPLE);
        assert_eq!(parse_html(&to_html(&items)), items);
        assert!(to_html(&items).contains("file:///D:/Projects/My%20Folder"));
    }
}