diff --git a/arc/canvas.md b/arc/canvas.md index d86a6cdfeb76d5edbc89f44b1ad29db07e4f067e..e299331614aa13be1163300c8230e2a4c5e1d8e0 100644 --- a/arc/canvas.md +++ b/arc/canvas.md @@ -321,6 +321,21 @@ notebook), paper, orientation, fitting to the paper's width and the footer. Prin the PDF to AppKit's print panel, the XDG print portal or the shell's print verb for PDFs. On iOS the page menu prints the page through the print sheet or shares its PDF. +## Websites + +`canvas::site` writes a notebook, section or page as a folder of web pages, which Save As +offers where OneNote 2010 offers its Single File Web Page, and Export as Website opens. It +lists every page first, so links between pages are known, then lays out and writes one page +at a time, as the view lays it out without an editor: every outline, picture, file and +drawing goes where the page puts it. An outline's text is the HTML Copy writes, within the +outline's laid-out width, its tags and list markers placed and its tag colours painted as the +page does them; drawings become SVG of the strokes the page paints. Pictures, files, tag art +and the Calibri stand-in are copied beside the pages, so a site needs no script and asks no +server for anything, and stored fonts and links pass the same checks as Copy's. Links to +pages, paragraphs and sections in the export lead to their files; links to the rest of the +notebook stay text. The index lists the section groups and sections, password-protected ones +as locked, and each page scrolls in its own pane beside its section's pages. + ## Search, dates, conflicts Smaller modules follow the same pattern of reproducing OneNote's behaviour diff --git a/crates/canvas/Cargo.toml b/crates/canvas/Cargo.toml index 0bfc76a723b64c0a23baafca804be0f69bea8f86..311439c183193290184ffddbf15f314db4bfc189 100644 --- a/crates/canvas/Cargo.toml +++ b/crates/canvas/Cargo.toml @@ -55,6 +55,10 @@ required-features = ["gpu"] name = "reading_inventory" required-features = ["gpu"] +[[example]] +name = "export_site" +required-features = ["interaction"] + [[example]] name = "print_pdf" required-features = ["pdf"] diff --git a/crates/canvas/assets/site.css b/crates/canvas/assets/site.css new file mode 100644 index 0000000000000000000000000000000000000000..cb53e9ff79aa7a31c702d2634410b1eee28d91e5 --- /dev/null +++ b/crates/canvas/assets/site.css @@ -0,0 +1,59 @@ +body { margin: 0; background: #fff; color: #000; } +/* As OneNote's window: the page scrolls both ways in its own pane, the page list beside it. */ +body:has(> .view) { display: grid; grid-template-rows: auto minmax(0, 1fr); height: 100vh; } +header, nav, .index { font: 13px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; } +a { color: #0563c1; } + +header { padding: 8px 16px; background: #f3f3f3; border-bottom: 1px solid #d6d6d6; } +header a { color: inherit; font-weight: 600; text-decoration: none; } +header a:hover { text-decoration: underline; } + +.view { display: grid; grid-template-columns: minmax(0, 1fr) 220px; min-height: 0; } +.page { position: relative; overflow: auto; font: 11pt Calibri, Carlito, sans-serif; } +.sheet { position: absolute; top: 0; min-width: 100%; min-height: 100%; background: inherit; } +.sheet > * { position: absolute; margin: 0; } +.rules { right: 0; bottom: 0; pointer-events: none; } +/* A page exported alone fills the window and scrolls with it. */ +body > .page { overflow: visible; min-height: 100vh; } +.outline p, .outline li { position: relative; } +.outline table { border-collapse: collapse; } +/* OneNote's own web pages pad cells so; its column widths leave room for no more. */ +.outline td { padding: 2pt 3pt !important; } +/* The page's own markers stand in; the lists keep theirs for assistive technology. */ +.outline ul, .outline ol { padding-left: 0; } +.outline li::marker { color: transparent; } +.tag, .marker { position: absolute; white-space: pre; } +.tag img { position: absolute; inset: 0; width: 100%; height: 100%; } +.picture { display: block; } +.ink { display: block; overflow: visible; } +.file { display: inline-flex; flex-direction: column; align-items: center; width: 54pt; color: inherit; + text-decoration: none; font: 11pt Arial, sans-serif; text-align: center; overflow-wrap: anywhere; } +.file span { margin-top: 6pt; } +.missing { display: flex; align-items: center; justify-content: center; box-sizing: border-box; + border: 1px dashed #b4b4b4; color: #7a7a7a; font: 9pt system-ui, sans-serif; } +.failed { margin: 36pt; color: #7a7a7a; } + +nav.pages { background: #f7f7f7; border-left: 1px solid #d6d6d6; padding: 8px 0; overflow-y: auto; } +nav ul, .index ul { list-style: none; margin: 0; padding: 0; } +nav ul ul { padding-left: 14px; } +nav a { display: block; padding: 3px 12px; color: inherit; text-decoration: none; + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +nav a:hover { background: #e8e8e8; } +nav a[aria-current] { background: #fff; font-weight: 600; box-shadow: inset 3px 0 #7a5fb8; } + +.index { max-width: 720px; margin: 0 auto; padding: 24px 16px 48px; } +.index h1 { font-size: 24px; font-weight: 600; } +.index h2 { font-size: 15px; font-weight: 600; margin: 20px 0 6px; color: #555; } +.index h3 { font-size: 15px; font-weight: 600; margin: 16px 0 4px; padding-left: 8px; + border-left: 5px solid #c8c8c8; } +.index .group > ul { padding-left: 16px; } +.index li li { padding-left: 13px; } +.index li a { display: inline-block; padding: 2px 0; } +.index .locked { margin: 0 0 0 13px; color: #7a7a7a; } + +@media print { + body:has(> .view) { display: block; height: auto; } + header, nav.pages { display: none; } + .view { display: block; } + .page { overflow: visible; } +} diff --git a/crates/canvas/examples/export_site.rs b/crates/canvas/examples/export_site.rs new file mode 100644 index 0000000000000000000000000000000000000000..c8f64849a6a9003691f47e9ab66d5d07e77383a3 --- /dev/null +++ b/crates/canvas/examples/export_site.rs @@ -0,0 +1,60 @@ +//! Writes sections as the website Export as Website makes, each section under the folders +//! its path names below `ROOT`. `export_site NEW-FOLDER ROOT SECTION.one...` + +use canvas::{layout::TextEngine, site}; +use onestore::{Arena, Section}; +use std::{env, fs, path::Path}; + +fn main() -> Result<(), Box> { + let args: Vec = env::args().skip(1).collect(); + let [destination, root, sections @ ..] = args.as_slice() else { + return Err("Expected a new folder, a root and sections".into()); + }; + let mut listed = Vec::new(); + let mut read = Vec::new(); + for path in sections { + let arena = Arena::default(); + let bytes = fs::read(path)?; + let identity = onestore::Header::parse(bytes.get(..1024).ok_or("Too short")?)?.file_id; + let mut section = Section::open(&arena, bytes)?; + let (mut listings, mut pages) = (Vec::new(), Vec::new()); + for (space, title, level) in section.pages()? { + let page = section.page(space)?; + listings.push(site::Listing { + title, + level, + identity: page.identity, + }); + pages.push(page); + } + let relative = Path::new(path).strip_prefix(root)?; + let groups = (relative.parent().into_iter()) + .flat_map(|parent| parent.iter()) + .map(|group| group.to_string_lossy().into_owned()) + .collect(); + let name = relative.file_stem().unwrap_or_default().to_string_lossy(); + listed.push(site::Section { + groups, + name: name.into_owned(), + color: None, + identity: Some(identity), + pages: Some(listings), + }); + read.push(pages); + } + let destination = Path::new(destination); + let mut write = |name: &str, bytes: &[u8]| { + let path = destination.join(name); + fs::create_dir_all(path.parent().unwrap_or(destination))?; + fs::write(path, bytes) + }; + let mut site = site::Site::new("Corpus", listed); + let mut engine = TextEngine::default(); + for (section, pages) in read.into_iter().enumerate() { + for (at, page) in pages.into_iter().enumerate() { + site.page([section, at], page, &mut engine, &mut write)?; + } + } + site.finish(&mut write)?; + Ok(()) +} diff --git a/crates/canvas/src/editor.rs b/crates/canvas/src/editor.rs index d9e447dfc017d4c240d847bff83f4c1d0d64b2f1..0e4f0790b438eb4664809556e246d9dba53ec2dc 100644 --- a/crates/canvas/src/editor.rs +++ b/crates/canvas/src/editor.rs @@ -29,7 +29,7 @@ mod equation; #[cfg(test)] mod evidence; mod format; -mod html; +pub(crate) mod html; mod ink; mod link; mod markdown; diff --git a/crates/canvas/src/editor/html.rs b/crates/canvas/src/editor/html.rs index 54319e0569fd1f969a62defe9041cabda60e334e..c6e69e2c887fa0313eb85db8ea3d20b967e29b57 100644 --- a/crates/canvas/src/editor/html.rs +++ b/crates/canvas/src/editor/html.rs @@ -23,7 +23,7 @@ impl Clip { /// The clip as a web page whose fragment the comments OneNote's mark out hold. pub fn html(&self) -> String { let mut body = String::new(); - blocks(&self.paragraphs, &self.definitions, &mut body); + blocks(&self.paragraphs, &self.definitions, &mut (), &mut body); format!( "\n\n\n\ \n\n\n\ @@ -32,10 +32,39 @@ impl Clip { } } +/// What a writer of whole pages adds to the blocks the clipboard writes. +pub(crate) trait Extras { + /// CSS added to text paragraph `node`'s own, each declaration led by `;`. + fn style(&mut self, _node: &PageParagraph) -> String { + String::new() + } + + /// Attributes added to text paragraph `node`'s element, each led by a space. + fn attributes(&mut self, _node: &PageParagraph) -> String { + String::new() + } + + /// What starts text paragraph `node`, inside its element, or stands for a picture, file or + /// drawing, which the clipboard leaves out. + fn content(&mut self, _node: &PageParagraph, _out: &mut String) {} + + /// Where a link to stored `target` leads; none for one that stays text. + fn link(&mut self, target: &str) -> Option { + linkable(target) + } +} + +impl Extras for () {} + /// `nodes` as blocks: a list opens at a paragraph whose list differs from the one open at /// its level, and a block's left margin steps it in from the list it sits in, which OneNote /// and Word take its level from. -fn blocks(nodes: &[PageParagraph], definitions: &BTreeMap, out: &mut String) { +pub(crate) fn blocks( + nodes: &[PageParagraph], + definitions: &BTreeMap, + extras: &mut dyn Extras, + out: &mut String, +) { let mut open: Vec<(u32, &str)> = Vec::new(); for node in nodes { let list = node @@ -61,13 +90,25 @@ fn blocks(nodes: &[PageParagraph], definitions: &BTreeMap, o ); open.push((node.level, tag)); } - out.push_str("
  • "); - runs(&text.text, out); + let _ = write!( + out, + "
  • ", + extras.style(node), + extras.attributes(node) + ); + extras.content(node, out); + runs(&text.text, extras, out); out.push_str("
  • \n"); } (_, ParagraphContent::Text(text)) => { - let _ = write!(out, "

    "); - runs(&text.text, out); + let _ = write!( + out, + "

    ", + extras.style(node), + extras.attributes(node) + ); + extras.content(node, out); + runs(&text.text, extras, out); out.push_str("

    \n"); } (_, ParagraphContent::Table(table)) => { @@ -84,14 +125,14 @@ fn blocks(nodes: &[PageParagraph], definitions: &BTreeMap, o vertical-align:top;width:{}pt;padding:4pt 4pt 4pt 4pt'>", column.width ); - blocks(&cell.paragraphs, definitions, out); + blocks(&cell.paragraphs, definitions, extras, out); out.push_str("\n"); } out.push_str("\n"); } out.push_str("\n"); } - _ => {} + _ => extras.content(node, out), } } for (_, tag) in open.into_iter().rev() { @@ -126,7 +167,7 @@ pub(super) fn list_tag(kind: &Kind) -> (&'static str, &'static str) { } /// A paragraph's shown runs as spans, its links' around theirs. -fn runs(text: &Paragraph, out: &mut String) { +fn runs(text: &Paragraph, extras: &mut dyn Extras, out: &mut String) { let links = links(text, 0); let (mut byte, mut unit) = (0, 0); let mut shown = false; @@ -141,7 +182,7 @@ fn runs(text: &Paragraph, out: &mut String) { shown = true; let link = (links.iter()) .find(|link| link.label.contains(&start)) - .and_then(|link| linkable(&link.target)); + .and_then(|link| extras.link(&link.target)); if let Some(target) = &link { let _ = write!(out, "", escape(target, &mut false)); } @@ -163,7 +204,7 @@ fn runs(text: &Paragraph, out: &mut String) { /// A stored link target as HTML may link it: a web or mail address, a link within the /// notebook, or a relative path, without the white space and controls browsers ignore in one. /// None for anything else, such as a script, which stays text. -fn linkable(target: &str) -> Option { +pub(crate) fn linkable(target: &str) -> Option { let target: String = (target.trim_matches(|c: char| c <= ' ').chars()) .filter(|c| !matches!(c, '\t' | '\n' | '\r')) .collect(); @@ -183,7 +224,7 @@ fn linkable(target: &str) -> Option { /// A font name CSS can hold as it is: letters, digits, spaces and `-`, `_` and `.`; none for /// another, which might break out of the style it is put in. -fn font_name(font: &str) -> Option<&str> { +pub(crate) fn font_name(font: &str) -> Option<&str> { (!font.is_empty() && font .chars() @@ -248,7 +289,7 @@ fn css(format: &Format) -> String { /// Text as HTML keeps it, in an element or a quoted attribute: markup characters and quotes /// escaped, line breaks as `br`, and a space after `space`, whether the text follows a space /// or starts its paragraph, unbreakable so it doesn't collapse. -fn escape(text: &str, space: &mut bool) -> String { +pub(crate) fn escape(text: &str, space: &mut bool) -> String { let mut escaped = String::with_capacity(text.len()); for c in text.chars() { match c { diff --git a/crates/canvas/src/interaction/mod.rs b/crates/canvas/src/interaction/mod.rs index 7c22dccca651dc5747ba221e2b051b40b187b33c..1c73e997044bfc8738653dd3c3e3b45faa810d06 100644 --- a/crates/canvas/src/interaction/mod.rs +++ b/crates/canvas/src/interaction/mod.rs @@ -2810,9 +2810,9 @@ pub(crate) fn rule_primitives( let Some(lines) = lines else { return Vec::new(); }; - let width = pixel.max(0.75); + let width = pixel.max(crate::RULE_WIDTH); // Stored spacings are in half inches; nothing draws closer than a device pixel apart. - let step = |spacing: f32| (spacing * 36.0).max(pixel); + let step = |spacing: f32| (spacing * crate::HALF_INCH).max(pixel); let color = |color| paper.tint(crate::gpu::colorref(color)); let horizontal = step(lines.spacing); let first = ((top - y) / horizontal).ceil().max(0.0); @@ -2829,7 +2829,9 @@ pub(crate) fn rule_primitives( color: color(rule_color), }; match lines.vertical { - VerticalRule::Margin(rule_color) => primitives.push(vertical(x - 0.75, rule_color)), + VerticalRule::Margin(rule_color) => { + primitives.push(vertical(x - crate::MARGIN_RULE, rule_color)) + } VerticalRule::Grid { spacing, color } => { let spacing = step(spacing); let first = ((left - x) / spacing).floor(); diff --git a/crates/canvas/src/layout.rs b/crates/canvas/src/layout.rs index 5c898dd3d051943e51b4732bd092a8e9bc475483..ffdaf3d704bf58b68a9d934b6851296597953839 100644 --- a/crates/canvas/src/layout.rs +++ b/crates/canvas/src/layout.rs @@ -118,10 +118,27 @@ pub(crate) const DEFAULT_FONT_SIZE: f32 = 11.0; /// which fetches them beside it instead (`register_substitute`). const BUNDLED: &[(&str, &[&[u8]])] = include!(concat!(env!("OUT_DIR"), "/bundled.rs")); -/// Each bundled family's faces, inflated the first time an engine lacks the family. +/// Each bundled family's faces, inflated the first time they are asked for. static INFLATED: [OnceLock>>; BUNDLED.len()] = [const { OnceLock::new() }; BUNDLED.len()]; +/// The bundled faces standing in for `family`, inflated the first time they are asked for; +/// none where the build left the family out. +pub(crate) fn bundled(family: &str) -> Option<&'static [Blob]> { + let at = BUNDLED.iter().position(|(bundled, _)| *bundled == family)?; + let faces = INFLATED[at].get_or_init(|| { + BUNDLED[at] + .1 + .iter() + .map(|face| { + let face = miniz_oxide::inflate::decompress_to_vec(face); + Blob::new(Arc::new(face.expect("bundled substitutes inflate"))) + }) + .collect() + }); + Some(faces) +} + impl Default for TextEngine { /// An engine that lays out each bundled family in its substitute where it is missing. fn default() -> Self { @@ -135,20 +152,11 @@ impl Default for TextEngine { arial_substitutes: BTreeSet::new(), substitutes: BTreeMap::new(), }; - for (&(family, faces), inflated) in BUNDLED.iter().zip(&INFLATED) { + for (family, _) in BUNDLED { if engine.fonts.collection.family_id(family).is_some() { continue; } - let faces = inflated.get_or_init(|| { - faces - .iter() - .map(|face| { - let face = miniz_oxide::inflate::decompress_to_vec(face); - Blob::new(Arc::new(face.expect("bundled substitutes inflate"))) - }) - .collect() - }); - for face in faces { + for face in bundled(family).into_iter().flatten() { engine .register(face.clone(), true) .expect("bundled substitutes register"); diff --git a/crates/canvas/src/lib.rs b/crates/canvas/src/lib.rs index 5e3d6613cc9a93c9bb22b7017805d27cf7ec53b9..d0dbdfae4baeb800c5d4a3c40182132f4a5d7447 100644 --- a/crates/canvas/src/lib.rs +++ b/crates/canvas/src/lib.rs @@ -19,6 +19,15 @@ pub mod interaction; pub mod print; #[cfg(feature = "gpu")] pub mod recording; +#[cfg(feature = "gpu")] +pub mod site; + +/// Points in the half inch rule line spacings are stored in. +pub(crate) const HALF_INCH: f32 = 36.0; +/// How thick rule lines draw at the least, in points. +pub(crate) const RULE_WIDTH: f32 = 0.75; +/// How far left of the margin origin a page's margin rule runs, in points. +pub(crate) const MARGIN_RULE: f32 = 0.75; /// Where an object stored with `layout` lies; an unset coordinate is zero. pub(crate) fn origin(layout: &onestore::document::Layout) -> [f32; 2] { diff --git a/crates/canvas/src/outline.rs b/crates/canvas/src/outline.rs index fb1e8d3f5a5bc1521ef82a52e6c8bf4aeed5c92d..b46d8c9602d9d64ea1dbec72efd058418549549b 100644 --- a/crates/canvas/src/outline.rs +++ b/crates/canvas/src/outline.rs @@ -297,6 +297,8 @@ pub struct ParagraphLayout { /// A highlight of the whole paragraph (its own `highlight`), COLORREF: a band across its /// outline behind its lines, as OneNote marks a conflict page's conflicting changes. pub(crate) band: Option, + /// The font colour and highlight its tags give every run, COLORREF. + pub(crate) tag_paint: [Option; 2], } /// How the page draws a note tag. @@ -1218,6 +1220,7 @@ impl ParagraphLayout { math, parent: paragraph.parent, band: paragraph.format.highlight, + tag_paint: [color, highlight], }; result.place_tags(result.marker_left()); Ok(result) diff --git a/crates/canvas/src/site.rs b/crates/canvas/src/site.rs new file mode 100644 index 0000000000000000000000000000000000000000..380de535b776922b3c87e9f1038f909306ef38ba --- /dev/null +++ b/crates/canvas/src/site.rs @@ -0,0 +1,1554 @@ +//! A notebook as a static website: an index listing its section groups, sections and pages, +//! and each page as OneNote's view lays it out, its outlines, pictures, files and drawings +//! placed where they lie on the page. Text is HTML the browser wraps, written as Copy writes it, +//! within each outline's laid-out width. Pictures and attached files are copied beside the +//! pages, drawings become SVG, and nothing written runs a script or asks a server for anything. + +use crate::editor::html::{Extras, blocks, escape, font_name, linkable}; +use crate::editor::page::{Content, build, ink_bounds}; +use crate::gpu::{colorref, page::append_ink, tag_sources}; +use crate::layout::TextEngine; +use crate::outline::{OutlineLayout, ParagraphLayout, ParagraphTag, TagIcon}; +use draw::Primitive; +use onestore::{ + ExGuid, + page::{Attachment, Definition, Image, Ink, Page, PageObject, PageParagraph, ParagraphContent}, +}; +use sha2::{Digest, Sha256}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fmt::Write as _, + io, +}; + +/// A section as the site lists it, before its pages are read. +pub struct Section { + /// The section groups holding it, outermost first. + pub groups: Vec, + pub name: String, + /// COLORREF. + pub color: Option, + /// Its file identity, which links into it name. + pub identity: Option<[u8; 16]>, + /// Its pages in order; none for a section the site lists as locked. + pub pages: Option>, +} + +/// A page as its section lists it. +pub struct Listing { + pub title: String, + /// 1 for a page, more for its subpages. + pub level: u32, + /// What links to the page name it by. + pub identity: Option<[u8; 16]>, +} + +/// Room left past the page's content, as OneNote's view leaves it. +const MARGIN: f32 = 36.0; + +const STYLE: &str = include_str!("../assets/site.css"); + +/// The icon of a file stored without one. +const BLANK_FILE: &str = "files/file.png"; + +/// A website being written: the notebook's pages, written one at a time with `page`, then the +/// index and stylesheet with `finish`. Every write goes through a `write` that takes +/// a path relative to the site's folder and the bytes to put there. +pub struct Site { + notebook: String, + sections: Vec
    , + /// Each section's folder and its pages' files. + listed: Vec<(String, Vec)>, + links: Links, + written: BTreeSet, + calibri: bool, + /// The language of the first page written that names one, the index's. + lang: Option<&'static str>, + /// Whether the site is one page alone, without the notebook around it. + alone: bool, +} + +impl Site { + /// The site of `sections` of `notebook`, each given a folder of its own and each page a + /// file, so that links between them are known before any is written. + pub fn new(notebook: &str, sections: Vec
    ) -> Self { + Self::build(notebook, sections, false) + } + + /// The site of `section`'s one page alone: the page as `index.html`, without the notebook's + /// header and page list around it. + pub fn page_alone(notebook: &str, section: Section) -> Self { + Self::build(notebook, vec![section], true) + } + + fn build(notebook: &str, sections: Vec
    , alone: bool) -> Self { + let mut taken = BTreeSet::new(); + let mut links = Links::default(); + let listed = (sections.iter()) + .map(|section| { + let folder = folder(section, &mut taken); + let pages: Vec = (section.pages.iter().flatten().enumerate()) + .map(|(at, page)| { + let title = shown_title(&page.title); + Listed { + href: match alone { + true => "index.html".to_owned(), + false => { + format!("{folder}/{:02} {}.html", at + 1, component(&title)) + } + }, + title, + level: page.level, + } + }) + .collect(); + if let (Some(identity), Some(first)) = (section.identity, pages.first()) { + links.sections.insert(identity, first.href.clone()); + } + for (page, listed) in section.pages.iter().flatten().zip(&pages) { + if let Some(identity) = page.identity { + links.pages.insert(identity, listed.href.clone()); + } + } + (folder, pages) + }) + .collect(); + Self { + notebook: notebook.to_owned(), + sections, + listed, + links, + written: BTreeSet::new(), + calibri: false, + lang: None, + alone, + } + } + + /// Writes `page`, the one at `at` in its section's listing at `section`. A page that can't + /// be laid out is written as a note saying so. + pub fn page( + &mut self, + [section, at]: [usize; 2], + page: Page, + engine: &mut TextEngine, + write: &mut dyn FnMut(&str, &[u8]) -> io::Result<()>, + ) -> io::Result<()> { + let (folder, listed) = &self.listed[section]; + let section = &self.sections[section]; + let listing = &listed[at]; + let root = match self.alone { + true => String::new(), + false => "../".repeat(folder.matches('/').count() + 1), + }; + let trail: String = (section.groups.iter()) + .map(|group| format!(" › {}", text(group))) + .collect(); + let formats = formats(&page); + self.calibri |= (formats.iter()).any(|format| format.font.as_deref() == Some("Calibri")); + let lang = (formats.iter()).find_map(|format| crate::language::tag(format.language?)); + self.lang = self.lang.or(lang); + let mut assets = Assets { + write, + written: &mut self.written, + }; + let body = match page_html(page, engine, &mut assets, &self.links, &root) { + Ok(body) => body?, + Err(error) => format!( + "

    This page couldn't be exported: {}

    ", + text(&error.to_string()) + ), + }; + if self.alone { + let head = head(&listing.title, lang, &root); + let html = format!("{head}{body}\n\n\n"); + return (assets.write)(&listing.href, html.as_bytes()); + } + let mut nav = String::new(); + page_list(listed, Some(at), &root, &mut nav); + let html = format!( + "{head}
    {notebook}{trail} › {name}
    \n\ +
    \n{body}\n\n
    \n\ + \n\n", + head = head( + &format!("{} - {}", listing.title, section.name), + lang, + &root + ), + name = text(§ion.name), + notebook = text(&self.notebook), + ); + (assets.write)(&listing.href, html.as_bytes()) + } + + /// Writes the index, listing every section in its groups, and the stylesheet. + pub fn finish(self, write: &mut dyn FnMut(&str, &[u8]) -> io::Result<()>) -> io::Result<()> { + let mut index = String::new(); + let mut groups: Vec<&String> = Vec::new(); + for (section, (_, pages)) in self.sections.iter().zip(&self.listed) { + // The index nests sections in their groups as the notebook does. + let kept = (groups.iter().zip(§ion.groups)) + .take_while(|(open, group)| *open == group) + .count(); + for _ in kept..groups.len() { + index.push_str("\n"); + } + groups.truncate(kept); + for group in §ion.groups[kept..] { + let level = (groups.len() + 2).min(6); + let _ = writeln!( + index, + "
  • {}
      ", + text(group) + ); + groups.push(group); + } + let level = (groups.len() + 2).min(6); + let color = section + .color + .map(|color| format!(" style='border-color:{}'", hex(color))); + let name = match pages.first() { + Some(page) => format!( + "{}", + href(&page.href), + text(§ion.name) + ), + None => text(§ion.name), + }; + let _ = writeln!( + index, + "
    • {name}", + color.unwrap_or_default() + ); + if section.pages.is_none() { + index.push_str("

      Locked

      \n"); + } + page_list(pages, None, "", &mut index); + index.push_str("
    • \n"); + } + for _ in groups { + index.push_str("
  • \n"); + } + let index = format!( + "{}
    \n

    {}

    \n
      \n{index}
    \n
    \n\n\n", + head(&self.notebook, self.lang, ""), + text(&self.notebook) + ); + if !self.alone { + write("index.html", index.as_bytes())?; + } + let mut style = String::new(); + // Calibri, OneNote's default, is missing from macOS and Linux; its metric-compatible + // stand-in keeps lines wrapping where they do on the page. + if self.calibri { + for face in crate::layout::bundled("Calibri").into_iter().flatten() { + use skrifa::{MetadataProvider, attribute::Style}; + let Ok(font) = skrifa::FontRef::new(face.as_ref()) else { + continue; + }; + let attributes = font.attributes(); + let weight = attributes.weight.value(); + let italic = attributes.style != Style::Normal; + let name = format!( + "fonts/Calibri-{weight}{}.ttf", + if italic { "-italic" } else { "" } + ); + write(&name, face.as_ref())?; + let _ = writeln!( + style, + "@font-face {{ font-family: Calibri; src: local(\"Calibri\"), url(\"{name}\"); \ + font-weight: {weight}; font-style: {}; }}", + if italic { "italic" } else { "normal" } + ); + } + } + style.push_str(STYLE); + write("style.css", style.as_bytes()) + } +} + +/// The formats of the text on `page`, title first. +fn formats(page: &Page) -> Vec<&onestore::document::Format> { + fn walk<'a>( + paragraphs: &'a [PageParagraph], + formats: &mut Vec<&'a onestore::document::Format>, + ) { + for paragraph in paragraphs { + match ¶graph.content { + ParagraphContent::Text(text) => { + formats.extend(text.text.spans().iter().map(|span| &span.format)) + } + ParagraphContent::Table(table) => { + for cell in table.rows.iter().flat_map(|row| &row.cells) { + walk(&cell.paragraphs, formats); + } + } + _ => {} + } + } + } + let mut formats = Vec::new(); + let titles = page.objects.iter().filter_map(|object| match object { + PageObject::Title(title) => Some(&title.outlines), + _ => None, + }); + for outline in titles.flatten() { + walk(&outline.paragraphs, &mut formats); + } + for object in &page.objects { + if let PageObject::Outline(outline) = object { + walk(&outline.paragraphs, &mut formats); + } + } + formats +} + +/// A document in `lang`, titled `title`, its stylesheet from `root`, to its body's start. +fn head(title: &str, lang: Option<&str>, root: &str) -> String { + let lang = lang.map(|lang| format!(" lang={lang}")).unwrap_or_default(); + format!( + "\n\n\n\n\ + \n\ + \n{}\n\ + \n\n\n", + text(title) + ) +} + +/// Where the exported files lie that links into the notebook name, by identity. +#[derive(Default)] +struct Links { + /// A section's first page. + sections: BTreeMap<[u8; 16], String>, + /// A page's file. + pages: BTreeMap<[u8; 16], String>, +} + +impl Links { + /// Where stored link `target` leads from `root`: into the export, to its file; out of the + /// notebook, as stored where HTML may link it. None for anything else, a link into the + /// notebook outside the export among them, whose address names the writer's own files. + fn link(&self, target: &str, root: &str) -> Option { + self.resolve(target, root).or_else(|| { + linkable(target).filter(|target| { + !(target.get(..8)).is_some_and(|scheme| scheme.eq_ignore_ascii_case("onenote:")) + }) + }) + } + + /// Where `target` leads in the site, from `root`, a paragraph to its anchor; none for a + /// link to something outside it, or to anything but the notebook. + fn resolve(&self, target: &str, root: &str) -> Option { + let link = onestore::page::link::parse_internal_link(target)?; + let (file, fragment) = match link.page { + Some(page) => ( + self.pages.get(&page)?, + link.object.map(|object| format!("#{}", anchor(object))), + ), + None => (self.sections.get(&link.section)?, None), + }; + Some(format!( + "{root}{}{}", + href(file), + fragment.unwrap_or_default() + )) + } +} + +/// The element id of paragraph `id`. +fn anchor(id: ExGuid) -> String { + let guid: String = id.guid.iter().map(|byte| format!("{byte:02x}")).collect(); + format!("p{guid}-{}", id.n) +} + +/// A page as navigation lists it. +struct Listed { + href: String, + title: String, + level: u32, +} + +/// `pages` as a list nested by level, `current` marked, hrefs from `root`. +fn page_list(pages: &[Listed], current: Option, root: &str, out: &mut String) { + let mut levels: Vec = Vec::new(); + for (at, page) in pages.iter().enumerate() { + while levels.last().is_some_and(|level| *level > page.level) { + out.push_str("\n"); + levels.pop(); + } + match levels.last() { + Some(level) if *level == page.level => out.push_str("\n"), + _ => { + out.push_str("
      \n"); + levels.push(page.level); + } + } + let current = if current == Some(at) { + " aria-current=page" + } else { + "" + }; + let _ = write!( + out, + "
    • {}", + href(&page.href), + text(&page.title) + ); + } + for _ in levels { + out.push_str("
    \n"); + } +} + +/// Pictures, files, tag icons and fonts copied beside the pages, each once. +struct Assets<'a> { + write: &'a mut dyn FnMut(&str, &[u8]) -> io::Result<()>, + written: &'a mut BTreeSet, +} + +impl Assets<'_> { + /// `bytes` at `name` under the site's folder, unless already there. + fn put(&mut self, name: String, bytes: &[u8]) -> io::Result { + if !self.written.contains(&name) { + (self.write)(&name, bytes)?; + self.written.insert(name.clone()); + } + Ok(name) + } + + /// Where the picture lies: its stored bytes in a format browsers show, else the raster + /// OneNote made of them; none where it has neither. + fn picture(&mut self, image: &Image) -> io::Result> { + let shown = [&image.bytes, &image.display] + .into_iter() + .flatten() + .find_map(|bytes| Some((bytes, shown_extension(bytes)?))); + let Some((bytes, extension)) = shown else { + return Ok(None); + }; + self.put(format!("files/{}.{extension}", digest(bytes)), bytes) + .map(Some) + } + + /// Where an attached file's copy lies, under its own name, and its icon. + fn file(&mut self, file: &Attachment) -> io::Result<(Option, String)> { + let copy = match &file.bytes { + Some(bytes) => Some(self.put( + format!("files/{}/{}", digest(bytes), component(&file.filename)), + bytes, + )?), + None => None, + }; + let preview = + (file.preview.as_deref()).and_then(|icon| Some((icon, shown_extension(icon)?))); + let icon = match preview { + Some((icon, extension)) => { + self.put(format!("files/{}.{extension}", digest(icon)), icon)? + } + None if self.written.contains(BLANK_FILE) => BLANK_FILE.to_owned(), + None => self.put(BLANK_FILE.to_owned(), &crate::gpu::page::file_icon())?, + }; + Ok((copy, icon)) + } + + /// The tag's icon, laid out as the page draws it in `[x, y]` points from where its + /// element starts. + fn tag(&mut self, tag: &ParagraphTag, [x, y]: [f32; 2], root: &str) -> io::Result { + let checked = matches!(tag.icon, TagIcon::Symbol { checked: true, .. }); + let label = match (tag.label.as_str(), checked) { + ("", _) => "Tag".to_owned(), + (label, true) => format!("{label} (done)"), + (label, false) => label.to_owned(), + }; + let mut out = format!( + "", + label = text(&label), + side = tag.size, + ); + for source in tag_sources(tag.icon) { + let name = self.put( + format!("tags/{}.svg", digest(source.as_bytes())), + source.as_bytes(), + )?; + let _ = write!(out, "\"\""); + } + out.push_str(""); + Ok(out) + } +} + +/// The file extension of a picture in a format every browser shows; none for another. +fn shown_extension(bytes: &[u8]) -> Option<&'static str> { + use image::ImageFormat; + match image::guess_format(bytes).ok()? { + ImageFormat::Png => Some("png"), + ImageFormat::Jpeg => Some("jpg"), + ImageFormat::Gif => Some("gif"), + ImageFormat::Bmp => Some("bmp"), + ImageFormat::WebP => Some("webp"), + _ => None, + } +} + +/// The page's `
    `: each object on the page where the page lays it out. +fn page_html( + mut page: Page, + engine: &mut TextEngine, + assets: &mut Assets, + links: &Links, + root: &str, +) -> Result, crate::editor::EditorError> { + let objects = build(&mut page, engine, false)?.objects; + Ok(PageWriter { + assets, + links, + root, + definitions: &page.definitions, + } + .write(&page, &objects)) +} + +struct PageWriter<'a, 'b> { + assets: &'a mut Assets<'b>, + links: &'a Links, + root: &'a str, + definitions: &'a BTreeMap, +} + +impl PageWriter<'_, '_> { + fn write(&mut self, page: &Page, objects: &[Content]) -> io::Result { + let mut bounds = [f32::INFINITY, f32::INFINITY, 0.0_f32, 0.0_f32]; + let mut body = String::new(); + for object in objects { + let rect = match object { + Content::Outline { source, layout, .. } => { + let [x, y] = crate::origin(&source.layout); + let heading = if source.title { + " role=heading aria-level=1" + } else { + "" + }; + self.outline(&source.paragraphs, layout, [x, y], heading, &mut body)?; + [x, y, x + layout.size[0], y + layout.size[1]] + } + Content::Image(image) => { + let [x, y] = crate::origin(&image.layout); + let Some([width, height]) = crate::outline::image_size(image) else { + continue; + }; + let style = format!("left:{x}pt;top:{y}pt;width:{width}pt;height:{height}pt"); + body.push_str(&self.picture(image, &style)?); + [x, y, x + width, y + height] + } + Content::File { source, .. } => { + let Some((_, rect)) = object.file() else { + continue; + }; + let style = format!("left:{}pt;top:{}pt", rect[0], rect[1]); + body.push_str(&self.file(source, &style)?); + rect + } + Content::Ink(ink) => { + let Some(rect) = ink_bounds(ink) else { + continue; + }; + let style = format!("left:{}pt;top:{}pt;", rect[0], rect[1]); + body.push_str(&ink_svg(ink, &style)); + rect + } + Content::ReadOnly(object) => { + let [x0, y0, x1, y1] = object.rect(); + let _ = write!( + body, + "
    \ + {}
    ", + x1 - x0, + y1 - y0, + text(&object.message.replace("\nRead-only", "")) + ); + [x0, y0, x1, y1] + } + Content::Date { .. } | Content::Editable(_) => continue, + }; + if let Some((_, tags, rect)) = object.tagged() { + for tag in crate::outline::object_tags(tags, self.definitions, rect) { + body.push_str(&self.assets.tag(&tag, tag.origin, self.root)?); + } + } + bounds = [ + bounds[0].min(rect[0]), + bounds[1].min(rect[1]), + bounds[2].max(rect[2]), + bounds[3].max(rect[3]), + ]; + } + // A right-to-left page lies far right of its origin, which OneNote opens scrolled to. + let left = if page.rtl && bounds[0].is_finite() { + bounds[0] - MARGIN + } else { + 0.0 + }; + let color = page + .color + .map(|color| format!(" style='background:{}'", hex(color))); + Ok(format!( + "
    \n
    \n\ + {}{body}
    \n
    ", + color.unwrap_or_default(), + -left, + bounds[2] + MARGIN, + bounds[3] + MARGIN, + rules(page) + )) + } + + fn outline( + &mut self, + paragraphs: &[PageParagraph], + layout: &OutlineLayout, + [x, y]: [f32; 2], + heading: &str, + out: &mut String, + ) -> io::Result<()> { + let mut visible: Vec = crate::outline::visible_paragraphs(paragraphs.iter()) + .cloned() + .collect(); + repaint(&mut visible, layout); + let definitions = self.definitions; + let column = layout.tag_column_offset(); + let mut extras = OutlineExtras { + writer: self, + paragraphs: (layout.paragraphs.iter()) + .map(|paragraph| (paragraph.id, paragraph)) + .collect(), + column, + failed: None, + }; + let mut html = String::new(); + blocks(&visible, definitions, &mut extras, &mut html); + if let Some(error) = extras.failed { + return Err(error); + } + let _ = write!( + out, + "
    \n{html}", + layout.size[0] + ); + // Text carries its own tags; those on tables and pictures lie where the page lays them. + for (paragraph, [tx, ty], tag) in layout.tags() { + if !layout.paragraphs.iter().any(|text| text.id == paragraph) { + out.push_str(&self.assets.tag(tag, [tx + column, ty], self.root)?); + } + } + out.push_str("
    \n"); + Ok(()) + } + + /// A picture, linked where it links, at `style`. + fn picture(&mut self, image: &Image, style: &str) -> io::Result { + let link = (image.link.as_deref()).and_then(|link| self.links.link(link, self.root)); + let (outer, inner) = match link { + Some(_) => (style, "width:100%;height:100%"), + None => ("", style), + }; + let picture = match self.assets.picture(image)? { + Some(name) => format!( + "\"{}\"", + self.root, + href(&name), + text(image.alt.as_deref().unwrap_or_default()) + ), + None => format!("Picture not shown"), + }; + // A link holding only a picture is named by the picture's text, else as a picture. + let label = match image.alt.as_deref().map(str::trim) { + Some("") | None => " aria-label=Picture", + Some(_) => "", + }; + Ok(match link { + Some(link) => format!( + "{picture}", + text(&link) + ), + None => picture, + }) + } + + /// A file as OneNote shows one, its icon over its name, linking to its copy. + fn file(&mut self, file: &Attachment, style: &str) -> io::Result { + let (copy, icon) = self.assets.file(file)?; + let name = std::path::Path::new(&file.filename) + .file_stem() + .map_or(file.filename.clone(), |stem| { + stem.to_string_lossy().into_owned() + }); + let [width, height] = file.size.unwrap_or([24.0, 24.0]); + let inner = format!( + "\"\"{}", + self.root, + href(&icon), + text(&name) + ); + Ok(match copy { + Some(copy) => format!( + "{inner}", + self.root, + href(©), + text(&file.filename) + ), + None => format!("{inner}"), + }) + } +} + +/// What a page adds to the blocks Copy writes: text paragraphs' alignment, spacing and tags, +/// and the pictures, files and drawings in an outline. +struct OutlineExtras<'w, 'a, 'b> { + writer: &'w mut PageWriter<'a, 'b>, + paragraphs: BTreeMap, + column: f32, + /// The first file that couldn't be written. + failed: Option, +} + +impl Extras for OutlineExtras<'_, '_, '_> { + fn style(&mut self, node: &PageParagraph) -> String { + let Some(format) = (node.text()) + .and_then(|text| text.text.spans().first()) + .map(|span| &span.format) + else { + return String::new(); + }; + let mut style = String::new(); + match format.alignment { + Some(1) => style.push_str(";text-align:center"), + Some(2) => style.push_str(";text-align:right"), + _ => {} + } + // Lines as tall as the page's, whose line boxes take Windows' font metrics. + if let Some(paragraph) = self.paragraphs.get(&node.id) { + let mut heights = paragraph.text.lines().map(|(_, line)| line.height); + if let Some(first) = heights.next() + && heights.all(|height| (height - first).abs() < 0.01) + { + let _ = write!(style, ";line-height:{first}pt"); + } + } + if let Some(before) = format.space_before.filter(|space| *space > 0.0) { + let _ = write!(style, ";margin-top:{before}pt"); + } + if let Some(after) = format.space_after.filter(|space| *space > 0.0) { + let _ = write!(style, ";margin-bottom:{after}pt"); + } + style + } + + fn attributes(&mut self, node: &PageParagraph) -> String { + // The number the page shows, which a list's own count would not give. + (self.paragraphs.get(&node.id)) + .and_then(|paragraph| paragraph.number.as_ref()) + .map(|(count, _)| format!(" value={}", count.number)) + .unwrap_or_default() + } + + fn link(&mut self, target: &str) -> Option { + self.writer.links.link(target, self.writer.root) + } + + fn content(&mut self, node: &PageParagraph, out: &mut String) { + let _ = write!(out, "", anchor(node.id)); + let written = match &node.content { + ParagraphContent::Text(_) => { + let Some(paragraph) = self.paragraphs.get(&node.id) else { + return; + }; + // List markers as the page numbers and places them, which HTML's lists can't. + let mut tags = String::new(); + let font = (node.text()) + .and_then(|text| text.text.spans().first()) + .map(|span| &span.format); + let lists = node.lists.iter().rev(); + for ((marker, [x, y]), list) in paragraph.markers.iter().zip(lists) { + let size = (self.writer.definitions.get(list)) + .and_then(|list| list.format.font_size) + .or(font.and_then(|font| font.font_size)) + .unwrap_or(crate::layout::DEFAULT_FONT_SIZE); + let family = font_name( + (font.and_then(|font| font.font.as_deref())) + .unwrap_or(crate::layout::DEFAULT_FONT), + ) + .map(|family| format!("font-family:\"{family}\";")) + .unwrap_or_default(); + // The list item tells assistive technology its number or bullet. + let _ = write!( + tags, + "", + x - paragraph.origin[0], + text(&marker.text) + ); + } + let mut result = Ok(()); + for tag in ¶graph.tags { + let at = [ + tag.origin[0] + self.column - paragraph.origin[0], + tag.origin[1], + ]; + match self.writer.assets.tag(tag, at, self.writer.root) { + Ok(tag) => tags.push_str(&tag), + Err(error) => result = Err(error), + } + } + result.map(|()| tags) + } + ParagraphContent::Image(image) => match crate::outline::image_size(image) { + Some([width, height]) => self + .writer + .picture(image, &format!("width:{width}pt;height:{height}pt")) + .map(|picture| format!("
    {picture}
    \n")), + None => Ok(String::new()), + }, + ParagraphContent::Attachment(file) => self + .writer + .file(file, "") + .map(|file| format!("
    {file}
    \n")), + ParagraphContent::Ink(ink) => Ok(format!("
    {}
    \n", ink_svg(ink, ""))), + ParagraphContent::Unsupported(_) => { + Ok("

    Content not shown

    \n".to_owned()) + } + ParagraphContent::Table(_) => Ok(String::new()), + }; + match written { + Ok(written) => out.push_str(&written), + Err(error) => { + self.failed.get_or_insert(error); + } + } + } +} + +/// `paragraphs` with the colour and highlight their tags give each run, as the page lays +/// them out. +fn repaint(paragraphs: &mut [PageParagraph], layout: &OutlineLayout) { + for paragraph in paragraphs { + match &mut paragraph.content { + ParagraphContent::Text(text) => { + let Some(laid) = (layout.paragraphs.iter()).find(|laid| laid.id == paragraph.id) + else { + continue; + }; + let [color, highlight] = laid.tag_paint; + if color.is_none() && highlight.is_none() { + continue; + } + let mut start = 0; + let runs: Vec<_> = (text.text.spans().iter()) + .map(|span| { + let run = text.text.text()[start..span.end].to_owned(); + start = span.end; + let mut format = span.format.clone(); + format.color = color.or(format.color); + format.highlight = highlight.or(format.highlight); + (run, format) + }) + .collect(); + text.text = onestore::page::text::Paragraph::from_runs(runs); + } + ParagraphContent::Table(table) => { + for cell in table.rows.iter_mut().flat_map(|row| &mut row.cells) { + repaint(&mut cell.paragraphs, layout); + } + } + _ => {} + } + } +} + +/// The drawing as SVG the size of its strokes, its own `style` first, its strokes as the page +/// paints them. +fn ink_svg(ink: &Ink, style: &str) -> String { + let Some([x0, y0, x1, y1]) = ink_bounds(ink) else { + return String::new(); + }; + let mut primitives = Vec::new(); + append_ink( + ink, + crate::origin(&ink.layout), + [0.0, 0.0, 0.0, 1.0], + &mut primitives, + ); + let (width, height) = (x1 - x0, y1 - y0); + let mut svg = format!( + "" + ); + let paint = |color: [f32; 4]| { + let [red, green, blue] = draw::srgb_bytes(color); + format!("#{red:02X}{green:02X}{blue:02X}' opacity='{}", color[3]) + }; + let cap = |round: bool| if round { "round" } else { "square" }; + for primitive in primitives { + match primitive { + Primitive::Segment { + from, + to, + width, + round, + color, + } => { + let _ = write!( + svg, + "", + from[0], + from[1], + to[0], + to[1], + paint(color), + cap(round) + ); + } + Primitive::Taper { + from, + to, + widths, + round, + color, + } => { + // A quadrilateral from one width to the other, capped at each end. + let [dx, dy] = [to[0] - from[0], to[1] - from[1]]; + let length = dx.hypot(dy).max(f32::EPSILON); + let [nx, ny] = [-dy / length, dx / length]; + let [a, b] = widths.map(|width| width / 2.0); + let _ = write!( + svg, + "", + from[0] + nx * a, + from[1] + ny * a, + to[0] + nx * b, + to[1] + ny * b, + to[0] - nx * b, + to[1] - ny * b, + from[0] - nx * a, + from[1] - ny * a, + paint(color) + ); + if round { + for ([x, y], radius) in [(from, a), (to, b)] { + let _ = write!( + svg, + "", + paint(color) + ); + } + } + } + Primitive::Highlight { + from, + to, + width, + color, + } => { + let _ = write!( + svg, + "", + from[0], + from[1], + to[0], + to[1], + paint(color) + ); + } + _ => {} + } + } + svg.push_str(""); + svg +} + +/// The page's rule lines and grid as backgrounds from its margin origin, as the page draws +/// them. +fn rules(page: &Page) -> String { + use crate::{HALF_INCH, MARGIN_RULE, RULE_WIDTH}; + use onestore::page::VerticalRule; + let Some(lines) = page.rule_lines else { + return String::new(); + }; + let [x, y] = page.margin_origin; + let line = |direction: &str, color: u32| { + format!( + "linear-gradient(to {direction}, {} {RULE_WIDTH}pt, transparent {RULE_WIDTH}pt)", + hex(color) + ) + }; + // Each line is centred on its place, as the page draws it. + let centred = -RULE_WIDTH / 2.0; + let mut images = vec![line("bottom", lines.color)]; + let mut sizes = vec![format!("100% {}pt", lines.spacing * HALF_INCH)]; + let mut positions = vec![format!("0 {centred}pt")]; + let mut repeats = vec!["repeat-y"]; + let mut left = 0.0; + match lines.vertical { + VerticalRule::Margin(color) => { + images.push(line("right", color)); + sizes.push("100% 100%".into()); + positions.push(format!("{}pt 0", x - MARGIN_RULE + centred)); + repeats.push("no-repeat"); + } + VerticalRule::Grid { spacing, color } => { + let spacing = spacing * HALF_INCH; + // The grid repeats from the margin origin both ways. + left = x - (x / spacing).ceil() * spacing; + images.push(line("right", color)); + sizes.push(format!("{spacing}pt 100%")); + positions.push(format!("{centred}pt 0")); + repeats.push("repeat-x"); + } + } + format!( + "
    \n", + images.join(","), + sizes.join(","), + positions.join(","), + repeats.join(",") + ) +} + +/// A page's title as navigation shows it. +fn shown_title(title: &str) -> String { + match title.trim() { + "" => "Untitled page".to_owned(), + title => title.to_owned(), + } +} + +/// The section's folder in the site, its groups' and its own names as path components, unlike +/// any folder `taken` (as `same_name` gives them), which it joins. +fn folder(section: &Section, taken: &mut BTreeSet) -> String { + let path = (section.groups.iter().chain([§ion.name])) + .map(|name| component(name)) + .collect::>() + .join("/"); + let folder = (1..) + .map(|number| match number { + 1 => path.clone(), + number => format!("{path} {number}"), + }) + .find(|folder| !taken.contains(&same_name(folder))) + .expect("some number is free"); + taken.insert(same_name(&folder)); + folder +} + +/// `name` as macOS and Windows compare names: case and Unicode composition aside. +fn same_name(name: &str) -> String { + icu_normalizer::ComposingNormalizerBorrowed::new_nfc() + .normalize(name) + .to_lowercase() +} + +/// `name` as a file or folder name every system takes, cut short where it is long so that +/// paths nested a few deep stay within Windows' 260 characters. +fn component(name: &str) -> String { + let name: String = name + .chars() + .map(|c| match c { + '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '#' | '%' => '-', + c if c.is_control() => ' ', + c => c, + }) + .collect(); + let mut end = name.len().min(48); + while !name.is_char_boundary(end) { + end -= 1; + } + let name = name[..end].trim_matches(|c: char| c.is_whitespace() || c == '.'); + // Windows reserves these names for devices, with or without an extension. + let stem = name + .split('.') + .next() + .unwrap_or_default() + .to_ascii_uppercase(); + let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") + || (stem.len() == 4 + && (stem.starts_with("COM") || stem.starts_with("LPT")) + && stem.as_bytes()[3].is_ascii_digit()); + match name { + "" => "Untitled".to_owned(), + name if reserved => match name.split_once('.') { + Some((stem, extension)) => format!("{stem}_.{extension}"), + None => format!("{name}_"), + }, + name => name.to_owned(), + } +} + +/// `path` as a URL path: every byte but unreserved characters and `/` percent-encoded. +fn href(path: &str) -> String { + let mut encoded = String::with_capacity(path.len()); + for byte in path.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => { + encoded.push(byte as char) + } + byte => { + let _ = write!(encoded, "%{byte:02X}"); + } + } + } + encoded +} + +/// Text as HTML shows it, also inside a quoted attribute. +fn text(value: &str) -> String { + escape(value, &mut false) +} + +fn hex(color: u32) -> String { + let [red, green, blue] = draw::srgb_bytes(colorref(color)); + format!("#{red:02X}{green:02X}{blue:02X}") +} + +fn digest(bytes: &[u8]) -> String { + Sha256::digest(bytes)[..8] + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A section of a corpus file, listed as the app lists it, and its pages. + fn section(name: &str, groups: &[&str], bytes: &[u8]) -> (Section, Vec) { + let arena = onestore::Arena::default(); + let mut stored = onestore::Section::open(&arena, bytes.to_vec()).unwrap(); + let (mut listings, mut pages) = (Vec::new(), Vec::new()); + for (space, title, level) in stored.pages().unwrap() { + let page = stored.page(space).unwrap(); + listings.push(Listing { + title, + level, + identity: page.identity, + }); + pages.push(page); + } + let section = Section { + groups: groups.iter().map(|group| (*group).to_owned()).collect(), + name: name.to_owned(), + color: Some(0x00d6a37c), + identity: Some(onestore::Header::parse(&bytes[..1024]).unwrap().file_id), + pages: Some(listings), + }; + (section, pages) + } + + /// The site's files, written a section at a time. + fn written(sections: Vec<(Section, Vec)>) -> BTreeMap> { + let mut files = BTreeMap::new(); + let mut write = |name: &str, bytes: &[u8]| { + assert!( + files.insert(name.to_owned(), bytes.to_vec()).is_none(), + "{name} written twice" + ); + Ok(()) + }; + let (listed, pages): (Vec<_>, Vec<_>) = sections.into_iter().unzip(); + let mut site = Site::new("Notebook", listed); + let mut engine = TextEngine::default(); + for (section, pages) in pages.into_iter().enumerate() { + for (at, page) in pages.into_iter().enumerate() { + site.page([section, at], page, &mut engine, &mut write) + .unwrap(); + } + } + site.finish(&mut write).unwrap(); + files + } + + /// Every `href` and `src` of the site's pages, each with the page holding it. + fn references(files: &BTreeMap>) -> Vec<(&str, String)> { + let mut references = Vec::new(); + for (name, bytes) in files.iter().filter(|(name, _)| name.ends_with(".html")) { + let page = std::str::from_utf8(bytes).unwrap(); + for attribute in ["href=\"", "src=\""] { + for (at, _) in page.match_indices(attribute) { + let value = &page[at + attribute.len()..]; + let value = &value[..value.find('"').unwrap()]; + references.push((name.as_str(), value.to_owned())); + } + } + } + references + } + + /// The site's file `link` from page `name` leads to, and the anchor it names. + fn resolved(name: &str, link: &str) -> (String, Option) { + let (path, anchor) = match link.split_once('#') { + Some((path, anchor)) => (path, Some(anchor.to_owned())), + None => (link, None), + }; + let mut file = std::path::Path::new(name).parent().unwrap().to_path_buf(); + for component in percent_decoded(path).split('/') { + match component { + ".." => assert!(file.pop(), "{name} reaches past the site: {link}"), + component => file.push(component), + } + } + (file.to_str().unwrap().to_owned(), anchor) + } + + /// Every page of a notebook with tagged tables, pictures, files and a recording is written, + /// and everything a page or the index points at lies in the site: nothing is asked of a + /// server. + #[test] + fn a_site_holds_everything_its_pages_point_at() { + let sections = vec![ + section( + "Tables", + &[], + include_bytes!("../../../corpus/table-tags/candidate/Tables.one"), + ), + section( + "Features", + &["Group", "Inner"], + include_bytes!("../../../corpus/media-edit/cold/notebook/Features.one"), + ), + ]; + let pages: usize = sections.iter().map(|(_, pages)| pages.len()).sum(); + let files = written(sections); + let html = files.keys().filter(|name| name.ends_with(".html")).count(); + assert_eq!(html, pages + 1); + assert!(files.contains_key("Group/Inner/Features/10 Files and recording.html")); + assert!(files.keys().any(|name| name.starts_with("tags/"))); + assert_eq!( + files.keys().any(|name| name.starts_with("fonts/")), + crate::layout::bundled("Calibri").is_some() + ); + for (name, link) in references(&files) { + if link.contains(':') { + continue; + } + let (path, _) = resolved(name, &link); + assert!(files.contains_key(&path), "{name} points at missing {path}"); + } + // Links may lead out of the site; nothing a page shows comes from outside it. + for (name, bytes) in &files { + let text = String::from_utf8_lossy(bytes); + assert!( + !text.contains("src=\"http") && !text.contains("url(http"), + "{name}" + ); + } + let index = String::from_utf8_lossy(&files["index.html"]); + assert!(index.contains("

    Group

    ") && index.contains("

    Inner

    ")); + assert!(index.contains("

    "), "{page}"); + assert!(page.contains("role=heading aria-level=1"), "{page}"); + } + + /// Links to a page and a section in the export lead to their files; links into the + /// notebook outside it, or to anything but the web or mail, stay text. + #[test] + fn links_into_the_notebook_lead_to_the_exported_pages() { + let files = written(vec![ + section( + "Internal", + &[], + include_bytes!("../../../corpus/link-edit/internal/candidate/links.one"), + ), + section( + "Native", + &["Group"], + include_bytes!("../../../corpus/link-edit/native-links/notebook/links.one"), + ), + ]); + let mut rewritten = 0; + for (name, link) in references(&files) { + assert!(!link.starts_with("onenote:"), "{name} keeps {link}"); + if link.contains(':') || name == "index.html" { + continue; + } + let (path, _) = resolved(name, &link); + assert!(files.contains_key(&path), "{name} points at missing {path}"); + rewritten += 1; + } + assert!(rewritten > 0); + // The page, paragraph and section links of the native page, beside its page list. + let native = + String::from_utf8_lossy(&files["Group/Native/01 Read about Rust the Rust site.html"]); + for (link, count) in [ + ("02%20Link%20target.html\"", 2), + ("02%20Link%20target.html#p", 1), + ("01%20Read%20about%20Rust%20the%20Rust%20site.html\"", 2), + ] { + assert_eq!(native.matches(link).count(), count, "{link} in {native}"); + } + } + + /// A link to a paragraph leads to its anchor on the exported page. + #[test] + fn a_paragraph_link_leads_to_its_anchor() { + use onestore::page::link::{LinkTarget, internal_link}; + let (section, pages) = section( + "Internal", + &[], + include_bytes!("../../../corpus/link-edit/internal/candidate/links.one"), + ); + let paragraph = pages[1] + .objects + .iter() + .find_map(|object| match object { + PageObject::Outline(outline) => outline.paragraphs.first(), + PageObject::Title(title) => title.outlines.first()?.paragraphs.first(), + _ => None, + }) + .unwrap() + .id; + let target = LinkTarget::Object { + identity: pages[1].identity.unwrap(), + title: "", + object: paragraph, + }; + let link = internal_link(section.identity.unwrap(), "", target); + let site = Site::new("Notebook", vec![section]); + let resolved = site.links.link(&link, "../").unwrap(); + assert_eq!( + resolved, + format!("../Internal/02%20Link%20target.html#{}", anchor(paragraph)) + ); + let files = written(vec![self::section( + "Internal", + &[], + include_bytes!("../../../corpus/link-edit/internal/candidate/links.one"), + )]); + let target = String::from_utf8_lossy(&files["Internal/02 Link target.html"]); + assert!(target.contains(&format!("", anchor(paragraph)))); + } + + /// A locked section is listed with its name and colour and a note, and has no pages. + #[test] + fn a_locked_section_is_listed_as_locked() { + let files = written(vec![( + Section { + groups: Vec::new(), + name: "Diary".into(), + color: Some(0x000000ff), + identity: None, + pages: None, + }, + Vec::new(), + )]); + let index = String::from_utf8(files["index.html"].clone()).unwrap(); + assert!( + index.contains("

    Diary

    "), + "{index}" + ); + assert!(index.contains("

    Locked

    ")); + assert_eq!( + files.keys().filter(|name| name.ends_with(".html")).count(), + 1 + ); + } + + /// Fonts, link targets, titles and names stored on a page can't put script, handlers or + /// outside requests into its file. + #[test] + fn hostile_strings_in_a_page_stay_inert() { + let (mut listed, mut pages) = section( + "Sec'tion\" ", + &["Gro'up"], + include_bytes!("../../../corpus/media-edit/cold/notebook/Features.one"), + ); + let hostile = [ + "Evil' tabindex=1 autofocus onfocus='alert(1)//", + "A B\";background-image:url(https://evil.example/px.png);x:\"", + ]; + let link = |target: &str| { + let code = onestore::document::Format { + hyperlink: Some(true), + hidden: Some(true), + ..Default::default() + }; + let label = onestore::document::Format { + hyperlink: Some(true), + hyperlink_label: Some(true), + ..Default::default() + }; + [ + (format!("\u{fddf}HYPERLINK \"{target}\""), code), + ("label".to_owned(), label), + ] + }; + fn poison( + paragraphs: &mut [PageParagraph], + font: &str, + runs: &[(String, onestore::document::Format)], + ) { + for paragraph in paragraphs { + if let ParagraphContent::Text(text) = &mut paragraph.content { + let mut all: Vec<_> = (text.text.spans().iter()) + .scan(0, |start, span| { + let run = text.text.text()[*start..span.end].to_owned(); + *start = span.end; + let mut format = span.format.clone(); + format.font = Some(font.to_owned()); + Some((run, format)) + }) + .collect(); + all.extend(runs.iter().cloned()); + text.text = onestore::page::text::Paragraph::from_runs(all); + } + } + } + let runs: Vec<_> = [ + "javascript:alert(document.domain)", + "data:text/html,x", + "file:///etc/passwd", + ] + .into_iter() + .flat_map(link) + .collect(); + for (at, page) in pages.iter_mut().enumerate() { + for object in &mut page.objects { + match object { + PageObject::Outline(outline) => { + poison(&mut outline.paragraphs, hostile[at % 2], &runs) + } + PageObject::Image(image) => image.link = Some("javascript:alert(2)".into()), + _ => {} + } + } + } + for listing in listed.pages.iter_mut().flatten() { + listing.title = "it's \"".into(); + } + listed.name = "Sec'tion\" ".into(); + let files = written(vec![(listed, pages)]); + for (name, bytes) in &files { + if !name.ends_with(".html") { + continue; + } + let html = String::from_utf8_lossy(bytes); + for bad in [ + "onfocus", + "autofocus", + "url(", + "javascript", + "data:text", + "file:", + "", + "Evil", + "evil.example", + ] { + assert!(!html.contains(bad), "{bad} in {name}"); + } + } + } + + /// Sections whose names a file system would take for the same folder, or refuse, get + /// folders of their own, and deep groups stay short. + #[test] + fn sections_get_folders_of_their_own() { + let named = |groups: &[&str], name: &str| Section { + groups: groups.iter().map(|group| (*group).to_owned()).collect(), + name: name.to_owned(), + color: None, + identity: None, + pages: Some(vec![Listing { + title: "Page".into(), + level: 1, + identity: None, + }]), + }; + let long = "A rather long group name that goes on for quite a while"; + let site = Site::new( + "Notebook", + vec![ + named(&[], "Plans #1"), + named(&[], "plans %1"), + named(&[], "CON"), + named(&[], "com1.txt"), + named(&[], " . . "), + named(&[], "Cafe\u{301}"), + named(&[], "Caf\u{e9}"), + named(&[long, long, long, long], long), + ], + ); + let folders: Vec<&str> = site + .listed + .iter() + .map(|(folder, _)| folder.as_str()) + .collect(); + assert_eq!( + folders[..5], + ["Plans -1", "plans -1 2", "CON_", "com1_.txt", "Untitled"] + ); + assert_eq!(folders[6], "Caf\u{e9} 2"); + assert!(folders[7].len() <= 5 * 49, "{}", folders[7]); + } + + /// A page alone is the page as `index.html`, with no header or page list, its pictures, + /// files and fonts beside it. + #[test] + fn a_page_alone_is_the_page_and_nothing_else() { + let (mut section, mut pages) = section( + "Features", + &["Group"], + include_bytes!("../../../corpus/media-edit/cold/notebook/Features.one"), + ); + let page = pages.remove(0); + section.pages.as_mut().unwrap().truncate(1); + let mut files = BTreeMap::new(); + let mut write = |name: &str, bytes: &[u8]| { + files.insert(name.to_owned(), bytes.to_vec()); + Ok(()) + }; + let mut site = Site::page_alone("Notebook", section); + site.page([0, 0], page, &mut TextEngine::default(), &mut write) + .unwrap(); + site.finish(&mut write).unwrap(); + let html = String::from_utf8_lossy(&files["index.html"]); + assert!( + !html.contains("
    ") && !html.contains(" String { + let bytes = link.as_bytes(); + let mut decoded = Vec::new(); + let mut at = 0; + while at < bytes.len() { + if bytes[at] == b'%' { + decoded.push(u8::from_str_radix(&link[at + 1..at + 3], 16).unwrap()); + at += 3; + } else { + decoded.push(bytes[at]); + at += 1; + } + } + String::from_utf8(decoded).unwrap() + } +} diff --git a/crates/notebook/src/lib.rs b/crates/notebook/src/lib.rs index dff88249c9399bf035db785988655c645eeb4b83..e7a3902041f8089d7e15f5064dac23b5d000237b 100644 --- a/crates/notebook/src/lib.rs +++ b/crates/notebook/src/lib.rs @@ -417,6 +417,11 @@ impl Replica { self.ask(|reply| working::Request::Pages { reply }) } + /// Each page's notebook-management identity, which internal links name. + pub fn identities(&self) -> Result)>> { + self.ask(|reply| working::Request::Identities { reply }) + } + /// The conflict pages of each page that has them (`onestore::Section::conflicts`). pub fn conflicts(&self) -> Result)>> { self.ask(|reply| working::Request::Conflicts { reply }) diff --git a/crates/notebook/src/session.rs b/crates/notebook/src/session.rs index df0304a9be9e9f7754f13802e71baa44c4cb88de..60caa43abd5b687fcf93b45778710856d56a457c 100644 --- a/crates/notebook/src/session.rs +++ b/crates/notebook/src/session.rs @@ -2995,6 +2995,11 @@ impl Section { self.replica.page(space) } + /// Each page's notebook-management identity, which internal links name. + pub fn identities(&self) -> Result)>> { + self.replica.identities() + } + /// Copies a page (usually from another section) to the end of this section under /// fresh identities, queued like the user's own edits. Returns the new page's space. /// Content outside the model refuses to copy. diff --git a/crates/notebook/src/working.rs b/crates/notebook/src/working.rs index 21e898b8f3cb374672f0776be59220989870ef50..8791f896d61783fb54698d04da9642f48ea5627d 100644 --- a/crates/notebook/src/working.rs +++ b/crates/notebook/src/working.rs @@ -36,6 +36,9 @@ pub(crate) enum Request { Pages { reply: Reply>, }, + Identities { + reply: Reply)>>, + }, Conflicts { reply: Reply)>>, }, @@ -123,6 +126,7 @@ impl Request { Self::Apply(Accepted { reply, .. }) => reply(Err(error())), Self::Page { reply, .. } => reply(Err(error())), Self::Pages { reply } => reply(Err(error())), + Self::Identities { reply } => reply(Err(error())), Self::Conflicts { reply } => reply(Err(error())), Self::Versions { reply } => reply(Err(error())), Self::Version { reply, .. } => reply(Err(error())), @@ -814,6 +818,7 @@ impl<'a> Working<'a> { } Request::Page { .. } | Request::Pages { .. } + | Request::Identities { .. } | Request::Conflicts { .. } | Request::Versions { .. } | Request::Version { .. } @@ -881,6 +886,7 @@ impl<'a> Working<'a> { match request { Request::Page { space, reply } => reply(self.section.page(space).map_err(Into::into)), Request::Pages { reply } => reply(self.section.pages().map_err(Into::into)), + Request::Identities { reply } => reply(self.section.identities().map_err(Into::into)), Request::Conflicts { reply } => reply(self.section.conflicts().map_err(Into::into)), Request::Versions { reply } => reply(self.section.versions().map_err(Into::into)), Request::Version { diff --git a/crates/onestore/src/page/mod.rs b/crates/onestore/src/page/mod.rs index 89b837110e5445ccba8f9256c7a70dca9c1f0680..d5d696319718c86504ba6611d07785ec29fa6b43 100644 --- a/crates/onestore/src/page/mod.rs +++ b/crates/onestore/src/page/mod.rs @@ -778,6 +778,12 @@ impl Page { .roots .get(&2) .and_then(|id| revision.nodes.get(id)) + .and_then(Self::metadata_identity) + } + + /// The identity page metadata element `metadata` holds. + pub(crate) fn metadata_identity(metadata: &Element<'_>) -> Option<[u8; 16]> { + Some(metadata) .filter(|node| matches!(node.kind, Kind::Metadata { .. })) .and_then(|node| node.extra.first()) .and_then(|fields| fields.iter().find(|field| field.id == 0x1c001c30)) diff --git a/crates/onestore/src/section.rs b/crates/onestore/src/section.rs index 4944351a255a5fffe4e362040eccdbb3ad9d7843..c3168ddc4d7dd3f5818c7db06652ead131360a32 100644 --- a/crates/onestore/src/section.rs +++ b/crates/onestore/src/section.rs @@ -451,6 +451,34 @@ impl<'a> Section<'a> { .collect()) } + /// Each listed page's notebook-management identity, which internal links name, read + /// from its metadata alone. + pub fn identities(&mut self) -> Result)>> { + let spaces: Vec = self.series()?.into_keys().collect(); + let mut identities = Vec::new(); + for space in spaces { + let revision = self.revision(space)?; + let identity = match (revision.roots.get(&2)).and_then(|id| revision.objects.get(id)) { + Some(metadata) => { + let metadata = crate::document::Element::parse_with( + metadata, + FileType::Section, + &mut |_| { + Err(Error { + offset: 0, + message: "Page metadata holds no payload", + }) + }, + )?; + crate::page::Page::metadata_identity(&metadata) + } + None => None, + }; + identities.push((space, identity)); + } + Ok(identities) + } + /// Page spaces in section order with the title and outline level (1 at the top) the /// page list shows, read from each page's metadata alone. pub fn pages(&mut self) -> Result> { @@ -1210,6 +1238,20 @@ mod tests { const { std::cell::Cell::new(None) }; } + /// Page identities read from metadata alone are those the whole page holds. + #[test] + fn identities_are_those_the_pages_hold() { + let bytes = include_bytes!("../../../corpus/link-edit/native-links/notebook/links.one"); + let arena = Arena::default(); + let mut section = Section::open(&arena, bytes.to_vec()).unwrap(); + let identities = section.identities().unwrap(); + assert_eq!(identities.len(), section.pages().unwrap().len()); + for (space, identity) in identities { + assert!(identity.is_some()); + assert_eq!(identity, section.page(space).unwrap().identity); + } + } + /// `f` with `fresh_guid` counting from `seed`. fn seeded(seed: u64, f: impl FnOnce() -> T) -> T { let outer = GUIDS.replace(Some(seed)); diff --git a/crates/snowbound/src/art.rs b/crates/snowbound/src/art.rs index 8e0746aceec88c22ca1375241d43a508736b51ed..fd0b91d109ae7d02f50a04f7f30b89eda81b660a 100644 --- a/crates/snowbound/src/art.rs +++ b/crates/snowbound/src/art.rs @@ -120,6 +120,7 @@ pub const CUSTOMIZE_TAGS: &[&str] = art!("icons/tag", "icons/badge-edit"); pub const DELETE: &[&str] = art!("icons/delete"); pub const EMPTY_RECYCLE_BIN: &[&str] = art!("icons/recycle-bin", "icons/badge-remove"); pub const EXPORT_PDF: &[&str] = art!("icons/pdf"); +pub const EXPORT_WEBSITE: &[&str] = art!("icons/page", "icons/badge-link"); pub const FAST_FORWARD: &[&str] = art!("icons/fast-forward"); pub const FIND: &[&str] = art!("icons/page", "icons/badge-search"); pub const FULL_PAGE: &[&str] = art!("icons/full-page"); diff --git a/crates/snowbound/src/commands.rs b/crates/snowbound/src/commands.rs index a8d7fdd20bd0ae15e8537cdb46593073cdbc7654..06a65f8db3f0292bd3895009556ae240b71d807d 100644 --- a/crates/snowbound/src/commands.rs +++ b/crates/snowbound/src/commands.rs @@ -49,6 +49,8 @@ pub enum Id { ShowUnread, NextUnread, ExportPdf, + /// Save As on the notebook as a website. + ExportWebsite, Print, Undo, Redo, @@ -328,6 +330,7 @@ pub const COMMANDS: &[Command] = &[ ), row!(Id::NextUnread, "Next Unread", NONE, NONE), row!(Id::ExportPdf, "Export as PDF", NONE, NONE), + row!(Id::ExportWebsite, "Export as Website", NONE, NONE), // Go to takes OneNote's Ctrl+P, and Pause its Ctrl+Alt+P. row!( Id::Print, @@ -1143,7 +1146,8 @@ impl State { || self.printing.open() || self.link.is_some() || self.tag_list.is_some() - || self.server.is_some(); + || self.server.is_some() + || self.exporting.is_some(); #[cfg(any(windows, target_os = "linux"))] let modal = modal || self.prompt.strong_count() != 0; let page = (session.is_some() || self.temporary) && !modal; @@ -1219,6 +1223,9 @@ impl State { Id::LiveShare => enabled(false), Id::PasswordProtect => enabled(!modal && self.shown_section().is_some()), Id::SaveAs => enabled(!modal && self.notebook().is_some()), + Id::ExportWebsite => { + enabled(!modal && cfg!(not(target_arch = "wasm32")) && self.notebook().is_some()) + } Id::RecycleBin => Status { enabled: !modal && self @@ -1595,6 +1602,11 @@ impl State { self.open_save_as(library, None, scope); return Ok(()); } + Id::ExportWebsite => { + let library = Arc::clone(self.notebook().ok_or("No notebook is open")?); + self.open_export_website(library); + return Ok(()); + } Id::RecycleBin | Id::EmptyRecycleBin | Id::MarkNotebookRead | Id::ShowUnread => { let library = Arc::clone(self.notebook().ok_or("No notebook is open")?); match id { diff --git a/crates/snowbound/src/main.rs b/crates/snowbound/src/main.rs index d6bbeb052a5edabe50c825b301a233647b221124..1359657fa0acdc7211d2096ad0a0dd5158d0df8b 100644 --- a/crates/snowbound/src/main.rs +++ b/crates/snowbound/src/main.rs @@ -999,6 +999,8 @@ struct State { symbols: Option, /// Save As while it is open. save_as: Option, + /// The website export under way, which a dialog shows. + exporting: Option>, /// Unpack Notebook while it is open. unpacking: Option, /// Snowbound's own dialogs, first the one shown, where the desktop has none. @@ -1491,6 +1493,7 @@ impl State { properties: None, symbols: None, save_as: None, + exporting: None, unpacking: None, #[cfg(target_os = "linux")] asking: Default::default(), @@ -1750,6 +1753,7 @@ impl State { self.properties_dialog(); self.symbols_dialog(); self.save_as_dialog(); + self.exporting_dialog(); self.unpack_dialog(); self.password_dialog()?; #[cfg(target_os = "linux")] @@ -6393,6 +6397,7 @@ fn artwork(id: commands::Id) -> Option<&'static [&'static str]> { Cmd::ShowUnread => art::SHOW_UNREAD, Cmd::NextUnread => art::NEXT_UNREAD, Cmd::ExportPdf => art::EXPORT_PDF, + Cmd::ExportWebsite => art::EXPORT_WEBSITE, Cmd::Print => art::PRINT, Cmd::SelectAll => art::SELECT_ALL, Cmd::Find => art::FIND, diff --git a/crates/snowbound/src/menubar.rs b/crates/snowbound/src/menubar.rs index 7d856842e55537e6a539abf77644b03cd401a577..2af7b3c99e7d68481b040c350975dad024de94fc 100644 --- a/crates/snowbound/src/menubar.rs +++ b/crates/snowbound/src/menubar.rs @@ -83,6 +83,7 @@ const MENUS: &[Item] = &[ S, C(Id::SaveAs), C(Id::ExportPdf), + C(Id::ExportWebsite), S, C(Id::Print), ], diff --git a/crates/snowbound/src/print.rs b/crates/snowbound/src/print.rs index 338d105121cd0e721bdb4ee17198c7a41c83d56c..2fc7aeeae558c30be6927175e25a224b578f59b9 100644 --- a/crates/snowbound/src/print.rs +++ b/crates/snowbound/src/print.rs @@ -2,7 +2,11 @@ //! preview, then the chosen pages laid on paper as OneNote prints them (`canvas::print`), //! handed to the system's printing or saved. -use crate::{State, UserEvent, library::Library, platform, printer}; +use crate::{ + State, UserEvent, + library::{Library, Tab}, + platform, printer, +}; use accesskit::Role; use canvas::print::Footer; use notebook::discover::Folder; @@ -347,7 +351,7 @@ impl State { this.into_iter().collect() } else { let mut sections = Vec::new(); - for (path, name) in others { + for Tab { path, name, .. } in others { if path == open_tab.0 && let Some(open) = this.take() { @@ -422,15 +426,14 @@ fn group(levels: &[u32], at: usize) -> std::ops::Range { start..end } -/// Every readable section of `library` but the recycle bin's, catalog path and name, in the -/// order each folder's TOC lists its sections and groups, as OneNote's notebook PDF prints them. -fn notebook_tabs(library: &Library) -> Vec<(String, String)> { - fn walk(library: &Library, folder: &Folder, tabs: &mut Vec<(String, String)>) { +/// Every readable section of `library` but the recycle bin's, in the order each folder's TOC +/// lists its sections and groups, as OneNote's notebook PDF prints them. +pub(crate) fn notebook_tabs(library: &Library) -> Vec { + fn walk(library: &Library, folder: &Folder, tabs: &mut Vec) { let mut sections = library.tabs(&folder.path); for path in &folder.order { if let Some(at) = sections.iter().position(|tab| tab.path == *path) { - let tab = sections.remove(at); - tabs.push((tab.path, tab.name)); + tabs.push(sections.remove(at)); } else if let Some(group) = (folder.groups.iter()) .find(|group| group.path == *path && !crate::library::recycle_bin(&group.path)) { @@ -441,7 +444,7 @@ fn notebook_tabs(library: &Library) -> Vec<(String, String)> { let mut tabs = Vec::new(); match library.catalog() { Some(catalog) => walk(library, catalog, &mut tabs), - None => tabs.extend(library.tabs("").into_iter().map(|tab| (tab.path, tab.name))), + None => tabs.extend(library.tabs("")), } tabs } @@ -570,7 +573,7 @@ mod tests { library.close_kept(); drop(library); let _ = notebook::fs::remove_dir_all(&temporary); - let paths: Vec<&str> = tabs.iter().map(|(path, _)| path.as_str()).collect(); + let paths: Vec<&str> = tabs.iter().map(|tab| tab.path.as_str()).collect(); assert_eq!(paths, ["A.one", "G/C.one", "B.one"]); } @@ -631,7 +634,7 @@ mod tests { let library = Library::created(root.to_str().unwrap(), notebook, &cache); let paths: Vec = notebook_tabs(&library) .into_iter() - .map(|(path, _)| path) + .map(|tab| tab.path) .collect(); notebook::fs::remove_dir_all(&temporary).unwrap(); assert_eq!(paths, ["New Section 1.one", "Group/Inner.one"]); diff --git a/crates/snowbound/src/save_as.rs b/crates/snowbound/src/save_as.rs index b880eef386fc45ffd26d863eb89669041ddbd4d4..e28323194f43a4e4062a5d52a30a77ec3f7dc084 100644 --- a/crates/snowbound/src/save_as.rs +++ b/crates/snowbound/src/save_as.rs @@ -1,11 +1,15 @@ //! File, Save As, as OneNote 2010's: the page, its section or its notebook, as a OneNote -//! section (`.one`), a package (`.onepkg`) or a PDF. A page or section saved as a section is -//! a copy outside any notebook; a notebook's package holds its sections as they stand here, -//! the open one's queued edits included (`notebook::package`). +//! section (`.one`), a package (`.onepkg`), a PDF or a website. A page or section saved as a +//! section is a copy outside any notebook; a notebook's package holds its sections as they +//! stand here, the open one's queued edits included (`notebook::package`). A website is a +//! folder of web pages (`canvas::site`), offered where OneNote offers its Single File Web Page. use crate::{Library, State, UserEvent, platform, print}; use accesskit::Role; use notebook::package; +use onestore::{ExGuid, page::Page}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::{error::Error, sync::Arc}; use ui::{Anchor, Axis, Id, Spec, children, fill, popup::Item, px}; use winit::keyboard::NamedKey; @@ -24,20 +28,35 @@ const SCOPES: [(Scope, &str); 3] = [ (Scope::Notebook, "Notebook"), ]; -/// OneNote 2010's formats for each scope, as Save As lists them. -fn formats(scope: Scope) -> [(&'static str, &'static str); 2] { - match scope { - Scope::Notebook => [ +/// The formats for each scope, as Save As lists them: OneNote 2010's, then a website, which +/// has no extension, being a folder. +fn formats(scope: Scope) -> &'static [(&'static str, &'static str)] { + let formats: &[_] = match scope { + Scope::Notebook => &[ ("OneNote Package (*.onepkg)", "onepkg"), ("PDF (*.pdf)", "pdf"), + ("Website (folder)", ""), ], - _ => [ + _ => &[ ("OneNote 2010 Section (*.one)", "one"), ("PDF (*.pdf)", "pdf"), + ("Website (folder)", ""), ], + }; + // A browser keeps what it saves in its own storage, where a website is no use. + match cfg!(target_arch = "wasm32") { + true => &formats[..formats.len() - 1], + false => formats, } } +/// Where `formats` lists the website for `scope`, where it does. +fn website(scope: Scope) -> Option { + formats(scope) + .iter() + .position(|(_, extension)| extension.is_empty()) +} + /// The dialog's choices while it is open: the section a scope of Section saves, by catalog /// path, and the place in `formats` chosen. pub struct Dialog { @@ -73,6 +92,14 @@ impl State { self.ui.open_popup(id()); } + /// Opens Save As on `library`'s notebook as a website, as Export as Website does. + pub(crate) fn open_export_website(&mut self, library: Arc) { + self.open_save_as(library, None, Scope::Notebook); + if let Some(dialog) = &mut self.save_as { + dialog.format = website(Scope::Notebook).unwrap_or_default(); + } + } + /// Builds Save As while it is open; Save As… asks where, then writes on a thread. pub(crate) fn save_as_dialog(&mut self) { let Some(dialog) = &mut self.save_as else { @@ -128,9 +155,11 @@ impl State { let names: Vec<&str> = offered.iter().map(|(_, name)| *name).collect(); if let Some(at) = choose(ui, "Save current", &names, current.unwrap_or(0)) { dialog.scope = offered[at].0; - dialog.format = 0; } - let names = formats(dialog.scope).map(|(name, _)| name); + let names: Vec<&str> = formats(dialog.scope) + .iter() + .map(|(name, _)| *name) + .collect(); if let Some(at) = choose(ui, "Format", &names, dialog.format) { dialog.format = at; } @@ -153,6 +182,9 @@ impl State { /// goes through Export as PDF's settings. fn save(&mut self, dialog: Dialog) -> Result<(), Box> { let (_, extension) = formats(dialog.scope)[dialog.format]; + if extension.is_empty() { + return self.export_website(dialog); + } if extension == "pdf" { self.export_pdf(match dialog.scope { Scope::Page => print::Scope::Page, @@ -233,6 +265,398 @@ impl State { } } +/// Where an exported section's pages are read from: the open page as the editor holds it, a +/// replica open already, or the section opened anew, at most one at a time. +enum Source { + Page(Page), + /// A replica, and the page the editor holds of it. + Replica(Arc, Option<(ExGuid, Page)>), + Section(String), +} + +/// A source made readable: for `Source::Section`, the replica a parked pane holds of it, or +/// the section opened anew and closed when this is dropped. +enum Reader<'a> { + Source(&'a Source), + Held(Arc), + Section(notebook::session::Section), +} + +impl Reader<'_> { + /// Each page's space, title and level, and the identity links name it by. + fn listing(&self) -> Result, Box> { + let (pages, identities) = match self { + Self::Source(Source::Page(page)) => { + let listing = canvas::site::Listing { + title: page.title.clone(), + level: 1, + identity: page.identity, + }; + return Ok(vec![(ExGuid::default(), listing)]); + } + Self::Source(Source::Replica(replica, _)) | Self::Held(replica) => { + (replica.pages()?, replica.identities()?) + } + Self::Section(section) => (section.pages()?, section.identities()?), + Self::Source(Source::Section(_)) => unreachable!("Sections are opened to be read"), + }; + let identities: std::collections::BTreeMap<_, _> = identities.into_iter().collect(); + Ok((pages.into_iter()) + .map(|(space, title, level)| { + let identity = identities.get(&space).copied().flatten(); + let listing = canvas::site::Listing { + title, + level, + identity, + }; + (space, listing) + }) + .collect()) + } + + fn page(&self, space: ExGuid) -> Result> { + Ok(match self { + Self::Source(Source::Page(page)) => page.clone(), + Self::Source(Source::Replica(_, Some((open, page)))) if *open == space => page.clone(), + Self::Source(Source::Replica(replica, _)) | Self::Held(replica) => { + replica.page(space)? + } + Self::Section(section) => section.page(space)?, + Self::Source(Source::Section(_)) => unreachable!("Sections are opened to be read"), + }) + } +} + +impl Source { + /// The source made readable; a section opens once, so one that `held`, the parked panes' + /// replicas, holds is read from there. + async fn reader( + &self, + library: &Library, + held: &[(String, Arc)], + ) -> Result, Box> { + Ok(match self { + Self::Section(path) => match held.iter().find(|(held, _)| held == path) { + Some((_, replica)) => Reader::Held(Arc::clone(replica)), + None => Reader::Section(library.open_async(path, || {}).await?), + }, + source => Reader::Source(source), + }) + } +} + +/// A website export under way: the pages listed and written, and whether it was cancelled. +#[derive(Default)] +pub struct Exporting { + listed: AtomicBool, + written: AtomicUsize, + pages: AtomicUsize, + cancelled: AtomicBool, +} + +fn exporting_id() -> Id { + Id::ROOT.child("exporting") +} + +/// Why a website can't go in `folder`: inside a notebook, whose table of contents lies in a +/// folder holding it however the path reaches it, or holding files already. +fn unfit(folder: &Path) -> Option<&'static str> { + let existing = folder.ancestors().find(|path| path.exists())?; + let resolved = notebook::fs::canonicalize(existing).unwrap_or_else(|_| existing.to_owned()); + let notebook = |dir: &Path| { + notebook::fs::read_dir(dir).is_ok_and(|entries| { + entries.flatten().any(|entry| { + (entry.path().extension()) + .is_some_and(|extension| extension.eq_ignore_ascii_case("onetoc2")) + }) + }) + }; + if resolved.ancestors().any(notebook) { + return Some("A website can't go in a notebook's folder."); + } + notebook::fs::read_dir(folder) + .is_ok_and(|mut entries| entries.next().is_some()) + .then_some("A website needs a folder of its own, and this one already holds files.") +} + +/// Removes what an export wrote, files and then the folders it made, deepest first, leaving +/// whatever else they hold. +fn remove_written(written: &[PathBuf]) { + for path in written.iter().rev() { + let _ = if path.is_dir() { + notebook::fs::remove_dir(path) + } else { + notebook::fs::remove_file(path) + }; + } +} + +impl State { + /// Asks where to put the website `dialog` chose, then reads its pages and writes the site's + /// folder on a thread of its own, a page at a time, showing how far it has got: the open page + /// as the editor holds it, the rest as stored. Password-protected sections are listed as + /// locked, unlocked here or not, as a website is for publishing. + fn export_website(&mut self, dialog: Dialog) -> Result<(), Box> { + if self.exporting.is_some() { + return Err("A website is being exported already.".into()); + } + let library = dialog.library; + let open = match (self.session.as_ref()) + .filter(|session| Arc::ptr_eq(&session.library, &library)) + { + Some(session) => Some(( + session.tabs[session.tab].path.clone(), + Arc::clone(session.section.replica()), + self.pane.showing.space, + self.pane.view.editor.page()?, + )), + None => None, + }; + let scope = dialog.scope; + let section = dialog.section.unwrap_or_default(); + let (title, tabs) = match scope { + Scope::Notebook => (library.name.clone(), print::notebook_tabs(&library)), + _ => { + if library.protected(§ion) { + return Err("A password-protected section isn't published as a website.".into()); + } + let tab = (library + .tabs(crate::menus::folder(§ion).as_str()) + .into_iter()) + .find(|tab| tab.path == section) + .ok_or("No section is open")?; + let title = match (scope, &open) { + (Scope::Page, Some((.., page))) => page.title.clone(), + (Scope::Page, None) => return Err("No page is open".into()), + _ => tab.name.clone(), + }; + (title, vec![tab]) + } + }; + // Sections parked panes show are open already, and read from their replicas. + let held = self.held(&library.location); + let (listed, sources): (Vec<_>, Vec<_>) = (tabs.into_iter()) + .map(|tab| { + let source = match &open { + _ if library.protected(&tab.path) => None, + Some((path, _, _, page)) if *path == tab.path && scope == Scope::Page => { + Some(Source::Page(page.clone())) + } + Some((path, replica, space, page)) if *path == tab.path => Some( + Source::Replica(Arc::clone(replica), Some((*space, page.clone()))), + ), + _ => Some(Source::Section(tab.path.clone())), + }; + let mut groups: Vec = tab.path.split('/').map(str::to_owned).collect(); + groups.pop(); + let section = canvas::site::Section { + groups, + name: tab.name, + color: tab.color, + identity: library.section_identity(&tab.path), + pages: None, + }; + (section, source) + }) + .unzip(); + let name = print::file_name(&title); + let reply = self.reply(move |state, folder: PathBuf| { + if let Some(unfit) = unfit(&folder) { + platform::alert("Choose a new folder", unfit); + return Ok(()); + } + let progress = Arc::new(Exporting::default()); + state.exporting = Some(Arc::clone(&progress)); + state.ui.open_popup(exporting_id()); + let (layouts, proxy) = (Arc::clone(&state.layouts), state.proxy.clone()); + crate::spawn_async(move || async move { + let written = std::cell::RefCell::new(Vec::new()); + let exported = async { + let cancelled = || progress.cancelled.load(Ordering::Relaxed); + // First what each section lists, which its metadata alone gives, so that + // links between pages lead where they will be written. + let mut spaces = Vec::new(); + let mut listed = listed; + for (section, source) in listed.iter_mut().zip(&sources) { + if cancelled() { + return Ok(()); + } + let mut kept = Vec::new(); + if let Some(source) = source { + let listing = source.reader(&library, &held).await?.listing()?; + progress.pages.fetch_add(listing.len(), Ordering::Relaxed); + let (each, listings) = listing.into_iter().unzip(); + kept = each; + section.pages = Some(listings); + } + spaces.push(kept); + } + progress.listed.store(true, Ordering::Relaxed); + let _ = proxy.send_event(UserEvent::Redraw); + // The page in view keeps its own layout engine while this one works. + let mut engine = layouts.lock().map_err(|_| "Page layout failed")?.clone(); + let mut write = |name: &str, bytes: &[u8]| { + let path = folder.join(name); + let parent = path.parent().unwrap_or(&folder); + let mut made: Vec = (parent.ancestors()) + .take_while(|dir| !dir.exists()) + .map(Path::to_owned) + .collect(); + made.reverse(); + notebook::fs::create_dir_all(parent)?; + written.borrow_mut().extend(made); + notebook::fs::write(&path, bytes)?; + written.borrow_mut().push(path); + Ok(()) + }; + // A page goes alone, without the notebook's header and page list. + let mut site = match scope { + Scope::Page => canvas::site::Site::page_alone( + &title, + listed.into_iter().next().ok_or("No page is open")?, + ), + _ => canvas::site::Site::new(&title, listed), + }; + for (at, (source, spaces)) in sources.iter().zip(spaces).enumerate() { + let Some(source) = source else { + continue; + }; + // Each section opened is closed once its pages are written. + let reader = source.reader(&library, &held).await?; + for (page, space) in spaces.into_iter().enumerate() { + if cancelled() { + return Ok(()); + } + site.page([at, page], reader.page(space)?, &mut engine, &mut write)?; + progress.written.fetch_add(1, Ordering::Relaxed); + let _ = proxy.send_event(UserEvent::Redraw); + } + } + site.finish(&mut write)?; + Ok::<_, Box>(()) + } + .await; + let cancelled = progress.cancelled.load(Ordering::Relaxed); + if cancelled || exported.is_err() { + remove_written(&written.borrow()); + } + let exported = exported.map_err(|error| crate::plain(&*error, "file")); + let _ = proxy.send_event(UserEvent::Then(Box::new(move |state| { + state.exporting = None; + state.ui.close_popup(exporting_id()); + match exported { + Ok(()) if !cancelled => { + // A replay leaves the file manager alone. + #[cfg(not(target_arch = "wasm32"))] + if !crate::automated() { + platform::show_file(&folder.join("index.html")); + } + } + Ok(()) => {} + Err(error) => { + platform::alert("Couldn't export the website", &error); + return Err(error.into()); + } + } + Ok(()) + }))); + }); + Ok(()) + }); + platform::pick_new("Export as Website", &name, "Export", None, reply); + Ok(()) + } + + /// Shows how far a website export has got while it runs; Cancel stops it. + pub(crate) fn exporting_dialog(&mut self) { + let Some(progress) = &self.exporting else { + return; + }; + let ui = &mut self.ui; + // Only Cancel stops an export: a press beside the dialog, which closes popups, or + // Escape leaves it running. + if !ui.popup_open(exporting_id()) { + ui.open_popup(exporting_id()); + } + let theme = ui.theme.clone(); + let (written, pages) = ( + progress.written.load(Ordering::Relaxed), + progress.pages.load(Ordering::Relaxed), + ); + ui.open_as( + exporting_id(), + Spec { + axis: Axis::Y, + size: [px(320.0), children()], + fill: Some(theme.popup), + border: Some(theme.chip), + shadow: Some(theme.shadow), + radius: 8.0, + pad: [16.0, 12.0], + gap: 8.0, + anchor: Some(Anchor::Dialog), + role: Some(Role::Dialog), + ..Spec::default() + }, + ); + if let Some(node) = ui.access(exporting_id()) { + node.set_label("Exporting Website"); + } + ui.leaf( + "title", + Spec { + size: [fill(), px(theme.font_size * 2.0)], + text: Some("Exporting Website"), + bold: true, + role: Some(Role::Heading), + ..Spec::default() + }, + ); + let status = match progress.listed.load(Ordering::Relaxed) { + false => "Listing pages…".to_owned(), + true => format!("Page {} of {pages}", (written + 1).min(pages.max(1))), + }; + ui.leaf( + "status", + Spec { + size: [fill(), px(theme.font_size * 1.5)], + text: Some(&status), + color: Some(theme.text_dim), + ..Spec::default() + }, + ); + let bar = ui.id("bar"); + ui.open_as( + bar, + Spec { + size: [fill(), px(6.0)], + fill: Some(theme.chip), + radius: 3.0, + role: Some(Role::ProgressIndicator), + ..Spec::default() + }, + ); + let fraction = written as f32 / pages.max(1) as f32; + let width = ui.laid_out(bar).map_or(0.0, |rect| rect[2] - rect[0]); + ui.mark([0.0, 0.0, width * fraction, 6.0], theme.accent, 3.0); + if let Some(node) = ui.access(bar) { + node.set_label("Export progress"); + node.set_min_numeric_value(0.0); + node.set_max_numeric_value(100.0); + node.set_numeric_value(f64::from((fraction * 100.0).round())); + } + ui.close(); + crate::buttons(ui); + let cancel = ui::button(ui, "cancel", "Cancel").clicked; + ui.close(); + ui.close(); + if cancel { + progress.cancelled.store(true, Ordering::Relaxed); + self.ui.close_popup(exporting_id()); + } + } +} + fn file_name(path: &std::path::Path) -> String { path.file_name() .map(|name| name.to_string_lossy().into_owned()) @@ -275,3 +699,63 @@ fn choose(ui: &mut ui::Ui, label: &str, names: &[&str], current: usize) -> Optio ui.close(); chosen } + +#[cfg(test)] +mod tests { + use super::*; + + /// A website never goes in a notebook, however the folder is reached, nor in a folder + /// holding files; a new folder, or an empty one, is fine. + #[test] + fn a_website_needs_a_folder_outside_every_notebook() { + let root = std::env::temp_dir().join(format!("snowbound-unfit-{}", std::process::id())); + let _ = notebook::fs::remove_dir_all(&root); + let notebook = root.join("Notebook"); + notebook::fs::create_dir_all(notebook.join("Group")).unwrap(); + notebook::fs::write(notebook.join("Open Notebook.onetoc2"), b"").unwrap(); + notebook::fs::create_dir_all(root.join("used")).unwrap(); + notebook::fs::write(root.join("used/kept.txt"), b"kept").unwrap(); + notebook::fs::create_dir_all(root.join("empty")).unwrap(); + #[cfg(unix)] + std::os::unix::fs::symlink(¬ebook, root.join("link")).unwrap(); + assert!(unfit(¬ebook.join("Site")).is_some()); + assert!(unfit(¬ebook.join("Group/New/Site")).is_some()); + #[cfg(unix)] + assert!(unfit(&root.join("link/Site")).is_some()); + assert!(unfit(&root.join("used")).is_some()); + assert!(unfit(&root.join("empty")).is_none()); + assert!(unfit(&root.join("new/Site")).is_none()); + notebook::fs::remove_dir_all(&root).unwrap(); + } + + /// Taking back an export removes what it wrote and the folders it made, and leaves + /// whatever else they or the folder chosen hold. + #[test] + fn taking_back_an_export_leaves_what_it_did_not_write() { + let root = std::env::temp_dir().join(format!("snowbound-taken-{}", std::process::id())); + let _ = notebook::fs::remove_dir_all(&root); + notebook::fs::create_dir_all(&root).unwrap(); + let written = [ + root.join("Section"), + root.join("Section/01 Page.html"), + root.join("files"), + root.join("files/a.png"), + root.join("index.html"), + ]; + for path in &written { + if path.extension().is_some() { + notebook::fs::write(path, b"").unwrap(); + } else { + notebook::fs::create_dir_all(path).unwrap(); + } + } + notebook::fs::write(root.join("files/added.txt"), b"added meanwhile").unwrap(); + remove_written(&written); + let left: Vec<_> = (notebook::fs::read_dir(&root).unwrap()) + .map(|entry| entry.unwrap().file_name()) + .collect(); + assert_eq!(left, ["files"]); + assert!(root.join("files/added.txt").is_file()); + notebook::fs::remove_dir_all(&root).unwrap(); + } +} diff --git a/crates/snowbound/tests/replay.rs b/crates/snowbound/tests/replay.rs index 7b031b97495a6405f8f700f49a43d9a6867ebb00..98d963dcdfd6e86605b5d77a942f441341c7e38e 100644 --- a/crates/snowbound/tests/replay.rs +++ b/crates/snowbound/tests/replay.rs @@ -1863,6 +1863,78 @@ fn escape_closes_save_as() { assert!(!closed.contains(r#"Dialog "Save As""#), "{closed}"); } +/// File > Export as Website through the palette, its Save As taken with Enter and its save +/// panel answered with `site`. +fn export_website(site: &Path) -> Vec { + [ + "modifiers shift command", + "key p", + "modifiers", + "settle", + "type Export as Website", + "settle", + "key Enter", + "settle", + "wait 300", + &format!("answer {}", site.display()), + "key Enter", + "settle", + "wait 500", + "settle", + "accessibility after", + ] + .map(str::to_owned) + .to_vec() +} + +/// Export as Website writes every section and page of the notebook into the folder chosen, +/// lists its password-protected sections as locked, and shows no dialog once done. +#[test] +fn a_notebook_exports_as_a_website() { + let scratch = Scratch::new("export-website"); + let notebook = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../corpus/protected-sections/candidate/notebook"); + let site = scratch.0.join("site"); + let steps = export_website(&site); + let steps: Vec<&str> = steps.iter().map(String::as_str).collect(); + let [after] = replay(&scratch, Some(¬ebook), &steps) + .try_into() + .unwrap(); + assert!(!after.contains("Exporting Website"), "{after}"); + let index = std::fs::read_to_string(site.join("index.html")).unwrap(); + for section in ["New Section 1", "Protected", "Removed", "Changed"] { + assert!( + index.contains(&format!(">{section}<")), + "{section} missing: {index}" + ); + } + assert_eq!( + index.matches("

    Locked

    ").count(), + 4, + "{index}" + ); + assert!(site.join("New Section 1/01 Gate.html").is_file()); + assert!(!site.join("Protected").exists()); +} + +/// A website never goes into a notebook's folder or a folder already holding files. +#[test] +fn a_website_needs_a_folder_of_its_own() { + let scratch = Scratch::new("export-website-guard"); + let notebook = + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/cross-container/candidate"); + let used = scratch.0.join("used"); + std::fs::create_dir_all(&used).unwrap(); + std::fs::write(used.join("keep.txt"), "kept").unwrap(); + let mut steps = export_website(&scratch.0.join("notebook").join("inside")); + steps.extend(export_website(&used)); + let steps: Vec<&str> = steps.iter().map(String::as_str).collect(); + replay(&scratch, Some(¬ebook), &steps); + assert!(!scratch.0.join("notebook/inside").exists()); + let kept: Vec<_> = std::fs::read_dir(&used).unwrap().collect(); + assert_eq!(kept.len(), 1); +} + /// A layout of panes as the settings keep it, on pages of `notebook`'s sections: a pane on /// the first, then a part below it, the second above the third. A page of `None` is gone. fn layout(notebook: &Path, panes: [(&str, Option<&str>); 3]) -> serde_json::Value {