Cotton code
503 lines · 22.5 KB · RustRaw
//! `notes.export { ids | view, tag?, list?, search?, format }` — a note, or//! several, as a file the phone hands to the share sheet//! (assets/design/notes/CONTRACT.md 9). The core writes it under the data//! directory's `cache/exports/notes/` (emptied before each export) and//! answers its path, never its bytes.//!//! - **markdown**: the text as written (`.md`); pictures keep their addresses.//! - **textbundle**: `text.md`, `assets/` with the pictures this phone holds//!   (the text pointing at them), and `info.json` with the dates; one note is//!   a `.textpack` (the bundle zipped), several a `.zip` of bundles.//! - **html**: one page per note, styled in Print's colours with Figtree,//!   pictures inline.//! - **pdf**: laid out here (A4, [`super::notes_pdf`]); several notes are one//!   document, each starting a page.//!//! What a note draws is the writing rule's: the same blocks and spans the//! phones draw from, read with no cursor (every mark hidden).use std::collections::BTreeSet;use std::io::Write as _;use std::path::{Path, PathBuf};use serde_json::{json, Value};use cotton_core::cotton_rules::writing::{self, derive, style};use cotton_tools::mcp::handlers::common::rows as query_rows;use cotton_tools::mcp::read_db::Query;use super::notes::{bad, note, photo_id, text_of, with_read, PHOTO_SRC};use crate::handle::CottonHandle;use crate::methods::MethodError;/// One note as it is exported.pub(crate) struct Exported {    pub title: Option<String>,    pub text: String,    pub made: String,    pub edited: String,    /// Each picture the text points at that this phone holds: its address    /// as written, its bytes and its kind.    pub pictures: Vec<Picture>,}pub(crate) struct Picture {    pub src: String,    pub bytes: Vec<u8>,    pub mime: String,}impl Picture {    pub fn ext(&self) -> &'static str {        match self.mime.as_str() {            "image/png" => "png",            "image/gif" => "gif",            "image/heic" => "heic",            "image/webp" => "webp",            _ => "jpg",        }    }    /// Its file name in a bundle: the photo's own hash.    pub fn file_name(&self) -> String {        let id = photo_id(&self.src).trim_start_matches(PHOTO_SRC);        format!("{}.{}", id.chars().filter(char::is_ascii_alphanumeric).take(64).collect::<String>(), self.ext())    }}/// The kind of a picture's bytes, read from the bytes.fn sniff(bytes: &[u8]) -> &'static str {    if bytes.starts_with(&[0x89, b'P', b'N', b'G']) {        "image/png"    } else if bytes.starts_with(b"GIF8") {        "image/gif"    } else if bytes.len() > 12 && &bytes[8..12] == b"WEBP" {        "image/webp"    } else if bytes.len() > 12 && &bytes[4..8] == b"ftyp" {        "image/heic"    } else {        "image/jpeg"    }}pub fn export(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let format = request.get("format").and_then(Value::as_str).unwrap_or("markdown");    if !matches!(format, "markdown" | "textbundle" | "html" | "pdf") {        return Err(bad(format!("`{format}` is no export of Notes: markdown, textbundle, html or pdf")));    }    let notes = collect_notes(handle, request)?;    if notes.is_empty() {        return Err(MethodError::new("refused", super::notes::line("export.nothing", &[])?));    }    let dir = handle.client().layout().exports_dir().join("notes");    // not a copy: an export.    let _ = std::fs::remove_dir_all(&dir);    std::fs::create_dir_all(&dir).map_err(|why| MethodError::new("unwritten", format!("the exports folder could not be made: {why}")))?;    let names = file_names(&notes);    let (path, mime) = match (format, notes.len()) {        ("markdown", 1) => (write(&dir, &format!("{}.md", names[0]), notes[0].text.as_bytes())?, "text/markdown"),        ("html", 1) => (write(&dir, &format!("{}.html", names[0]), html(&notes[0]).as_bytes())?, "text/html"),        ("textbundle", 1) => (zipped(&dir, &format!("{}.textpack", names[0]), &notes, &names, format)?, "application/zip"),        ("pdf", _) => {            let name = if notes.len() == 1 { format!("{}.pdf", names[0]) } else { format!("{}.pdf", super::notes::line("export.many_name", &[])?) };            (write(&dir, &name, &super::notes_pdf::pdf(&notes))?, "application/pdf")        }        _ => (zipped(&dir, &format!("{}.zip", super::notes::line("export.many_name", &[])?), &notes, &names, format)?, "application/zip"),    };    let file_name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();    Ok(json!({ "path": path.to_string_lossy(), "file_name": file_name, "mime": mime, "count": notes.len() }))}/// The notes asked for: `ids` in their order, or the notes of a list.fn collect_notes(handle: &CottonHandle, request: &Value) -> Result<Vec<Exported>, MethodError> {    let answer = with_read(handle, "notes.export", |ctx| {        let ids: Vec<String> = match request.get("ids").and_then(Value::as_array) {            Some(ids) => ids.iter().filter_map(Value::as_str).map(str::to_string).collect(),            None => super::notes::list(ctx, request)?["rows"].as_array().into_iter().flatten().filter_map(|row| row["id"].as_str().map(str::to_string)).collect(),        };        let mut out = Vec::new();        for id in ids {            let held = note(ctx, &id)?;            let text = text_of(ctx, &held)?;            let mut pictures = Vec::new();            for src in derive::pictures(&text) {                let photo = photo_id(&src).to_string();                if !photo.starts_with(PHOTO_SRC) {                    continue;                }                let found = query_rows(ctx, &Query::on("cotton_photos").columns(&["id", "key"]).eq("id", photo)).unwrap_or_default();                let key = found.first().and_then(|row| row.get("key")).and_then(Value::as_str).map(str::to_string);                let bytes = key.and_then(|key| super::media::local_path_of(ctx.read.driver(), &key)).and_then(|path| std::fs::read(path).ok());                if let Some(bytes) = bytes {                    pictures.push(json!({ "src": src, "bytes": base64_of(&bytes) }));                }            }            // Named as the list titles it: its heading, else its first line (owner, 21 Nov 2026), never "Note" for a            // note the person sees titled (the iPhone walk, 24 Nov 2026: "Shopping for Sunday" left as Note.md).            let title = derive::title(&text).or_else(|| derive::derive(&text).preview.lines().map(str::trim).find(|l| !l.is_empty()).map(str::to_string));            out.push(json!({ "title": title, "text": text, "made": held.made, "edited": held.edited, "pictures": pictures }));        }        Ok(json!(out))    })?;    Ok(answer        .as_array()        .into_iter()        .flatten()        .map(|note| Exported {            title: note["title"].as_str().map(str::to_string),            text: note["text"].as_str().unwrap_or_default().to_string(),            made: note["made"].as_str().unwrap_or_default().to_string(),            edited: note["edited"].as_str().unwrap_or_default().to_string(),            pictures: note["pictures"]                .as_array()                .into_iter()                .flatten()                .filter_map(|picture| {                    let bytes = bytes_of(picture["bytes"].as_str()?)?;                    Some(Picture { src: picture["src"].as_str()?.to_string(), mime: sniff(&bytes).to_string(), bytes })                })                .collect(),        })        .collect())}fn base64_of(bytes: &[u8]) -> String {    use base64::Engine as _;    base64::engine::general_purpose::STANDARD.encode(bytes)}fn bytes_of(said: &str) -> Option<Vec<u8>> {    use base64::Engine as _;    base64::engine::general_purpose::STANDARD.decode(said).ok()}/// A file name for each note: its title made safe, else "Note"; twins/// numbered.fn file_names(notes: &[Exported]) -> Vec<String> {    let mut seen = BTreeSet::new();    notes        .iter()        .map(|note| {            let base: String = note.title.as_deref().unwrap_or("Note").chars().map(|c| if matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') || c.is_control() { ' ' } else { c }).collect();            let base = base.split_whitespace().collect::<Vec<_>>().join(" ");            let base: String = if base.is_empty() { "Note".to_string() } else { base.chars().take(80).collect() };            let mut name = base.clone();            let mut n = 2;            while !seen.insert(name.to_lowercase()) {                name = format!("{base} {n}");                n += 1;            }            name        })        .collect()}fn write(dir: &Path, name: &str, bytes: &[u8]) -> Result<PathBuf, MethodError> {    let path = dir.join(name);    // not a copy: an export.    std::fs::write(&path, bytes).map_err(|why| MethodError::new("unwritten", format!("{name}: {why}")))?;    Ok(path)}/// The bundle's text: each picture this phone holds pointed at in `assets/`.pub(crate) fn bundle_text(note: &Exported) -> String {    let mut text = note.text.clone();    for picture in &note.pictures {        text = text.replace(&format!("]({})", picture.src), &format!("](assets/{})", picture.file_name()));    }    text}fn info_json(note: &Exported) -> String {    serde_json::to_string_pretty(&json!({        "version": 2,        "type": "net.daringfireball.markdown",        "creatorIdentifier": "com.cottondb.notes",        "transient": false,        "creationDate": note.made,        "modificationDate": note.edited,    }))    .unwrap_or_default()}/// A zip of the notes in `format` (TextBundles as folders, Markdown or HTML/// files), or one TextPack.fn zipped(dir: &Path, name: &str, notes: &[Exported], names: &[String], format: &str) -> Result<PathBuf, MethodError> {    let path = dir.join(name);    // not a copy: an export.    let file = std::fs::File::create(&path).map_err(|why| MethodError::new("unwritten", format!("{name}: {why}")))?;    let mut zip = zip::ZipWriter::new(file);    let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);    let fail = |why: String| MethodError::new("unwritten", format!("{name}: {why}"));    let mut put = |zip: &mut zip::ZipWriter<std::fs::File>, inside: String, bytes: &[u8]| -> Result<(), MethodError> {        zip.start_file(inside, options).map_err(|why| fail(why.to_string()))?;        zip.write_all(bytes).map_err(|why| fail(why.to_string()))    };    for (note, base) in notes.iter().zip(names) {        match format {            "textbundle" => {                let root = format!("{base}.textbundle");                put(&mut zip, format!("{root}/text.md"), bundle_text(note).as_bytes())?;                put(&mut zip, format!("{root}/info.json"), info_json(note).as_bytes())?;                let mut kept = BTreeSet::new();                for picture in &note.pictures {                    if kept.insert(picture.file_name()) {                        put(&mut zip, format!("{root}/assets/{}", picture.file_name()), &picture.bytes)?;                    }                }            }            "html" => put(&mut zip, format!("{base}.html"), html(note).as_bytes())?,            _ => put(&mut zip, format!("{base}.md"), note.text.as_bytes())?,        }    }    zip.finish().map_err(|why| fail(why.to_string()))?;    Ok(path)}// ── the drawing, read once for HTML and PDF ─────────────────────────────────/// A run of one block's words with the inline looks over it.#[derive(Debug, Clone, Default, PartialEq)]pub(crate) struct Run {    pub text: String,    pub bold: bool,    pub italic: bool,    pub underline: bool,    pub strike: bool,    pub highlight: bool,    pub code: bool,    pub tag: bool,    pub done: bool,    pub link: Option<String>,}/// One block's visible words between `from` and `to` (UTF-16), cut into/// runs at every span's edge, the hidden marks left out.pub(crate) fn runs(text: &str, spans: &[style::Span], from: u32, to: u32) -> Vec<Run> {    let over: Vec<&style::Span> = spans.iter().filter(|s| s.start < to && s.end > from).collect();    let mut edges: Vec<u32> = vec![from, to];    for span in &over {        edges.push(span.start.clamp(from, to));        edges.push(span.end.clamp(from, to));    }    edges.sort_unstable();    edges.dedup();    let mut out: Vec<Run> = Vec::new();    for pair in edges.windows(2) {        let (a, b) = (pair[0], pair[1]);        if a >= b {            continue;        }        let active: Vec<&&style::Span> = over.iter().filter(|s| s.start <= a && s.end >= b).collect();        if active.iter().any(|s| matches!(s.look, style::Look::Hidden | style::Look::Glyph) || s.style == style::Style::Indent) {            continue;        }        let words = &text[writing::byte_at(text, a)..writing::byte_at(text, b)];        let mut run = Run { text: words.to_string(), ..Run::default() };        for span in active {            match span.style {                style::Style::Bold => run.bold = true,                style::Style::Italic | style::Style::Quote => run.italic = true,                style::Style::Underline => run.underline = true,                style::Style::Strike => run.strike = true,                style::Style::Done => {                    run.strike = true;                    run.done = true;                }                style::Style::Highlight => run.highlight = true,                style::Style::Code | style::Style::CodeBlock => run.code = true,                style::Style::Tag => run.tag = true,                style::Style::Link => run.link = span.url.clone(),                style::Style::NoteLink => run.link = span.url.clone().map(|target| format!("note:{target}")),                _ => {}            }        }        match out.last_mut() {            Some(last) if Run { text: String::new(), ..last.clone() } == Run { text: String::new(), ..run.clone() } => last.text.push_str(&run.text),            _ => out.push(run),        }    }    out}// ── HTML ────────────────────────────────────────────────────────────────────fn escape(text: &str) -> String {    text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")}fn runs_html(runs: &[Run]) -> String {    let mut out = String::new();    for run in runs {        let mut words = escape(&run.text);        if run.code {            words = format!("<code>{words}</code>");        }        if run.bold {            words = format!("<strong>{words}</strong>");        }        if run.italic {            words = format!("<em>{words}</em>");        }        if run.underline {            words = format!("<u>{words}</u>");        }        if run.strike {            words = format!("<s>{words}</s>");        }        if run.highlight {            words = format!("<mark>{words}</mark>");        }        if run.tag {            words = format!("<span class=\"tag\">{words}</span>");        }        if let Some(url) = &run.link {            words = match url.strip_prefix("note:") {                Some(_) => format!("<span class=\"note-link\">{words}</span>"),                None => format!("<a href=\"{}\">{words}</a>", escape(url)),            };        }        out.push_str(&words);    }    out}const CSS: &str = "body{background:#FFFFFF;color:#000000;font-family:Figtree,-apple-system,'Segoe UI',Helvetica,Arial,sans-serif;font-size:17px;line-height:1.5;max-width:42em;margin:3em auto;padding:0 1.25em}\h1,h2,h3,h4,h5,h6{color:#000000;line-height:1.25;margin:1.2em 0 .4em}h1.title{font-size:2em;margin-top:0}\p{margin:0 0 .4em}a,.note-link{color:#0B4FA8}.tag{color:#B3261E}mark{background:#FFEB3B}\code,pre{font-family:'JetBrains Mono',ui-monospace,Menlo,monospace;font-size:.9em;background:#EDEDED;border-radius:4px}code{padding:.1em .3em}pre{padding:.8em 1em;overflow-x:auto}pre code{background:none;padding:0}\blockquote{border-left:3px solid #1A1A1A;margin:.4em 0;padding-left:1em;color:#333333}hr{border:0;border-top:1px solid #1A1A1A;margin:1.5em 0}\ul.checks{list-style:none;padding-left:1.2em}ul.checks li.done{color:#333333}ul.checks input{margin-right:.5em}\table{border-collapse:collapse;margin:.6em 0}td,th{border:1px solid #1A1A1A;padding:.3em .6em}th{text-align:left}\img{max-width:100%;height:auto}img.small{width:160px}img.medium{width:320px}figure{margin:.6em 0}";/// A picture's address as the exported page shows it: inline, when this/// phone holds it.fn picture_src(note: &Exported, src: &str) -> Option<String> {    let picture = note.pictures.iter().find(|p| p.src == src)?;    Some(format!("data:{};base64,{}", picture.mime, base64_of(&picture.bytes)))}/// One note as a page of its own.pub(crate) fn html(note: &Exported) -> String {    let text = &note.text;    let styled = style::style(text, None);    let mut body = String::new();    let mut open_list: Vec<(String, u8)> = Vec::new();    let close_lists = |body: &mut String, open: &mut Vec<(String, u8)>, keep: usize| {        while open.len() > keep {            let (tag, _) = open.pop().unwrap_or_default();            body.push_str(&format!("</{}>", if tag == "checks" { "ul" } else { tag.as_str() }));        }    };    let mut k = 0;    let blocks = &styled.blocks;    while k < blocks.len() {        let block = &blocks[k];        let words = runs_html(&runs(text, &styled.spans, block.content, block.end));        let list_kind = match block.kind {            style::Kind::Bullet => Some("ul"),            style::Kind::Numbered => Some("ol"),            style::Kind::Check => Some("checks"),            _ => None,        };        match list_kind {            Some(kind) => {                let depth = block.depth;                while open_list.last().is_some_and(|(_, d)| *d > depth) {                    let keep = open_list.len() - 1;                    close_lists(&mut body, &mut open_list, keep);                }                if open_list.last().is_some_and(|(tag, d)| *d == depth && tag != kind) {                    let keep = open_list.len() - 1;                    close_lists(&mut body, &mut open_list, keep);                }                if open_list.last().is_none_or(|(_, d)| *d < depth) {                    body.push_str(match kind {                        "checks" => "<ul class=\"checks\">",                        "ol" => "<ol>",                        _ => "<ul>",                    });                    open_list.push((kind.to_string(), depth));                }                match block.checked {                    Some(true) => body.push_str(&format!("<li class=\"done\"><input type=\"checkbox\" checked disabled>{words}</li>")),                    Some(false) => body.push_str(&format!("<li><input type=\"checkbox\" disabled>{words}</li>")),                    None => body.push_str(&format!("<li>{words}</li>")),                }                k += 1;                continue;            }            None => close_lists(&mut body, &mut open_list, 0),        }        match block.kind {            style::Kind::Heading => {                let level = block.level.unwrap_or(1).clamp(1, 6);                let class = if block.title { " class=\"title\"" } else { "" };                body.push_str(&format!("<h{level}{class}>{words}</h{level}>"));            }            style::Kind::Paragraph => body.push_str(&format!("<p>{words}</p>")),            style::Kind::Quote => body.push_str(&format!("<blockquote>{words}</blockquote>")),            style::Kind::Divider => body.push_str("<hr>"),            style::Kind::Picture => {                let src = block.src.clone().unwrap_or_default();                let class = block.width.as_deref().filter(|w| *w != "full").map(|w| format!(" class=\"{w}\"")).unwrap_or_default();                match picture_src(note, &src) {                    Some(data) => body.push_str(&format!("<figure><img{class} src=\"{data}\" alt=\"{}\"></figure>", escape(&words_plain(&words)))),                    None => body.push_str(&format!("<p><em>{}</em></p>", escape(&super::notes::line("export.picture_missing", &[]).unwrap_or_default()))),                }            }            style::Kind::Code | style::Kind::Fence => {                let mut code = String::new();                while k < blocks.len() && matches!(blocks[k].kind, style::Kind::Code | style::Kind::Fence) {                    if blocks[k].kind == style::Kind::Code {                        code.push_str(&escape(&text[writing::byte_at(text, blocks[k].start)..writing::byte_at(text, blocks[k].end)]));                        code.push('\n');                    }                    k += 1;                }                if !code.is_empty() {                    body.push_str(&format!("<pre><code>{}</code></pre>", code.trim_end_matches('\n')));                }                continue;            }            style::Kind::Table | style::Kind::TableRule => {                if let Some(table) = styled.tables.iter().find(|t| t.start <= block.start && block.end <= t.end) {                    body.push_str("<table>");                    for (r, row) in table.rows.iter().enumerate() {                        body.push_str("<tr>");                        for cell in row {                            let tag = if r == 0 { "th" } else { "td" };                            body.push_str(&format!("<{tag}>{}</{tag}>", runs_html(&runs(text, &styled.spans, cell.start, cell.end))));                        }                        body.push_str("</tr>");                    }                    body.push_str("</table>");                    while k < blocks.len() && matches!(blocks[k].kind, style::Kind::Table | style::Kind::TableRule) && blocks[k].end <= table.end {                        k += 1;                    }                    continue;                }            }            _ => {}        }        k += 1;    }    close_lists(&mut body, &mut open_list, 0);    let title = escape(note.title.as_deref().unwrap_or("Note"));    format!("<!doctype html>\n<html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>{title}</title><style>{CSS}</style></head><body>\n{body}\n</body></html>\n")}fn words_plain(html: &str) -> String {    let mut out = String::new();    let mut inside = false;    for c in html.chars() {        match c {            '<' => inside = true,            '>' => inside = false,            c if !inside => out.push(c),            _ => {}        }    }    out.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&amp;", "&")}