| author | |
| committer | |
| log | b7ace116f7bb71058ff631dacd943b545238f439 |
| tree | d896dcf5718abbb4ec8ff2a4924e5828718fa5fe |
| parent | 36498b522852632e131ef7260a39d49cb9f34668 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
Save As offers Website (folder) for the page, the section and the notebook, where OneNote
2010 offers its Single File Web Page (.mht), and File > Export as Website opens it on the
notebook. canvas::site lists every page first from its metadata alone, so links between
pages are known, then reads, 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. Outline text is the HTML Copy writes, through a small extension point for alignment,
spacing, line heights and list numbers, with tags and list markers placed and tag colours
painted as the page does them; drawings are SVG of the strokes the page paints. 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. Pictures,
attachments, tag art and the Carlito stand-in for Calibri are copied beside the pages, so a
site needs no script and makes no request. The index nests section groups, sections and
pages; each page scrolls in its own pane beside its section's pages. A page exported on its
own is just that page, as index.html, without the header and page list.
The export runs on a layout engine of its own with each section open only while it is
read, shows how far it has got in a dialog only Cancel stops, and shows the finished
index in the file manager. A cancelled or failed export removes only what it wrote. It
writes only into a new or empty folder that no notebook holds, however the path reaches
it. Password-protected sections are listed as locked, unlocked here or not, and a
protected section or page is not exported on its own, as a website is for publishing.
Section folders that a file system would take for the same name, or refuse, get names of
their own.
- Save As can export a page, section or notebook as a website, and File > Export as Website exports the notebook.
- Exporting a single page as a website gives the page alone, without the notebook's header and page list.
- Links between pages of an exported website lead to the exported pages.
- Exporting a website shows its progress, can be cancelled, and shows the finished site.
- Website exports never write into a notebook or a folder already holding files.
- Website exports list password-protected sections as locked and leave out their pages.
Refs #77
Assisted-by: claude-opus-5.523 files changed, 2448 insertions(+), 51 deletions(-)
arc/canvas.md+15| ... | @@ -321,6 +321,21 @@ notebook), paper, orientation, fitting to the paper's width and the footer. Prin | ... | @@ -321,6 +321,21 @@ notebook), paper, orientation, fitting to the paper's width and the footer. Prin |
| 321 | the PDF to AppKit's print panel, the XDG print portal or the shell's print verb for PDFs. | 321 | the PDF to AppKit's print panel, the XDG print portal or the shell's print verb for PDFs. |
| 322 | On iOS the page menu prints the page through the print sheet or shares its PDF. | 322 | On iOS the page menu prints the page through the print sheet or shares its PDF. |
| 323 | 323 | ||
| 324 | ## Websites | ||
| 325 | |||
| 326 | `canvas::site` writes a notebook, section or page as a folder of web pages, which Save As | ||
| 327 | offers where OneNote 2010 offers its Single File Web Page, and Export as Website opens. It | ||
| 328 | lists every page first, so links between pages are known, then lays out and writes one page | ||
| 329 | at a time, as the view lays it out without an editor: every outline, picture, file and | ||
| 330 | drawing goes where the page puts it. An outline's text is the HTML Copy writes, within the | ||
| 331 | outline's laid-out width, its tags and list markers placed and its tag colours painted as the | ||
| 332 | page does them; drawings become SVG of the strokes the page paints. Pictures, files, tag art | ||
| 333 | and the Calibri stand-in are copied beside the pages, so a site needs no script and asks no | ||
| 334 | server for anything, and stored fonts and links pass the same checks as Copy's. Links to | ||
| 335 | pages, paragraphs and sections in the export lead to their files; links to the rest of the | ||
| 336 | notebook stay text. The index lists the section groups and sections, password-protected ones | ||
| 337 | as locked, and each page scrolls in its own pane beside its section's pages. | ||
| 338 | |||
| 324 | ## Search, dates, conflicts | 339 | ## Search, dates, conflicts |
| 325 | 340 | ||
| 326 | Smaller modules follow the same pattern of reproducing OneNote's behaviour | 341 | Smaller modules follow the same pattern of reproducing OneNote's behaviour |
crates/canvas/Cargo.toml+4| ... | @@ -55,6 +55,10 @@ required-features = ["gpu"] | ... | @@ -55,6 +55,10 @@ required-features = ["gpu"] |
| 55 | name = "reading_inventory" | 55 | name = "reading_inventory" |
| 56 | required-features = ["gpu"] | 56 | required-features = ["gpu"] |
| 57 | 57 | ||
| 58 | [[example]] | ||
| 59 | name = "export_site" | ||
| 60 | required-features = ["interaction"] | ||
| 61 | |||
| 58 | [[example]] | 62 | [[example]] |
| 59 | name = "print_pdf" | 63 | name = "print_pdf" |
| 60 | required-features = ["pdf"] | 64 | required-features = ["pdf"] |
crates/canvas/assets/site.css created+59| ... | @@ -0,0 +1,59 @@ | ||
| 1 | body { margin: 0; background: #fff; color: #000; } | ||
| 2 | /* As OneNote's window: the page scrolls both ways in its own pane, the page list beside it. */ | ||
| 3 | body:has(> .view) { display: grid; grid-template-rows: auto minmax(0, 1fr); height: 100vh; } | ||
| 4 | header, nav, .index { font: 13px/1.4 system-ui, -apple-system, "Segoe UI", sans-serif; } | ||
| 5 | a { color: #0563c1; } | ||
| 6 | |||
| 7 | header { padding: 8px 16px; background: #f3f3f3; border-bottom: 1px solid #d6d6d6; } | ||
| 8 | header a { color: inherit; font-weight: 600; text-decoration: none; } | ||
| 9 | header a:hover { text-decoration: underline; } | ||
| 10 | |||
| 11 | .view { display: grid; grid-template-columns: minmax(0, 1fr) 220px; min-height: 0; } | ||
| 12 | .page { position: relative; overflow: auto; font: 11pt Calibri, Carlito, sans-serif; } | ||
| 13 | .sheet { position: absolute; top: 0; min-width: 100%; min-height: 100%; background: inherit; } | ||
| 14 | .sheet > * { position: absolute; margin: 0; } | ||
| 15 | .rules { right: 0; bottom: 0; pointer-events: none; } | ||
| 16 | /* A page exported alone fills the window and scrolls with it. */ | ||
| 17 | body > .page { overflow: visible; min-height: 100vh; } | ||
| 18 | .outline p, .outline li { position: relative; } | ||
| 19 | .outline table { border-collapse: collapse; } | ||
| 20 | /* OneNote's own web pages pad cells so; its column widths leave room for no more. */ | ||
| 21 | .outline td { padding: 2pt 3pt !important; } | ||
| 22 | /* The page's own markers stand in; the lists keep theirs for assistive technology. */ | ||
| 23 | .outline ul, .outline ol { padding-left: 0; } | ||
| 24 | .outline li::marker { color: transparent; } | ||
| 25 | .tag, .marker { position: absolute; white-space: pre; } | ||
| 26 | .tag img { position: absolute; inset: 0; width: 100%; height: 100%; } | ||
| 27 | .picture { display: block; } | ||
| 28 | .ink { display: block; overflow: visible; } | ||
| 29 | .file { display: inline-flex; flex-direction: column; align-items: center; width: 54pt; color: inherit; | ||
| 30 | text-decoration: none; font: 11pt Arial, sans-serif; text-align: center; overflow-wrap: anywhere; } | ||
| 31 | .file span { margin-top: 6pt; } | ||
| 32 | .missing { display: flex; align-items: center; justify-content: center; box-sizing: border-box; | ||
| 33 | border: 1px dashed #b4b4b4; color: #7a7a7a; font: 9pt system-ui, sans-serif; } | ||
| 34 | .failed { margin: 36pt; color: #7a7a7a; } | ||
| 35 | |||
| 36 | nav.pages { background: #f7f7f7; border-left: 1px solid #d6d6d6; padding: 8px 0; overflow-y: auto; } | ||
| 37 | nav ul, .index ul { list-style: none; margin: 0; padding: 0; } | ||
| 38 | nav ul ul { padding-left: 14px; } | ||
| 39 | nav a { display: block; padding: 3px 12px; color: inherit; text-decoration: none; | ||
| 40 | overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } | ||
| 41 | nav a:hover { background: #e8e8e8; } | ||
| 42 | nav a[aria-current] { background: #fff; font-weight: 600; box-shadow: inset 3px 0 #7a5fb8; } | ||
| 43 | |||
| 44 | .index { max-width: 720px; margin: 0 auto; padding: 24px 16px 48px; } | ||
| 45 | .index h1 { font-size: 24px; font-weight: 600; } | ||
| 46 | .index h2 { font-size: 15px; font-weight: 600; margin: 20px 0 6px; color: #555; } | ||
| 47 | .index h3 { font-size: 15px; font-weight: 600; margin: 16px 0 4px; padding-left: 8px; | ||
| 48 | border-left: 5px solid #c8c8c8; } | ||
| 49 | .index .group > ul { padding-left: 16px; } | ||
| 50 | .index li li { padding-left: 13px; } | ||
| 51 | .index li a { display: inline-block; padding: 2px 0; } | ||
| 52 | .index .locked { margin: 0 0 0 13px; color: #7a7a7a; } | ||
| 53 | |||
| 54 | @media print { | ||
| 55 | body:has(> .view) { display: block; height: auto; } | ||
| 56 | header, nav.pages { display: none; } | ||
| 57 | .view { display: block; } | ||
| 58 | .page { overflow: visible; } | ||
| 59 | } | ||
crates/canvas/examples/export_site.rs created+60| ... | @@ -0,0 +1,60 @@ | ||
| 1 | //! Writes sections as the website Export as Website makes, each section under the folders | ||
| 2 | //! its path names below `ROOT`. `export_site NEW-FOLDER ROOT SECTION.one...` | ||
| 3 | |||
| 4 | use canvas::{layout::TextEngine, site}; | ||
| 5 | use onestore::{Arena, Section}; | ||
| 6 | use std::{env, fs, path::Path}; | ||
| 7 | |||
| 8 | fn main() -> Result<(), Box<dyn std::error::Error>> { | ||
| 9 | let args: Vec<String> = env::args().skip(1).collect(); | ||
| 10 | let [destination, root, sections @ ..] = args.as_slice() else { | ||
| 11 | return Err("Expected a new folder, a root and sections".into()); | ||
| 12 | }; | ||
| 13 | let mut listed = Vec::new(); | ||
| 14 | let mut read = Vec::new(); | ||
| 15 | for path in sections { | ||
| 16 | let arena = Arena::default(); | ||
| 17 | let bytes = fs::read(path)?; | ||
| 18 | let identity = onestore::Header::parse(bytes.get(..1024).ok_or("Too short")?)?.file_id; | ||
| 19 | let mut section = Section::open(&arena, bytes)?; | ||
| 20 | let (mut listings, mut pages) = (Vec::new(), Vec::new()); | ||
| 21 | for (space, title, level) in section.pages()? { | ||
| 22 | let page = section.page(space)?; | ||
| 23 | listings.push(site::Listing { | ||
| 24 | title, | ||
| 25 | level, | ||
| 26 | identity: page.identity, | ||
| 27 | }); | ||
| 28 | pages.push(page); | ||
| 29 | } | ||
| 30 | let relative = Path::new(path).strip_prefix(root)?; | ||
| 31 | let groups = (relative.parent().into_iter()) | ||
| 32 | .flat_map(|parent| parent.iter()) | ||
| 33 | .map(|group| group.to_string_lossy().into_owned()) | ||
| 34 | .collect(); | ||
| 35 | let name = relative.file_stem().unwrap_or_default().to_string_lossy(); | ||
| 36 | listed.push(site::Section { | ||
| 37 | groups, | ||
| 38 | name: name.into_owned(), | ||
| 39 | color: None, | ||
| 40 | identity: Some(identity), | ||
| 41 | pages: Some(listings), | ||
| 42 | }); | ||
| 43 | read.push(pages); | ||
| 44 | } | ||
| 45 | let destination = Path::new(destination); | ||
| 46 | let mut write = |name: &str, bytes: &[u8]| { | ||
| 47 | let path = destination.join(name); | ||
| 48 | fs::create_dir_all(path.parent().unwrap_or(destination))?; | ||
| 49 | fs::write(path, bytes) | ||
| 50 | }; | ||
| 51 | let mut site = site::Site::new("Corpus", listed); | ||
| 52 | let mut engine = TextEngine::default(); | ||
| 53 | for (section, pages) in read.into_iter().enumerate() { | ||
| 54 | for (at, page) in pages.into_iter().enumerate() { | ||
| 55 | site.page([section, at], page, &mut engine, &mut write)?; | ||
| 56 | } | ||
| 57 | } | ||
| 58 | site.finish(&mut write)?; | ||
| 59 | Ok(()) | ||
| 60 | } | ||
crates/canvas/src/editor.rs+1-1| ... | @@ -29,7 +29,7 @@ mod equation; | ... | @@ -29,7 +29,7 @@ mod equation; |
| 29 | #[cfg(test)] | 29 | #[cfg(test)] |
| 30 | mod evidence; | 30 | mod evidence; |
| 31 | mod format; | 31 | mod format; |
| 32 | mod html; | 32 | pub(crate) mod html; |
| 33 | mod ink; | 33 | mod ink; |
| 34 | mod link; | 34 | mod link; |
| 35 | mod markdown; | 35 | mod markdown; |
crates/canvas/src/editor/html.rs+54-13| ... | @@ -23,7 +23,7 @@ impl Clip { | ... | @@ -23,7 +23,7 @@ impl Clip { |
| 23 | /// The clip as a web page whose fragment the comments OneNote's mark out hold. | 23 | /// The clip as a web page whose fragment the comments OneNote's mark out hold. |
| 24 | pub fn html(&self) -> String { | 24 | pub fn html(&self) -> String { |
| 25 | let mut body = String::new(); | 25 | let mut body = String::new(); |
| 26 | blocks(&self.paragraphs, &self.definitions, &mut body); | 26 | blocks(&self.paragraphs, &self.definitions, &mut (), &mut body); |
| 27 | format!( | 27 | format!( |
| 28 | "<html>\n<head>\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\n\ | 28 | "<html>\n<head>\n<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">\n\ |
| 29 | <meta name=Generator content=\"Snowbound\">\n</head>\n<body>\n\ | 29 | <meta name=Generator content=\"Snowbound\">\n</head>\n<body>\n\ |
| ... | @@ -32,10 +32,39 @@ impl Clip { | ... | @@ -32,10 +32,39 @@ impl Clip { |
| 32 | } | 32 | } |
| 33 | } | 33 | } |
| 34 | 34 | ||
| 35 | /// What a writer of whole pages adds to the blocks the clipboard writes. | ||
| 36 | pub(crate) trait Extras { | ||
| 37 | /// CSS added to text paragraph `node`'s own, each declaration led by `;`. | ||
| 38 | fn style(&mut self, _node: &PageParagraph) -> String { | ||
| 39 | String::new() | ||
| 40 | } | ||
| 41 | |||
| 42 | /// Attributes added to text paragraph `node`'s element, each led by a space. | ||
| 43 | fn attributes(&mut self, _node: &PageParagraph) -> String { | ||
| 44 | String::new() | ||
| 45 | } | ||
| 46 | |||
| 47 | /// What starts text paragraph `node`, inside its element, or stands for a picture, file or | ||
| 48 | /// drawing, which the clipboard leaves out. | ||
| 49 | fn content(&mut self, _node: &PageParagraph, _out: &mut String) {} | ||
| 50 | |||
| 51 | /// Where a link to stored `target` leads; none for one that stays text. | ||
| 52 | fn link(&mut self, target: &str) -> Option<String> { | ||
| 53 | linkable(target) | ||
| 54 | } | ||
| 55 | } | ||
| 56 | |||
| 57 | impl Extras for () {} | ||
| 58 | |||
| 35 | /// `nodes` as blocks: a list opens at a paragraph whose list differs from the one open at | 59 | /// `nodes` as blocks: a list opens at a paragraph whose list differs from the one open at |
| 36 | /// its level, and a block's left margin steps it in from the list it sits in, which OneNote | 60 | /// its level, and a block's left margin steps it in from the list it sits in, which OneNote |
| 37 | /// and Word take its level from. | 61 | /// and Word take its level from. |
| 38 | fn blocks(nodes: &[PageParagraph], definitions: &BTreeMap<ExGuid, Definition>, out: &mut String) { | 62 | pub(crate) fn blocks( |
| 63 | nodes: &[PageParagraph], | ||
| 64 | definitions: &BTreeMap<ExGuid, Definition>, | ||
| 65 | extras: &mut dyn Extras, | ||
| 66 | out: &mut String, | ||
| 67 | ) { | ||
| 39 | let mut open: Vec<(u32, &str)> = Vec::new(); | 68 | let mut open: Vec<(u32, &str)> = Vec::new(); |
| 40 | for node in nodes { | 69 | for node in nodes { |
| 41 | let list = node | 70 | let list = node |
| ... | @@ -61,13 +90,25 @@ fn blocks(nodes: &[PageParagraph], definitions: &BTreeMap<ExGuid, Definition>, o | ... | @@ -61,13 +90,25 @@ fn blocks(nodes: &[PageParagraph], definitions: &BTreeMap<ExGuid, Definition>, o |
| 61 | ); | 90 | ); |
| 62 | open.push((node.level, tag)); | 91 | open.push((node.level, tag)); |
| 63 | } | 92 | } |
| 64 | out.push_str("<li style='margin-top:0;margin-bottom:0'>"); | 93 | let _ = write!( |
| 65 | runs(&text.text, out); | 94 | out, |
| 95 | "<li style='margin-top:0;margin-bottom:0{}'{}>", | ||
| 96 | extras.style(node), | ||
| 97 | extras.attributes(node) | ||
| 98 | ); | ||
| 99 | extras.content(node, out); | ||
| 100 | runs(&text.text, extras, out); | ||
| 66 | out.push_str("</li>\n"); | 101 | out.push_str("</li>\n"); |
| 67 | } | 102 | } |
| 68 | (_, ParagraphContent::Text(text)) => { | 103 | (_, ParagraphContent::Text(text)) => { |
| 69 | let _ = write!(out, "<p style='margin:0in;margin-left:{indent}in'>"); | 104 | let _ = write!( |
| 70 | runs(&text.text, out); | 105 | out, |
| 106 | "<p style='margin:0in;margin-left:{indent}in{}'{}>", | ||
| 107 | extras.style(node), | ||
| 108 | extras.attributes(node) | ||
| 109 | ); | ||
| 110 | extras.content(node, out); | ||
| 111 | runs(&text.text, extras, out); | ||
| 71 | out.push_str("</p>\n"); | 112 | out.push_str("</p>\n"); |
| 72 | } | 113 | } |
| 73 | (_, ParagraphContent::Table(table)) => { | 114 | (_, ParagraphContent::Table(table)) => { |
| ... | @@ -84,14 +125,14 @@ fn blocks(nodes: &[PageParagraph], definitions: &BTreeMap<ExGuid, Definition>, o | ... | @@ -84,14 +125,14 @@ fn blocks(nodes: &[PageParagraph], definitions: &BTreeMap<ExGuid, Definition>, o |
| 84 | vertical-align:top;width:{}pt;padding:4pt 4pt 4pt 4pt'>", | 125 | vertical-align:top;width:{}pt;padding:4pt 4pt 4pt 4pt'>", |
| 85 | column.width | 126 | column.width |
| 86 | ); | 127 | ); |
| 87 | blocks(&cell.paragraphs, definitions, out); | 128 | blocks(&cell.paragraphs, definitions, extras, out); |
| 88 | out.push_str("</td>\n"); | 129 | out.push_str("</td>\n"); |
| 89 | } | 130 | } |
| 90 | out.push_str("</tr>\n"); | 131 | out.push_str("</tr>\n"); |
| 91 | } | 132 | } |
| 92 | out.push_str("</table>\n"); | 133 | out.push_str("</table>\n"); |
| 93 | } | 134 | } |
| 94 | _ => {} | 135 | _ => extras.content(node, out), |
| 95 | } | 136 | } |
| 96 | } | 137 | } |
| 97 | for (_, tag) in open.into_iter().rev() { | 138 | for (_, tag) in open.into_iter().rev() { |
| ... | @@ -126,7 +167,7 @@ pub(super) fn list_tag(kind: &Kind) -> (&'static str, &'static str) { | ... | @@ -126,7 +167,7 @@ pub(super) fn list_tag(kind: &Kind) -> (&'static str, &'static str) { |
| 126 | } | 167 | } |
| 127 | 168 | ||
| 128 | /// A paragraph's shown runs as spans, its links' around theirs. | 169 | /// A paragraph's shown runs as spans, its links' around theirs. |
| 129 | fn runs(text: &Paragraph, out: &mut String) { | 170 | fn runs(text: &Paragraph, extras: &mut dyn Extras, out: &mut String) { |
| 130 | let links = links(text, 0); | 171 | let links = links(text, 0); |
| 131 | let (mut byte, mut unit) = (0, 0); | 172 | let (mut byte, mut unit) = (0, 0); |
| 132 | let mut shown = false; | 173 | let mut shown = false; |
| ... | @@ -141,7 +182,7 @@ fn runs(text: &Paragraph, out: &mut String) { | ... | @@ -141,7 +182,7 @@ fn runs(text: &Paragraph, out: &mut String) { |
| 141 | shown = true; | 182 | shown = true; |
| 142 | let link = (links.iter()) | 183 | let link = (links.iter()) |
| 143 | .find(|link| link.label.contains(&start)) | 184 | .find(|link| link.label.contains(&start)) |
| 144 | .and_then(|link| linkable(&link.target)); | 185 | .and_then(|link| extras.link(&link.target)); |
| 145 | if let Some(target) = &link { | 186 | if let Some(target) = &link { |
| 146 | let _ = write!(out, "<a href=\"{}\">", escape(target, &mut false)); | 187 | let _ = write!(out, "<a href=\"{}\">", escape(target, &mut false)); |
| 147 | } | 188 | } |
| ... | @@ -163,7 +204,7 @@ fn runs(text: &Paragraph, out: &mut String) { | ... | @@ -163,7 +204,7 @@ fn runs(text: &Paragraph, out: &mut String) { |
| 163 | /// A stored link target as HTML may link it: a web or mail address, a link within the | 204 | /// A stored link target as HTML may link it: a web or mail address, a link within the |
| 164 | /// notebook, or a relative path, without the white space and controls browsers ignore in one. | 205 | /// notebook, or a relative path, without the white space and controls browsers ignore in one. |
| 165 | /// None for anything else, such as a script, which stays text. | 206 | /// None for anything else, such as a script, which stays text. |
| 166 | fn linkable(target: &str) -> Option<String> { | 207 | pub(crate) fn linkable(target: &str) -> Option<String> { |
| 167 | let target: String = (target.trim_matches(|c: char| c <= ' ').chars()) | 208 | let target: String = (target.trim_matches(|c: char| c <= ' ').chars()) |
| 168 | .filter(|c| !matches!(c, '\t' | '\n' | '\r')) | 209 | .filter(|c| !matches!(c, '\t' | '\n' | '\r')) |
| 169 | .collect(); | 210 | .collect(); |
| ... | @@ -183,7 +224,7 @@ fn linkable(target: &str) -> Option<String> { | ... | @@ -183,7 +224,7 @@ fn linkable(target: &str) -> Option<String> { |
| 183 | 224 | ||
| 184 | /// A font name CSS can hold as it is: letters, digits, spaces and `-`, `_` and `.`; none for | 225 | /// A font name CSS can hold as it is: letters, digits, spaces and `-`, `_` and `.`; none for |
| 185 | /// another, which might break out of the style it is put in. | 226 | /// another, which might break out of the style it is put in. |
| 186 | fn font_name(font: &str) -> Option<&str> { | 227 | pub(crate) fn font_name(font: &str) -> Option<&str> { |
| 187 | (!font.is_empty() | 228 | (!font.is_empty() |
| 188 | && font | 229 | && font |
| 189 | .chars() | 230 | .chars() |
| ... | @@ -248,7 +289,7 @@ fn css(format: &Format) -> String { | ... | @@ -248,7 +289,7 @@ fn css(format: &Format) -> String { |
| 248 | /// Text as HTML keeps it, in an element or a quoted attribute: markup characters and quotes | 289 | /// Text as HTML keeps it, in an element or a quoted attribute: markup characters and quotes |
| 249 | /// escaped, line breaks as `br`, and a space after `space`, whether the text follows a space | 290 | /// escaped, line breaks as `br`, and a space after `space`, whether the text follows a space |
| 250 | /// or starts its paragraph, unbreakable so it doesn't collapse. | 291 | /// or starts its paragraph, unbreakable so it doesn't collapse. |
| 251 | fn escape(text: &str, space: &mut bool) -> String { | 292 | pub(crate) fn escape(text: &str, space: &mut bool) -> String { |
| 252 | let mut escaped = String::with_capacity(text.len()); | 293 | let mut escaped = String::with_capacity(text.len()); |
| 253 | for c in text.chars() { | 294 | for c in text.chars() { |
| 254 | match c { | 295 | match c { |
crates/canvas/src/interaction/mod.rs+5-3| ... | @@ -2810,9 +2810,9 @@ pub(crate) fn rule_primitives( | ... | @@ -2810,9 +2810,9 @@ pub(crate) fn rule_primitives( |
| 2810 | let Some(lines) = lines else { | 2810 | let Some(lines) = lines else { |
| 2811 | return Vec::new(); | 2811 | return Vec::new(); |
| 2812 | }; | 2812 | }; |
| 2813 | let width = pixel.max(0.75); | 2813 | let width = pixel.max(crate::RULE_WIDTH); |
| 2814 | // Stored spacings are in half inches; nothing draws closer than a device pixel apart. | 2814 | // Stored spacings are in half inches; nothing draws closer than a device pixel apart. |
| 2815 | let step = |spacing: f32| (spacing * 36.0).max(pixel); | 2815 | let step = |spacing: f32| (spacing * crate::HALF_INCH).max(pixel); |
| 2816 | let color = |color| paper.tint(crate::gpu::colorref(color)); | 2816 | let color = |color| paper.tint(crate::gpu::colorref(color)); |
| 2817 | let horizontal = step(lines.spacing); | 2817 | let horizontal = step(lines.spacing); |
| 2818 | let first = ((top - y) / horizontal).ceil().max(0.0); | 2818 | let first = ((top - y) / horizontal).ceil().max(0.0); |
| ... | @@ -2829,7 +2829,9 @@ pub(crate) fn rule_primitives( | ... | @@ -2829,7 +2829,9 @@ pub(crate) fn rule_primitives( |
| 2829 | color: color(rule_color), | 2829 | color: color(rule_color), |
| 2830 | }; | 2830 | }; |
| 2831 | match lines.vertical { | 2831 | match lines.vertical { |
| 2832 | VerticalRule::Margin(rule_color) => primitives.push(vertical(x - 0.75, rule_color)), | 2832 | VerticalRule::Margin(rule_color) => { |
| 2833 | primitives.push(vertical(x - crate::MARGIN_RULE, rule_color)) | ||
| 2834 | } | ||
| 2833 | VerticalRule::Grid { spacing, color } => { | 2835 | VerticalRule::Grid { spacing, color } => { |
| 2834 | let spacing = step(spacing); | 2836 | let spacing = step(spacing); |
| 2835 | let first = ((left - x) / spacing).floor(); | 2837 | let first = ((left - x) / spacing).floor(); |
crates/canvas/src/layout.rs+20-12| ... | @@ -118,10 +118,27 @@ pub(crate) const DEFAULT_FONT_SIZE: f32 = 11.0; | ... | @@ -118,10 +118,27 @@ pub(crate) const DEFAULT_FONT_SIZE: f32 = 11.0; |
| 118 | /// which fetches them beside it instead (`register_substitute`). | 118 | /// which fetches them beside it instead (`register_substitute`). |
| 119 | const BUNDLED: &[(&str, &[&[u8]])] = include!(concat!(env!("OUT_DIR"), "/bundled.rs")); | 119 | const BUNDLED: &[(&str, &[&[u8]])] = include!(concat!(env!("OUT_DIR"), "/bundled.rs")); |
| 120 | 120 | ||
| 121 | /// Each bundled family's faces, inflated the first time an engine lacks the family. | 121 | /// Each bundled family's faces, inflated the first time they are asked for. |
| 122 | static INFLATED: [OnceLock<Vec<Blob<u8>>>; BUNDLED.len()] = | 122 | static INFLATED: [OnceLock<Vec<Blob<u8>>>; BUNDLED.len()] = |
| 123 | [const { OnceLock::new() }; BUNDLED.len()]; | 123 | [const { OnceLock::new() }; BUNDLED.len()]; |
| 124 | 124 | ||
| 125 | /// The bundled faces standing in for `family`, inflated the first time they are asked for; | ||
| 126 | /// none where the build left the family out. | ||
| 127 | pub(crate) fn bundled(family: &str) -> Option<&'static [Blob<u8>]> { | ||
| 128 | let at = BUNDLED.iter().position(|(bundled, _)| *bundled == family)?; | ||
| 129 | let faces = INFLATED[at].get_or_init(|| { | ||
| 130 | BUNDLED[at] | ||
| 131 | .1 | ||
| 132 | .iter() | ||
| 133 | .map(|face| { | ||
| 134 | let face = miniz_oxide::inflate::decompress_to_vec(face); | ||
| 135 | Blob::new(Arc::new(face.expect("bundled substitutes inflate"))) | ||
| 136 | }) | ||
| 137 | .collect() | ||
| 138 | }); | ||
| 139 | Some(faces) | ||
| 140 | } | ||
| 141 | |||
| 125 | impl Default for TextEngine { | 142 | impl Default for TextEngine { |
| 126 | /// An engine that lays out each bundled family in its substitute where it is missing. | 143 | /// An engine that lays out each bundled family in its substitute where it is missing. |
| 127 | fn default() -> Self { | 144 | fn default() -> Self { |
| ... | @@ -135,20 +152,11 @@ impl Default for TextEngine { | ... | @@ -135,20 +152,11 @@ impl Default for TextEngine { |
| 135 | arial_substitutes: BTreeSet::new(), | 152 | arial_substitutes: BTreeSet::new(), |
| 136 | substitutes: BTreeMap::new(), | 153 | substitutes: BTreeMap::new(), |
| 137 | }; | 154 | }; |
| 138 | for (&(family, faces), inflated) in BUNDLED.iter().zip(&INFLATED) { | 155 | for (family, _) in BUNDLED { |
| 139 | if engine.fonts.collection.family_id(family).is_some() { | 156 | if engine.fonts.collection.family_id(family).is_some() { |
| 140 | continue; | 157 | continue; |
| 141 | } | 158 | } |
| 142 | let faces = inflated.get_or_init(|| { | 159 | for face in bundled(family).into_iter().flatten() { |
| 143 | faces | ||
| 144 | .iter() | ||
| 145 | .map(|face| { | ||
| 146 | let face = miniz_oxide::inflate::decompress_to_vec(face); | ||
| 147 | Blob::new(Arc::new(face.expect("bundled substitutes inflate"))) | ||
| 148 | }) | ||
| 149 | .collect() | ||
| 150 | }); | ||
| 151 | for face in faces { | ||
| 152 | engine | 160 | engine |
| 153 | .register(face.clone(), true) | 161 | .register(face.clone(), true) |
| 154 | .expect("bundled substitutes register"); | 162 | .expect("bundled substitutes register"); |
crates/canvas/src/lib.rs+9| ... | @@ -19,6 +19,15 @@ pub mod interaction; | ... | @@ -19,6 +19,15 @@ pub mod interaction; |
| 19 | pub mod print; | 19 | pub mod print; |
| 20 | #[cfg(feature = "gpu")] | 20 | #[cfg(feature = "gpu")] |
| 21 | pub mod recording; | 21 | pub mod recording; |
| 22 | #[cfg(feature = "gpu")] | ||
| 23 | pub mod site; | ||
| 24 | |||
| 25 | /// Points in the half inch rule line spacings are stored in. | ||
| 26 | pub(crate) const HALF_INCH: f32 = 36.0; | ||
| 27 | /// How thick rule lines draw at the least, in points. | ||
| 28 | pub(crate) const RULE_WIDTH: f32 = 0.75; | ||
| 29 | /// How far left of the margin origin a page's margin rule runs, in points. | ||
| 30 | pub(crate) const MARGIN_RULE: f32 = 0.75; | ||
| 22 | 31 | ||
| 23 | /// Where an object stored with `layout` lies; an unset coordinate is zero. | 32 | /// Where an object stored with `layout` lies; an unset coordinate is zero. |
| 24 | pub(crate) fn origin(layout: &onestore::document::Layout) -> [f32; 2] { | 33 | pub(crate) fn origin(layout: &onestore::document::Layout) -> [f32; 2] { |
crates/canvas/src/outline.rs+3| ... | @@ -297,6 +297,8 @@ pub struct ParagraphLayout { | ... | @@ -297,6 +297,8 @@ pub struct ParagraphLayout { |
| 297 | /// A highlight of the whole paragraph (its own `highlight`), COLORREF: a band across its | 297 | /// A highlight of the whole paragraph (its own `highlight`), COLORREF: a band across its |
| 298 | /// outline behind its lines, as OneNote marks a conflict page's conflicting changes. | 298 | /// outline behind its lines, as OneNote marks a conflict page's conflicting changes. |
| 299 | pub(crate) band: Option<u32>, | 299 | pub(crate) band: Option<u32>, |
| 300 | /// The font colour and highlight its tags give every run, COLORREF. | ||
| 301 | pub(crate) tag_paint: [Option<u32>; 2], | ||
| 300 | } | 302 | } |
| 301 | 303 | ||
| 302 | /// How the page draws a note tag. | 304 | /// How the page draws a note tag. |
| ... | @@ -1218,6 +1220,7 @@ impl ParagraphLayout { | ... | @@ -1218,6 +1220,7 @@ impl ParagraphLayout { |
| 1218 | math, | 1220 | math, |
| 1219 | parent: paragraph.parent, | 1221 | parent: paragraph.parent, |
| 1220 | band: paragraph.format.highlight, | 1222 | band: paragraph.format.highlight, |
| 1223 | tag_paint: [color, highlight], | ||
| 1221 | }; | 1224 | }; |
| 1222 | result.place_tags(result.marker_left()); | 1225 | result.place_tags(result.marker_left()); |
| 1223 | Ok(result) | 1226 | Ok(result) |
crates/canvas/src/site.rs created+1554| ... | @@ -0,0 +1,1554 @@ | ||
| 1 | //! A notebook as a static website: an index listing its section groups, sections and pages, | ||
| 2 | //! and each page as OneNote's view lays it out, its outlines, pictures, files and drawings | ||
| 3 | //! placed where they lie on the page. Text is HTML the browser wraps, written as Copy writes it, | ||
| 4 | //! within each outline's laid-out width. Pictures and attached files are copied beside the | ||
| 5 | //! pages, drawings become SVG, and nothing written runs a script or asks a server for anything. | ||
| 6 | |||
| 7 | use crate::editor::html::{Extras, blocks, escape, font_name, linkable}; | ||
| 8 | use crate::editor::page::{Content, build, ink_bounds}; | ||
| 9 | use crate::gpu::{colorref, page::append_ink, tag_sources}; | ||
| 10 | use crate::layout::TextEngine; | ||
| 11 | use crate::outline::{OutlineLayout, ParagraphLayout, ParagraphTag, TagIcon}; | ||
| 12 | use draw::Primitive; | ||
| 13 | use onestore::{ | ||
| 14 | ExGuid, | ||
| 15 | page::{Attachment, Definition, Image, Ink, Page, PageObject, PageParagraph, ParagraphContent}, | ||
| 16 | }; | ||
| 17 | use sha2::{Digest, Sha256}; | ||
| 18 | use std::{ | ||
| 19 | collections::{BTreeMap, BTreeSet}, | ||
| 20 | fmt::Write as _, | ||
| 21 | io, | ||
| 22 | }; | ||
| 23 | |||
| 24 | /// A section as the site lists it, before its pages are read. | ||
| 25 | pub struct Section { | ||
| 26 | /// The section groups holding it, outermost first. | ||
| 27 | pub groups: Vec<String>, | ||
| 28 | pub name: String, | ||
| 29 | /// COLORREF. | ||
| 30 | pub color: Option<u32>, | ||
| 31 | /// Its file identity, which links into it name. | ||
| 32 | pub identity: Option<[u8; 16]>, | ||
| 33 | /// Its pages in order; none for a section the site lists as locked. | ||
| 34 | pub pages: Option<Vec<Listing>>, | ||
| 35 | } | ||
| 36 | |||
| 37 | /// A page as its section lists it. | ||
| 38 | pub struct Listing { | ||
| 39 | pub title: String, | ||
| 40 | /// 1 for a page, more for its subpages. | ||
| 41 | pub level: u32, | ||
| 42 | /// What links to the page name it by. | ||
| 43 | pub identity: Option<[u8; 16]>, | ||
| 44 | } | ||
| 45 | |||
| 46 | /// Room left past the page's content, as OneNote's view leaves it. | ||
| 47 | const MARGIN: f32 = 36.0; | ||
| 48 | |||
| 49 | const STYLE: &str = include_str!("../assets/site.css"); | ||
| 50 | |||
| 51 | /// The icon of a file stored without one. | ||
| 52 | const BLANK_FILE: &str = "files/file.png"; | ||
| 53 | |||
| 54 | /// A website being written: the notebook's pages, written one at a time with `page`, then the | ||
| 55 | /// index and stylesheet with `finish`. Every write goes through a `write` that takes | ||
| 56 | /// a path relative to the site's folder and the bytes to put there. | ||
| 57 | pub struct Site { | ||
| 58 | notebook: String, | ||
| 59 | sections: Vec<Section>, | ||
| 60 | /// Each section's folder and its pages' files. | ||
| 61 | listed: Vec<(String, Vec<Listed>)>, | ||
| 62 | links: Links, | ||
| 63 | written: BTreeSet<String>, | ||
| 64 | calibri: bool, | ||
| 65 | /// The language of the first page written that names one, the index's. | ||
| 66 | lang: Option<&'static str>, | ||
| 67 | /// Whether the site is one page alone, without the notebook around it. | ||
| 68 | alone: bool, | ||
| 69 | } | ||
| 70 | |||
| 71 | impl Site { | ||
| 72 | /// The site of `sections` of `notebook`, each given a folder of its own and each page a | ||
| 73 | /// file, so that links between them are known before any is written. | ||
| 74 | pub fn new(notebook: &str, sections: Vec<Section>) -> Self { | ||
| 75 | Self::build(notebook, sections, false) | ||
| 76 | } | ||
| 77 | |||
| 78 | /// The site of `section`'s one page alone: the page as `index.html`, without the notebook's | ||
| 79 | /// header and page list around it. | ||
| 80 | pub fn page_alone(notebook: &str, section: Section) -> Self { | ||
| 81 | Self::build(notebook, vec![section], true) | ||
| 82 | } | ||
| 83 | |||
| 84 | fn build(notebook: &str, sections: Vec<Section>, alone: bool) -> Self { | ||
| 85 | let mut taken = BTreeSet::new(); | ||
| 86 | let mut links = Links::default(); | ||
| 87 | let listed = (sections.iter()) | ||
| 88 | .map(|section| { | ||
| 89 | let folder = folder(section, &mut taken); | ||
| 90 | let pages: Vec<Listed> = (section.pages.iter().flatten().enumerate()) | ||
| 91 | .map(|(at, page)| { | ||
| 92 | let title = shown_title(&page.title); | ||
| 93 | Listed { | ||
| 94 | href: match alone { | ||
| 95 | true => "index.html".to_owned(), | ||
| 96 | false => { | ||
| 97 | format!("{folder}/{:02} {}.html", at + 1, component(&title)) | ||
| 98 | } | ||
| 99 | }, | ||
| 100 | title, | ||
| 101 | level: page.level, | ||
| 102 | } | ||
| 103 | }) | ||
| 104 | .collect(); | ||
| 105 | if let (Some(identity), Some(first)) = (section.identity, pages.first()) { | ||
| 106 | links.sections.insert(identity, first.href.clone()); | ||
| 107 | } | ||
| 108 | for (page, listed) in section.pages.iter().flatten().zip(&pages) { | ||
| 109 | if let Some(identity) = page.identity { | ||
| 110 | links.pages.insert(identity, listed.href.clone()); | ||
| 111 | } | ||
| 112 | } | ||
| 113 | (folder, pages) | ||
| 114 | }) | ||
| 115 | .collect(); | ||
| 116 | Self { | ||
| 117 | notebook: notebook.to_owned(), | ||
| 118 | sections, | ||
| 119 | listed, | ||
| 120 | links, | ||
| 121 | written: BTreeSet::new(), | ||
| 122 | calibri: false, | ||
| 123 | lang: None, | ||
| 124 | alone, | ||
| 125 | } | ||
| 126 | } | ||
| 127 | |||
| 128 | /// Writes `page`, the one at `at` in its section's listing at `section`. A page that can't | ||
| 129 | /// be laid out is written as a note saying so. | ||
| 130 | pub fn page( | ||
| 131 | &mut self, | ||
| 132 | [section, at]: [usize; 2], | ||
| 133 | page: Page, | ||
| 134 | engine: &mut TextEngine, | ||
| 135 | write: &mut dyn FnMut(&str, &[u8]) -> io::Result<()>, | ||
| 136 | ) -> io::Result<()> { | ||
| 137 | let (folder, listed) = &self.listed[section]; | ||
| 138 | let section = &self.sections[section]; | ||
| 139 | let listing = &listed[at]; | ||
| 140 | let root = match self.alone { | ||
| 141 | true => String::new(), | ||
| 142 | false => "../".repeat(folder.matches('/').count() + 1), | ||
| 143 | }; | ||
| 144 | let trail: String = (section.groups.iter()) | ||
| 145 | .map(|group| format!(" › {}", text(group))) | ||
| 146 | .collect(); | ||
| 147 | let formats = formats(&page); | ||
| 148 | self.calibri |= (formats.iter()).any(|format| format.font.as_deref() == Some("Calibri")); | ||
| 149 | let lang = (formats.iter()).find_map(|format| crate::language::tag(format.language?)); | ||
| 150 | self.lang = self.lang.or(lang); | ||
| 151 | let mut assets = Assets { | ||
| 152 | write, | ||
| 153 | written: &mut self.written, | ||
| 154 | }; | ||
| 155 | let body = match page_html(page, engine, &mut assets, &self.links, &root) { | ||
| 156 | Ok(body) => body?, | ||
| 157 | Err(error) => format!( | ||
| 158 | "<main class=page><p class=failed>This page couldn't be exported: {}</p></main>", | ||
| 159 | text(&error.to_string()) | ||
| 160 | ), | ||
| 161 | }; | ||
| 162 | if self.alone { | ||
| 163 | let head = head(&listing.title, lang, &root); | ||
| 164 | let html = format!("{head}{body}\n</body>\n</html>\n"); | ||
| 165 | return (assets.write)(&listing.href, html.as_bytes()); | ||
| 166 | } | ||
| 167 | let mut nav = String::new(); | ||
| 168 | page_list(listed, Some(at), &root, &mut nav); | ||
| 169 | let html = format!( | ||
| 170 | "{head}<header><a href=\"{root}index.html\">{notebook}</a>{trail} › {name}</header>\n\ | ||
| 171 | <div class=view>\n{body}\n<nav class=pages aria-label=Pages>\n{nav}</nav>\n</div>\n\ | ||
| 172 | </body>\n</html>\n", | ||
| 173 | head = head( | ||
| 174 | &format!("{} - {}", listing.title, section.name), | ||
| 175 | lang, | ||
| 176 | &root | ||
| 177 | ), | ||
| 178 | name = text(&section.name), | ||
| 179 | notebook = text(&self.notebook), | ||
| 180 | ); | ||
| 181 | (assets.write)(&listing.href, html.as_bytes()) | ||
| 182 | } | ||
| 183 | |||
| 184 | /// Writes the index, listing every section in its groups, and the stylesheet. | ||
| 185 | pub fn finish(self, write: &mut dyn FnMut(&str, &[u8]) -> io::Result<()>) -> io::Result<()> { | ||
| 186 | let mut index = String::new(); | ||
| 187 | let mut groups: Vec<&String> = Vec::new(); | ||
| 188 | for (section, (_, pages)) in self.sections.iter().zip(&self.listed) { | ||
| 189 | // The index nests sections in their groups as the notebook does. | ||
| 190 | let kept = (groups.iter().zip(&section.groups)) | ||
| 191 | .take_while(|(open, group)| *open == group) | ||
| 192 | .count(); | ||
| 193 | for _ in kept..groups.len() { | ||
| 194 | index.push_str("</ul></li>\n"); | ||
| 195 | } | ||
| 196 | groups.truncate(kept); | ||
| 197 | for group in &section.groups[kept..] { | ||
| 198 | let level = (groups.len() + 2).min(6); | ||
| 199 | let _ = writeln!( | ||
| 200 | index, | ||
| 201 | "<li class=group><h{level}>{}</h{level}><ul>", | ||
| 202 | text(group) | ||
| 203 | ); | ||
| 204 | groups.push(group); | ||
| 205 | } | ||
| 206 | let level = (groups.len() + 2).min(6); | ||
| 207 | let color = section | ||
| 208 | .color | ||
| 209 | .map(|color| format!(" style='border-color:{}'", hex(color))); | ||
| 210 | let name = match pages.first() { | ||
| 211 | Some(page) => format!( | ||
| 212 | "<a href=\"{}\">{}</a>", | ||
| 213 | href(&page.href), | ||
| 214 | text(&section.name) | ||
| 215 | ), | ||
| 216 | None => text(&section.name), | ||
| 217 | }; | ||
| 218 | let _ = writeln!( | ||
| 219 | index, | ||
| 220 | "<li class=section><h{level} class=section{}>{name}</h{level}>", | ||
| 221 | color.unwrap_or_default() | ||
| 222 | ); | ||
| 223 | if section.pages.is_none() { | ||
| 224 | index.push_str("<p class=locked>Locked</p>\n"); | ||
| 225 | } | ||
| 226 | page_list(pages, None, "", &mut index); | ||
| 227 | index.push_str("</li>\n"); | ||
| 228 | } | ||
| 229 | for _ in groups { | ||
| 230 | index.push_str("</ul></li>\n"); | ||
| 231 | } | ||
| 232 | let index = format!( | ||
| 233 | "{}<main class=index>\n<h1>{}</h1>\n<ul>\n{index}</ul>\n</main>\n</body>\n</html>\n", | ||
| 234 | head(&self.notebook, self.lang, ""), | ||
| 235 | text(&self.notebook) | ||
| 236 | ); | ||
| 237 | if !self.alone { | ||
| 238 | write("index.html", index.as_bytes())?; | ||
| 239 | } | ||
| 240 | let mut style = String::new(); | ||
| 241 | // Calibri, OneNote's default, is missing from macOS and Linux; its metric-compatible | ||
| 242 | // stand-in keeps lines wrapping where they do on the page. | ||
| 243 | if self.calibri { | ||
| 244 | for face in crate::layout::bundled("Calibri").into_iter().flatten() { | ||
| 245 | use skrifa::{MetadataProvider, attribute::Style}; | ||
| 246 | let Ok(font) = skrifa::FontRef::new(face.as_ref()) else { | ||
| 247 | continue; | ||
| 248 | }; | ||
| 249 | let attributes = font.attributes(); | ||
| 250 | let weight = attributes.weight.value(); | ||
| 251 | let italic = attributes.style != Style::Normal; | ||
| 252 | let name = format!( | ||
| 253 | "fonts/Calibri-{weight}{}.ttf", | ||
| 254 | if italic { "-italic" } else { "" } | ||
| 255 | ); | ||
| 256 | write(&name, face.as_ref())?; | ||
| 257 | let _ = writeln!( | ||
| 258 | style, | ||
| 259 | "@font-face {{ font-family: Calibri; src: local(\"Calibri\"), url(\"{name}\"); \ | ||
| 260 | font-weight: {weight}; font-style: {}; }}", | ||
| 261 | if italic { "italic" } else { "normal" } | ||
| 262 | ); | ||
| 263 | } | ||
| 264 | } | ||
| 265 | style.push_str(STYLE); | ||
| 266 | write("style.css", style.as_bytes()) | ||
| 267 | } | ||
| 268 | } | ||
| 269 | |||
| 270 | /// The formats of the text on `page`, title first. | ||
| 271 | fn formats(page: &Page) -> Vec<&onestore::document::Format> { | ||
| 272 | fn walk<'a>( | ||
| 273 | paragraphs: &'a [PageParagraph], | ||
| 274 | formats: &mut Vec<&'a onestore::document::Format>, | ||
| 275 | ) { | ||
| 276 | for paragraph in paragraphs { | ||
| 277 | match &paragraph.content { | ||
| 278 | ParagraphContent::Text(text) => { | ||
| 279 | formats.extend(text.text.spans().iter().map(|span| &span.format)) | ||
| 280 | } | ||
| 281 | ParagraphContent::Table(table) => { | ||
| 282 | for cell in table.rows.iter().flat_map(|row| &row.cells) { | ||
| 283 | walk(&cell.paragraphs, formats); | ||
| 284 | } | ||
| 285 | } | ||
| 286 | _ => {} | ||
| 287 | } | ||
| 288 | } | ||
| 289 | } | ||
| 290 | let mut formats = Vec::new(); | ||
| 291 | let titles = page.objects.iter().filter_map(|object| match object { | ||
| 292 | PageObject::Title(title) => Some(&title.outlines), | ||
| 293 | _ => None, | ||
| 294 | }); | ||
| 295 | for outline in titles.flatten() { | ||
| 296 | walk(&outline.paragraphs, &mut formats); | ||
| 297 | } | ||
| 298 | for object in &page.objects { | ||
| 299 | if let PageObject::Outline(outline) = object { | ||
| 300 | walk(&outline.paragraphs, &mut formats); | ||
| 301 | } | ||
| 302 | } | ||
| 303 | formats | ||
| 304 | } | ||
| 305 | |||
| 306 | /// A document in `lang`, titled `title`, its stylesheet from `root`, to its body's start. | ||
| 307 | fn head(title: &str, lang: Option<&str>, root: &str) -> String { | ||
| 308 | let lang = lang.map(|lang| format!(" lang={lang}")).unwrap_or_default(); | ||
| 309 | format!( | ||
| 310 | "<!DOCTYPE html>\n<html{lang}>\n<head>\n<meta charset=utf-8>\n\ | ||
| 311 | <meta name=viewport content=\"width=device-width\">\n\ | ||
| 312 | <meta name=generator content=Snowbound>\n<title>{}</title>\n\ | ||
| 313 | <link rel=stylesheet href=\"{root}style.css\">\n</head>\n<body>\n", | ||
| 314 | text(title) | ||
| 315 | ) | ||
| 316 | } | ||
| 317 | |||
| 318 | /// Where the exported files lie that links into the notebook name, by identity. | ||
| 319 | #[derive(Default)] | ||
| 320 | struct Links { | ||
| 321 | /// A section's first page. | ||
| 322 | sections: BTreeMap<[u8; 16], String>, | ||
| 323 | /// A page's file. | ||
| 324 | pages: BTreeMap<[u8; 16], String>, | ||
| 325 | } | ||
| 326 | |||
| 327 | impl Links { | ||
| 328 | /// Where stored link `target` leads from `root`: into the export, to its file; out of the | ||
| 329 | /// notebook, as stored where HTML may link it. None for anything else, a link into the | ||
| 330 | /// notebook outside the export among them, whose address names the writer's own files. | ||
| 331 | fn link(&self, target: &str, root: &str) -> Option<String> { | ||
| 332 | self.resolve(target, root).or_else(|| { | ||
| 333 | linkable(target).filter(|target| { | ||
| 334 | !(target.get(..8)).is_some_and(|scheme| scheme.eq_ignore_ascii_case("onenote:")) | ||
| 335 | }) | ||
| 336 | }) | ||
| 337 | } | ||
| 338 | |||
| 339 | /// Where `target` leads in the site, from `root`, a paragraph to its anchor; none for a | ||
| 340 | /// link to something outside it, or to anything but the notebook. | ||
| 341 | fn resolve(&self, target: &str, root: &str) -> Option<String> { | ||
| 342 | let link = onestore::page::link::parse_internal_link(target)?; | ||
| 343 | let (file, fragment) = match link.page { | ||
| 344 | Some(page) => ( | ||
| 345 | self.pages.get(&page)?, | ||
| 346 | link.object.map(|object| format!("#{}", anchor(object))), | ||
| 347 | ), | ||
| 348 | None => (self.sections.get(&link.section)?, None), | ||
| 349 | }; | ||
| 350 | Some(format!( | ||
| 351 | "{root}{}{}", | ||
| 352 | href(file), | ||
| 353 | fragment.unwrap_or_default() | ||
| 354 | )) | ||
| 355 | } | ||
| 356 | } | ||
| 357 | |||
| 358 | /// The element id of paragraph `id`. | ||
| 359 | fn anchor(id: ExGuid) -> String { | ||
| 360 | let guid: String = id.guid.iter().map(|byte| format!("{byte:02x}")).collect(); | ||
| 361 | format!("p{guid}-{}", id.n) | ||
| 362 | } | ||
| 363 | |||
| 364 | /// A page as navigation lists it. | ||
| 365 | struct Listed { | ||
| 366 | href: String, | ||
| 367 | title: String, | ||
| 368 | level: u32, | ||
| 369 | } | ||
| 370 | |||
| 371 | /// `pages` as a list nested by level, `current` marked, hrefs from `root`. | ||
| 372 | fn page_list(pages: &[Listed], current: Option<usize>, root: &str, out: &mut String) { | ||
| 373 | let mut levels: Vec<u32> = Vec::new(); | ||
| 374 | for (at, page) in pages.iter().enumerate() { | ||
| 375 | while levels.last().is_some_and(|level| *level > page.level) { | ||
| 376 | out.push_str("</li></ul>\n"); | ||
| 377 | levels.pop(); | ||
| 378 | } | ||
| 379 | match levels.last() { | ||
| 380 | Some(level) if *level == page.level => out.push_str("</li>\n"), | ||
| 381 | _ => { | ||
| 382 | out.push_str("<ul>\n"); | ||
| 383 | levels.push(page.level); | ||
| 384 | } | ||
| 385 | } | ||
| 386 | let current = if current == Some(at) { | ||
| 387 | " aria-current=page" | ||
| 388 | } else { | ||
| 389 | "" | ||
| 390 | }; | ||
| 391 | let _ = write!( | ||
| 392 | out, | ||
| 393 | "<li><a href=\"{root}{}\"{current}>{}</a>", | ||
| 394 | href(&page.href), | ||
| 395 | text(&page.title) | ||
| 396 | ); | ||
| 397 | } | ||
| 398 | for _ in levels { | ||
| 399 | out.push_str("</li></ul>\n"); | ||
| 400 | } | ||
| 401 | } | ||
| 402 | |||
| 403 | /// Pictures, files, tag icons and fonts copied beside the pages, each once. | ||
| 404 | struct Assets<'a> { | ||
| 405 | write: &'a mut dyn FnMut(&str, &[u8]) -> io::Result<()>, | ||
| 406 | written: &'a mut BTreeSet<String>, | ||
| 407 | } | ||
| 408 | |||
| 409 | impl Assets<'_> { | ||
| 410 | /// `bytes` at `name` under the site's folder, unless already there. | ||
| 411 | fn put(&mut self, name: String, bytes: &[u8]) -> io::Result<String> { | ||
| 412 | if !self.written.contains(&name) { | ||
| 413 | (self.write)(&name, bytes)?; | ||
| 414 | self.written.insert(name.clone()); | ||
| 415 | } | ||
| 416 | Ok(name) | ||
| 417 | } | ||
| 418 | |||
| 419 | /// Where the picture lies: its stored bytes in a format browsers show, else the raster | ||
| 420 | /// OneNote made of them; none where it has neither. | ||
| 421 | fn picture(&mut self, image: &Image) -> io::Result<Option<String>> { | ||
| 422 | let shown = [&image.bytes, &image.display] | ||
| 423 | .into_iter() | ||
| 424 | .flatten() | ||
| 425 | .find_map(|bytes| Some((bytes, shown_extension(bytes)?))); | ||
| 426 | let Some((bytes, extension)) = shown else { | ||
| 427 | return Ok(None); | ||
| 428 | }; | ||
| 429 | self.put(format!("files/{}.{extension}", digest(bytes)), bytes) | ||
| 430 | .map(Some) | ||
| 431 | } | ||
| 432 | |||
| 433 | /// Where an attached file's copy lies, under its own name, and its icon. | ||
| 434 | fn file(&mut self, file: &Attachment) -> io::Result<(Option<String>, String)> { | ||
| 435 | let copy = match &file.bytes { | ||
| 436 | Some(bytes) => Some(self.put( | ||
| 437 | format!("files/{}/{}", digest(bytes), component(&file.filename)), | ||
| 438 | bytes, | ||
| 439 | )?), | ||
| 440 | None => None, | ||
| 441 | }; | ||
| 442 | let preview = | ||
| 443 | (file.preview.as_deref()).and_then(|icon| Some((icon, shown_extension(icon)?))); | ||
| 444 | let icon = match preview { | ||
| 445 | Some((icon, extension)) => { | ||
| 446 | self.put(format!("files/{}.{extension}", digest(icon)), icon)? | ||
| 447 | } | ||
| 448 | None if self.written.contains(BLANK_FILE) => BLANK_FILE.to_owned(), | ||
| 449 | None => self.put(BLANK_FILE.to_owned(), &crate::gpu::page::file_icon())?, | ||
| 450 | }; | ||
| 451 | Ok((copy, icon)) | ||
| 452 | } | ||
| 453 | |||
| 454 | /// The tag's icon, laid out as the page draws it in `[x, y]` points from where its | ||
| 455 | /// element starts. | ||
| 456 | fn tag(&mut self, tag: &ParagraphTag, [x, y]: [f32; 2], root: &str) -> io::Result<String> { | ||
| 457 | let checked = matches!(tag.icon, TagIcon::Symbol { checked: true, .. }); | ||
| 458 | let label = match (tag.label.as_str(), checked) { | ||
| 459 | ("", _) => "Tag".to_owned(), | ||
| 460 | (label, true) => format!("{label} (done)"), | ||
| 461 | (label, false) => label.to_owned(), | ||
| 462 | }; | ||
| 463 | let mut out = format!( | ||
| 464 | "<span class=tag role=img aria-label=\"{label}\" title=\"{label}\" \ | ||
| 465 | style='left:{x}pt;top:{y}pt;width:{side}pt;height:{side}pt'>", | ||
| 466 | label = text(&label), | ||
| 467 | side = tag.size, | ||
| 468 | ); | ||
| 469 | for source in tag_sources(tag.icon) { | ||
| 470 | let name = self.put( | ||
| 471 | format!("tags/{}.svg", digest(source.as_bytes())), | ||
| 472 | source.as_bytes(), | ||
| 473 | )?; | ||
| 474 | let _ = write!(out, "<img src=\"{root}{name}\" alt=\"\">"); | ||
| 475 | } | ||
| 476 | out.push_str("</span>"); | ||
| 477 | Ok(out) | ||
| 478 | } | ||
| 479 | } | ||
| 480 | |||
| 481 | /// The file extension of a picture in a format every browser shows; none for another. | ||
| 482 | fn shown_extension(bytes: &[u8]) -> Option<&'static str> { | ||
| 483 | use image::ImageFormat; | ||
| 484 | match image::guess_format(bytes).ok()? { | ||
| 485 | ImageFormat::Png => Some("png"), | ||
| 486 | ImageFormat::Jpeg => Some("jpg"), | ||
| 487 | ImageFormat::Gif => Some("gif"), | ||
| 488 | ImageFormat::Bmp => Some("bmp"), | ||
| 489 | ImageFormat::WebP => Some("webp"), | ||
| 490 | _ => None, | ||
| 491 | } | ||
| 492 | } | ||
| 493 | |||
| 494 | /// The page's `<main>`: each object on the page where the page lays it out. | ||
| 495 | fn page_html( | ||
| 496 | mut page: Page, | ||
| 497 | engine: &mut TextEngine, | ||
| 498 | assets: &mut Assets, | ||
| 499 | links: &Links, | ||
| 500 | root: &str, | ||
| 501 | ) -> Result<io::Result<String>, crate::editor::EditorError> { | ||
| 502 | let objects = build(&mut page, engine, false)?.objects; | ||
| 503 | Ok(PageWriter { | ||
| 504 | assets, | ||
| 505 | links, | ||
| 506 | root, | ||
| 507 | definitions: &page.definitions, | ||
| 508 | } | ||
| 509 | .write(&page, &objects)) | ||
| 510 | } | ||
| 511 | |||
| 512 | struct PageWriter<'a, 'b> { | ||
| 513 | assets: &'a mut Assets<'b>, | ||
| 514 | links: &'a Links, | ||
| 515 | root: &'a str, | ||
| 516 | definitions: &'a BTreeMap<ExGuid, Definition>, | ||
| 517 | } | ||
| 518 | |||
| 519 | impl PageWriter<'_, '_> { | ||
| 520 | fn write(&mut self, page: &Page, objects: &[Content]) -> io::Result<String> { | ||
| 521 | let mut bounds = [f32::INFINITY, f32::INFINITY, 0.0_f32, 0.0_f32]; | ||
| 522 | let mut body = String::new(); | ||
| 523 | for object in objects { | ||
| 524 | let rect = match object { | ||
| 525 | Content::Outline { source, layout, .. } => { | ||
| 526 | let [x, y] = crate::origin(&source.layout); | ||
| 527 | let heading = if source.title { | ||
| 528 | " role=heading aria-level=1" | ||
| 529 | } else { | ||
| 530 | "" | ||
| 531 | }; | ||
| 532 | self.outline(&source.paragraphs, layout, [x, y], heading, &mut body)?; | ||
| 533 | [x, y, x + layout.size[0], y + layout.size[1]] | ||
| 534 | } | ||
| 535 | Content::Image(image) => { | ||
| 536 | let [x, y] = crate::origin(&image.layout); | ||
| 537 | let Some([width, height]) = crate::outline::image_size(image) else { | ||
| 538 | continue; | ||
| 539 | }; | ||
| 540 | let style = format!("left:{x}pt;top:{y}pt;width:{width}pt;height:{height}pt"); | ||
| 541 | body.push_str(&self.picture(image, &style)?); | ||
| 542 | [x, y, x + width, y + height] | ||
| 543 | } | ||
| 544 | Content::File { source, .. } => { | ||
| 545 | let Some((_, rect)) = object.file() else { | ||
| 546 | continue; | ||
| 547 | }; | ||
| 548 | let style = format!("left:{}pt;top:{}pt", rect[0], rect[1]); | ||
| 549 | body.push_str(&self.file(source, &style)?); | ||
| 550 | rect | ||
| 551 | } | ||
| 552 | Content::Ink(ink) => { | ||
| 553 | let Some(rect) = ink_bounds(ink) else { | ||
| 554 | continue; | ||
| 555 | }; | ||
| 556 | let style = format!("left:{}pt;top:{}pt;", rect[0], rect[1]); | ||
| 557 | body.push_str(&ink_svg(ink, &style)); | ||
| 558 | rect | ||
| 559 | } | ||
| 560 | Content::ReadOnly(object) => { | ||
| 561 | let [x0, y0, x1, y1] = object.rect(); | ||
| 562 | let _ = write!( | ||
| 563 | body, | ||
| 564 | "<div class=missing style='left:{x0}pt;top:{y0}pt;width:{}pt;height:{}pt'>\ | ||
| 565 | {}</div>", | ||
| 566 | x1 - x0, | ||
| 567 | y1 - y0, | ||
| 568 | text(&object.message.replace("\nRead-only", "")) | ||
| 569 | ); | ||
| 570 | [x0, y0, x1, y1] | ||
| 571 | } | ||
| 572 | Content::Date { .. } | Content::Editable(_) => continue, | ||
| 573 | }; | ||
| 574 | if let Some((_, tags, rect)) = object.tagged() { | ||
| 575 | for tag in crate::outline::object_tags(tags, self.definitions, rect) { | ||
| 576 | body.push_str(&self.assets.tag(&tag, tag.origin, self.root)?); | ||
| 577 | } | ||
| 578 | } | ||
| 579 | bounds = [ | ||
| 580 | bounds[0].min(rect[0]), | ||
| 581 | bounds[1].min(rect[1]), | ||
| 582 | bounds[2].max(rect[2]), | ||
| 583 | bounds[3].max(rect[3]), | ||
| 584 | ]; | ||
| 585 | } | ||
| 586 | // A right-to-left page lies far right of its origin, which OneNote opens scrolled to. | ||
| 587 | let left = if page.rtl && bounds[0].is_finite() { | ||
| 588 | bounds[0] - MARGIN | ||
| 589 | } else { | ||
| 590 | 0.0 | ||
| 591 | }; | ||
| 592 | let color = page | ||
| 593 | .color | ||
| 594 | .map(|color| format!(" style='background:{}'", hex(color))); | ||
| 595 | Ok(format!( | ||
| 596 | "<main class=page{}>\n<div class=sheet style='left:{}pt;width:{}pt;height:{}pt'>\n\ | ||
| 597 | {}{body}</div>\n</main>", | ||
| 598 | color.unwrap_or_default(), | ||
| 599 | -left, | ||
| 600 | bounds[2] + MARGIN, | ||
| 601 | bounds[3] + MARGIN, | ||
| 602 | rules(page) | ||
| 603 | )) | ||
| 604 | } | ||
| 605 | |||
| 606 | fn outline( | ||
| 607 | &mut self, | ||
| 608 | paragraphs: &[PageParagraph], | ||
| 609 | layout: &OutlineLayout, | ||
| 610 | [x, y]: [f32; 2], | ||
| 611 | heading: &str, | ||
| 612 | out: &mut String, | ||
| 613 | ) -> io::Result<()> { | ||
| 614 | let mut visible: Vec<PageParagraph> = crate::outline::visible_paragraphs(paragraphs.iter()) | ||
| 615 | .cloned() | ||
| 616 | .collect(); | ||
| 617 | repaint(&mut visible, layout); | ||
| 618 | let definitions = self.definitions; | ||
| 619 | let column = layout.tag_column_offset(); | ||
| 620 | let mut extras = OutlineExtras { | ||
| 621 | writer: self, | ||
| 622 | paragraphs: (layout.paragraphs.iter()) | ||
| 623 | .map(|paragraph| (paragraph.id, paragraph)) | ||
| 624 | .collect(), | ||
| 625 | column, | ||
| 626 | failed: None, | ||
| 627 | }; | ||
| 628 | let mut html = String::new(); | ||
| 629 | blocks(&visible, definitions, &mut extras, &mut html); | ||
| 630 | if let Some(error) = extras.failed { | ||
| 631 | return Err(error); | ||
| 632 | } | ||
| 633 | let _ = write!( | ||
| 634 | out, | ||
| 635 | "<div class=outline{heading} style='left:{x}pt;top:{y}pt;width:{}pt'>\n{html}", | ||
| 636 | layout.size[0] | ||
| 637 | ); | ||
| 638 | // Text carries its own tags; those on tables and pictures lie where the page lays them. | ||
| 639 | for (paragraph, [tx, ty], tag) in layout.tags() { | ||
| 640 | if !layout.paragraphs.iter().any(|text| text.id == paragraph) { | ||
| 641 | out.push_str(&self.assets.tag(tag, [tx + column, ty], self.root)?); | ||
| 642 | } | ||
| 643 | } | ||
| 644 | out.push_str("</div>\n"); | ||
| 645 | Ok(()) | ||
| 646 | } | ||
| 647 | |||
| 648 | /// A picture, linked where it links, at `style`. | ||
| 649 | fn picture(&mut self, image: &Image, style: &str) -> io::Result<String> { | ||
| 650 | let link = (image.link.as_deref()).and_then(|link| self.links.link(link, self.root)); | ||
| 651 | let (outer, inner) = match link { | ||
| 652 | Some(_) => (style, "width:100%;height:100%"), | ||
| 653 | None => ("", style), | ||
| 654 | }; | ||
| 655 | let picture = match self.assets.picture(image)? { | ||
| 656 | Some(name) => format!( | ||
| 657 | "<img class=picture src=\"{}{}\" alt=\"{}\" style='{inner}'>", | ||
| 658 | self.root, | ||
| 659 | href(&name), | ||
| 660 | text(image.alt.as_deref().unwrap_or_default()) | ||
| 661 | ), | ||
| 662 | None => format!("<span class=missing style='{inner}'>Picture not shown</span>"), | ||
| 663 | }; | ||
| 664 | // A link holding only a picture is named by the picture's text, else as a picture. | ||
| 665 | let label = match image.alt.as_deref().map(str::trim) { | ||
| 666 | Some("") | None => " aria-label=Picture", | ||
| 667 | Some(_) => "", | ||
| 668 | }; | ||
| 669 | Ok(match link { | ||
| 670 | Some(link) => format!( | ||
| 671 | "<a href=\"{}\"{label} style='{outer}'>{picture}</a>", | ||
| 672 | text(&link) | ||
| 673 | ), | ||
| 674 | None => picture, | ||
| 675 | }) | ||
| 676 | } | ||
| 677 | |||
| 678 | /// A file as OneNote shows one, its icon over its name, linking to its copy. | ||
| 679 | fn file(&mut self, file: &Attachment, style: &str) -> io::Result<String> { | ||
| 680 | let (copy, icon) = self.assets.file(file)?; | ||
| 681 | let name = std::path::Path::new(&file.filename) | ||
| 682 | .file_stem() | ||
| 683 | .map_or(file.filename.clone(), |stem| { | ||
| 684 | stem.to_string_lossy().into_owned() | ||
| 685 | }); | ||
| 686 | let [width, height] = file.size.unwrap_or([24.0, 24.0]); | ||
| 687 | let inner = format!( | ||
| 688 | "<img src=\"{}{}\" alt=\"\" style='width:{width}pt;height:{height}pt'><span>{}</span>", | ||
| 689 | self.root, | ||
| 690 | href(&icon), | ||
| 691 | text(&name) | ||
| 692 | ); | ||
| 693 | Ok(match copy { | ||
| 694 | Some(copy) => format!( | ||
| 695 | "<a class=file href=\"{}{}\" title=\"{}\" style='{style}'>{inner}</a>", | ||
| 696 | self.root, | ||
| 697 | href(&copy), | ||
| 698 | text(&file.filename) | ||
| 699 | ), | ||
| 700 | None => format!("<span class=file style='{style}'>{inner}</span>"), | ||
| 701 | }) | ||
| 702 | } | ||
| 703 | } | ||
| 704 | |||
| 705 | /// What a page adds to the blocks Copy writes: text paragraphs' alignment, spacing and tags, | ||
| 706 | /// and the pictures, files and drawings in an outline. | ||
| 707 | struct OutlineExtras<'w, 'a, 'b> { | ||
| 708 | writer: &'w mut PageWriter<'a, 'b>, | ||
| 709 | paragraphs: BTreeMap<ExGuid, &'w ParagraphLayout>, | ||
| 710 | column: f32, | ||
| 711 | /// The first file that couldn't be written. | ||
| 712 | failed: Option<io::Error>, | ||
| 713 | } | ||
| 714 | |||
| 715 | impl Extras for OutlineExtras<'_, '_, '_> { | ||
| 716 | fn style(&mut self, node: &PageParagraph) -> String { | ||
| 717 | let Some(format) = (node.text()) | ||
| 718 | .and_then(|text| text.text.spans().first()) | ||
| 719 | .map(|span| &span.format) | ||
| 720 | else { | ||
| 721 | return String::new(); | ||
| 722 | }; | ||
| 723 | let mut style = String::new(); | ||
| 724 | match format.alignment { | ||
| 725 | Some(1) => style.push_str(";text-align:center"), | ||
| 726 | Some(2) => style.push_str(";text-align:right"), | ||
| 727 | _ => {} | ||
| 728 | } | ||
| 729 | // Lines as tall as the page's, whose line boxes take Windows' font metrics. | ||
| 730 | if let Some(paragraph) = self.paragraphs.get(&node.id) { | ||
| 731 | let mut heights = paragraph.text.lines().map(|(_, line)| line.height); | ||
| 732 | if let Some(first) = heights.next() | ||
| 733 | && heights.all(|height| (height - first).abs() < 0.01) | ||
| 734 | { | ||
| 735 | let _ = write!(style, ";line-height:{first}pt"); | ||
| 736 | } | ||
| 737 | } | ||
| 738 | if let Some(before) = format.space_before.filter(|space| *space > 0.0) { | ||
| 739 | let _ = write!(style, ";margin-top:{before}pt"); | ||
| 740 | } | ||
| 741 | if let Some(after) = format.space_after.filter(|space| *space > 0.0) { | ||
| 742 | let _ = write!(style, ";margin-bottom:{after}pt"); | ||
| 743 | } | ||
| 744 | style | ||
| 745 | } | ||
| 746 | |||
| 747 | fn attributes(&mut self, node: &PageParagraph) -> String { | ||
| 748 | // The number the page shows, which a list's own count would not give. | ||
| 749 | (self.paragraphs.get(&node.id)) | ||
| 750 | .and_then(|paragraph| paragraph.number.as_ref()) | ||
| 751 | .map(|(count, _)| format!(" value={}", count.number)) | ||
| 752 | .unwrap_or_default() | ||
| 753 | } | ||
| 754 | |||
| 755 | fn link(&mut self, target: &str) -> Option<String> { | ||
| 756 | self.writer.links.link(target, self.writer.root) | ||
| 757 | } | ||
| 758 | |||
| 759 | fn content(&mut self, node: &PageParagraph, out: &mut String) { | ||
| 760 | let _ = write!(out, "<a id={}></a>", anchor(node.id)); | ||
| 761 | let written = match &node.content { | ||
| 762 | ParagraphContent::Text(_) => { | ||
| 763 | let Some(paragraph) = self.paragraphs.get(&node.id) else { | ||
| 764 | return; | ||
| 765 | }; | ||
| 766 | // List markers as the page numbers and places them, which HTML's lists can't. | ||
| 767 | let mut tags = String::new(); | ||
| 768 | let font = (node.text()) | ||
| 769 | .and_then(|text| text.text.spans().first()) | ||
| 770 | .map(|span| &span.format); | ||
| 771 | let lists = node.lists.iter().rev(); | ||
| 772 | for ((marker, [x, y]), list) in paragraph.markers.iter().zip(lists) { | ||
| 773 | let size = (self.writer.definitions.get(list)) | ||
| 774 | .and_then(|list| list.format.font_size) | ||
| 775 | .or(font.and_then(|font| font.font_size)) | ||
| 776 | .unwrap_or(crate::layout::DEFAULT_FONT_SIZE); | ||
| 777 | let family = font_name( | ||
| 778 | (font.and_then(|font| font.font.as_deref())) | ||
| 779 | .unwrap_or(crate::layout::DEFAULT_FONT), | ||
| 780 | ) | ||
| 781 | .map(|family| format!("font-family:\"{family}\";")) | ||
| 782 | .unwrap_or_default(); | ||
| 783 | // The list item tells assistive technology its number or bullet. | ||
| 784 | let _ = write!( | ||
| 785 | tags, | ||
| 786 | "<span class=marker aria-hidden=true style='left:{}pt;top:{y}pt;{family}\ | ||
| 787 | font-size:{size}pt'>{}</span>", | ||
| 788 | x - paragraph.origin[0], | ||
| 789 | text(&marker.text) | ||
| 790 | ); | ||
| 791 | } | ||
| 792 | let mut result = Ok(()); | ||
| 793 | for tag in &paragraph.tags { | ||
| 794 | let at = [ | ||
| 795 | tag.origin[0] + self.column - paragraph.origin[0], | ||
| 796 | tag.origin[1], | ||
| 797 | ]; | ||
| 798 | match self.writer.assets.tag(tag, at, self.writer.root) { | ||
| 799 | Ok(tag) => tags.push_str(&tag), | ||
| 800 | Err(error) => result = Err(error), | ||
| 801 | } | ||
| 802 | } | ||
| 803 | result.map(|()| tags) | ||
| 804 | } | ||
| 805 | ParagraphContent::Image(image) => match crate::outline::image_size(image) { | ||
| 806 | Some([width, height]) => self | ||
| 807 | .writer | ||
| 808 | .picture(image, &format!("width:{width}pt;height:{height}pt")) | ||
| 809 | .map(|picture| format!("<div>{picture}</div>\n")), | ||
| 810 | None => Ok(String::new()), | ||
| 811 | }, | ||
| 812 | ParagraphContent::Attachment(file) => self | ||
| 813 | .writer | ||
| 814 | .file(file, "") | ||
| 815 | .map(|file| format!("<div>{file}</div>\n")), | ||
| 816 | ParagraphContent::Ink(ink) => Ok(format!("<div>{}</div>\n", ink_svg(ink, ""))), | ||
| 817 | ParagraphContent::Unsupported(_) => { | ||
| 818 | Ok("<p class=missing>Content not shown</p>\n".to_owned()) | ||
| 819 | } | ||
| 820 | ParagraphContent::Table(_) => Ok(String::new()), | ||
| 821 | }; | ||
| 822 | match written { | ||
| 823 | Ok(written) => out.push_str(&written), | ||
| 824 | Err(error) => { | ||
| 825 | self.failed.get_or_insert(error); | ||
| 826 | } | ||
| 827 | } | ||
| 828 | } | ||
| 829 | } | ||
| 830 | |||
| 831 | /// `paragraphs` with the colour and highlight their tags give each run, as the page lays | ||
| 832 | /// them out. | ||
| 833 | fn repaint(paragraphs: &mut [PageParagraph], layout: &OutlineLayout) { | ||
| 834 | for paragraph in paragraphs { | ||
| 835 | match &mut paragraph.content { | ||
| 836 | ParagraphContent::Text(text) => { | ||
| 837 | let Some(laid) = (layout.paragraphs.iter()).find(|laid| laid.id == paragraph.id) | ||
| 838 | else { | ||
| 839 | continue; | ||
| 840 | }; | ||
| 841 | let [color, highlight] = laid.tag_paint; | ||
| 842 | if color.is_none() && highlight.is_none() { | ||
| 843 | continue; | ||
| 844 | } | ||
| 845 | let mut start = 0; | ||
| 846 | let runs: Vec<_> = (text.text.spans().iter()) | ||
| 847 | .map(|span| { | ||
| 848 | let run = text.text.text()[start..span.end].to_owned(); | ||
| 849 | start = span.end; | ||
| 850 | let mut format = span.format.clone(); | ||
| 851 | format.color = color.or(format.color); | ||
| 852 | format.highlight = highlight.or(format.highlight); | ||
| 853 | (run, format) | ||
| 854 | }) | ||
| 855 | .collect(); | ||
| 856 | text.text = onestore::page::text::Paragraph::from_runs(runs); | ||
| 857 | } | ||
| 858 | ParagraphContent::Table(table) => { | ||
| 859 | for cell in table.rows.iter_mut().flat_map(|row| &mut row.cells) { | ||
| 860 | repaint(&mut cell.paragraphs, layout); | ||
| 861 | } | ||
| 862 | } | ||
| 863 | _ => {} | ||
| 864 | } | ||
| 865 | } | ||
| 866 | } | ||
| 867 | |||
| 868 | /// The drawing as SVG the size of its strokes, its own `style` first, its strokes as the page | ||
| 869 | /// paints them. | ||
| 870 | fn ink_svg(ink: &Ink, style: &str) -> String { | ||
| 871 | let Some([x0, y0, x1, y1]) = ink_bounds(ink) else { | ||
| 872 | return String::new(); | ||
| 873 | }; | ||
| 874 | let mut primitives = Vec::new(); | ||
| 875 | append_ink( | ||
| 876 | ink, | ||
| 877 | crate::origin(&ink.layout), | ||
| 878 | [0.0, 0.0, 0.0, 1.0], | ||
| 879 | &mut primitives, | ||
| 880 | ); | ||
| 881 | let (width, height) = (x1 - x0, y1 - y0); | ||
| 882 | let mut svg = format!( | ||
| 883 | "<svg class=ink style='{style}width:{width}pt;height:{height}pt' \ | ||
| 884 | viewBox='{x0} {y0} {width} {height}' role=img aria-label=Drawing>" | ||
| 885 | ); | ||
| 886 | let paint = |color: [f32; 4]| { | ||
| 887 | let [red, green, blue] = draw::srgb_bytes(color); | ||
| 888 | format!("#{red:02X}{green:02X}{blue:02X}' opacity='{}", color[3]) | ||
| 889 | }; | ||
| 890 | let cap = |round: bool| if round { "round" } else { "square" }; | ||
| 891 | for primitive in primitives { | ||
| 892 | match primitive { | ||
| 893 | Primitive::Segment { | ||
| 894 | from, | ||
| 895 | to, | ||
| 896 | width, | ||
| 897 | round, | ||
| 898 | color, | ||
| 899 | } => { | ||
| 900 | let _ = write!( | ||
| 901 | svg, | ||
| 902 | "<line x1='{}' y1='{}' x2='{}' y2='{}' stroke='{}' stroke-width='{width}' \ | ||
| 903 | stroke-linecap='{}'/>", | ||
| 904 | from[0], | ||
| 905 | from[1], | ||
| 906 | to[0], | ||
| 907 | to[1], | ||
| 908 | paint(color), | ||
| 909 | cap(round) | ||
| 910 | ); | ||
| 911 | } | ||
| 912 | Primitive::Taper { | ||
| 913 | from, | ||
| 914 | to, | ||
| 915 | widths, | ||
| 916 | round, | ||
| 917 | color, | ||
| 918 | } => { | ||
| 919 | // A quadrilateral from one width to the other, capped at each end. | ||
| 920 | let [dx, dy] = [to[0] - from[0], to[1] - from[1]]; | ||
| 921 | let length = dx.hypot(dy).max(f32::EPSILON); | ||
| 922 | let [nx, ny] = [-dy / length, dx / length]; | ||
| 923 | let [a, b] = widths.map(|width| width / 2.0); | ||
| 924 | let _ = write!( | ||
| 925 | svg, | ||
| 926 | "<path d='M{} {}L{} {}L{} {}L{} {}Z' fill='{}'/>", | ||
| 927 | from[0] + nx * a, | ||
| 928 | from[1] + ny * a, | ||
| 929 | to[0] + nx * b, | ||
| 930 | to[1] + ny * b, | ||
| 931 | to[0] - nx * b, | ||
| 932 | to[1] - ny * b, | ||
| 933 | from[0] - nx * a, | ||
| 934 | from[1] - ny * a, | ||
| 935 | paint(color) | ||
| 936 | ); | ||
| 937 | if round { | ||
| 938 | for ([x, y], radius) in [(from, a), (to, b)] { | ||
| 939 | let _ = write!( | ||
| 940 | svg, | ||
| 941 | "<circle cx='{x}' cy='{y}' r='{radius}' fill='{}'/>", | ||
| 942 | paint(color) | ||
| 943 | ); | ||
| 944 | } | ||
| 945 | } | ||
| 946 | } | ||
| 947 | Primitive::Highlight { | ||
| 948 | from, | ||
| 949 | to, | ||
| 950 | width, | ||
| 951 | color, | ||
| 952 | } => { | ||
| 953 | let _ = write!( | ||
| 954 | svg, | ||
| 955 | "<line x1='{}' y1='{}' x2='{}' y2='{}' stroke='{}' stroke-width='{width}' \ | ||
| 956 | stroke-linecap='square' style='mix-blend-mode:multiply'/>", | ||
| 957 | from[0], | ||
| 958 | from[1], | ||
| 959 | to[0], | ||
| 960 | to[1], | ||
| 961 | paint(color) | ||
| 962 | ); | ||
| 963 | } | ||
| 964 | _ => {} | ||
| 965 | } | ||
| 966 | } | ||
| 967 | svg.push_str("</svg>"); | ||
| 968 | svg | ||
| 969 | } | ||
| 970 | |||
| 971 | /// The page's rule lines and grid as backgrounds from its margin origin, as the page draws | ||
| 972 | /// them. | ||
| 973 | fn rules(page: &Page) -> String { | ||
| 974 | use crate::{HALF_INCH, MARGIN_RULE, RULE_WIDTH}; | ||
| 975 | use onestore::page::VerticalRule; | ||
| 976 | let Some(lines) = page.rule_lines else { | ||
| 977 | return String::new(); | ||
| 978 | }; | ||
| 979 | let [x, y] = page.margin_origin; | ||
| 980 | let line = |direction: &str, color: u32| { | ||
| 981 | format!( | ||
| 982 | "linear-gradient(to {direction}, {} {RULE_WIDTH}pt, transparent {RULE_WIDTH}pt)", | ||
| 983 | hex(color) | ||
| 984 | ) | ||
| 985 | }; | ||
| 986 | // Each line is centred on its place, as the page draws it. | ||
| 987 | let centred = -RULE_WIDTH / 2.0; | ||
| 988 | let mut images = vec![line("bottom", lines.color)]; | ||
| 989 | let mut sizes = vec![format!("100% {}pt", lines.spacing * HALF_INCH)]; | ||
| 990 | let mut positions = vec![format!("0 {centred}pt")]; | ||
| 991 | let mut repeats = vec!["repeat-y"]; | ||
| 992 | let mut left = 0.0; | ||
| 993 | match lines.vertical { | ||
| 994 | VerticalRule::Margin(color) => { | ||
| 995 | images.push(line("right", color)); | ||
| 996 | sizes.push("100% 100%".into()); | ||
| 997 | positions.push(format!("{}pt 0", x - MARGIN_RULE + centred)); | ||
| 998 | repeats.push("no-repeat"); | ||
| 999 | } | ||
| 1000 | VerticalRule::Grid { spacing, color } => { | ||
| 1001 | let spacing = spacing * HALF_INCH; | ||
| 1002 | // The grid repeats from the margin origin both ways. | ||
| 1003 | left = x - (x / spacing).ceil() * spacing; | ||
| 1004 | images.push(line("right", color)); | ||
| 1005 | sizes.push(format!("{spacing}pt 100%")); | ||
| 1006 | positions.push(format!("{centred}pt 0")); | ||
| 1007 | repeats.push("repeat-x"); | ||
| 1008 | } | ||
| 1009 | } | ||
| 1010 | format!( | ||
| 1011 | "<div class=rules style='left:{left}pt;top:{y}pt;background-image:{};\ | ||
| 1012 | background-size:{};background-position:{};background-repeat:{}'></div>\n", | ||
| 1013 | images.join(","), | ||
| 1014 | sizes.join(","), | ||
| 1015 | positions.join(","), | ||
| 1016 | repeats.join(",") | ||
| 1017 | ) | ||
| 1018 | } | ||
| 1019 | |||
| 1020 | /// A page's title as navigation shows it. | ||
| 1021 | fn shown_title(title: &str) -> String { | ||
| 1022 | match title.trim() { | ||
| 1023 | "" => "Untitled page".to_owned(), | ||
| 1024 | title => title.to_owned(), | ||
| 1025 | } | ||
| 1026 | } | ||
| 1027 | |||
| 1028 | /// The section's folder in the site, its groups' and its own names as path components, unlike | ||
| 1029 | /// any folder `taken` (as `same_name` gives them), which it joins. | ||
| 1030 | fn folder(section: &Section, taken: &mut BTreeSet<String>) -> String { | ||
| 1031 | let path = (section.groups.iter().chain([&section.name])) | ||
| 1032 | .map(|name| component(name)) | ||
| 1033 | .collect::<Vec<_>>() | ||
| 1034 | .join("/"); | ||
| 1035 | let folder = (1..) | ||
| 1036 | .map(|number| match number { | ||
| 1037 | 1 => path.clone(), | ||
| 1038 | number => format!("{path} {number}"), | ||
| 1039 | }) | ||
| 1040 | .find(|folder| !taken.contains(&same_name(folder))) | ||
| 1041 | .expect("some number is free"); | ||
| 1042 | taken.insert(same_name(&folder)); | ||
| 1043 | folder | ||
| 1044 | } | ||
| 1045 | |||
| 1046 | /// `name` as macOS and Windows compare names: case and Unicode composition aside. | ||
| 1047 | fn same_name(name: &str) -> String { | ||
| 1048 | icu_normalizer::ComposingNormalizerBorrowed::new_nfc() | ||
| 1049 | .normalize(name) | ||
| 1050 | .to_lowercase() | ||
| 1051 | } | ||
| 1052 | |||
| 1053 | /// `name` as a file or folder name every system takes, cut short where it is long so that | ||
| 1054 | /// paths nested a few deep stay within Windows' 260 characters. | ||
| 1055 | fn component(name: &str) -> String { | ||
| 1056 | let name: String = name | ||
| 1057 | .chars() | ||
| 1058 | .map(|c| match c { | ||
| 1059 | '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' | '#' | '%' => '-', | ||
| 1060 | c if c.is_control() => ' ', | ||
| 1061 | c => c, | ||
| 1062 | }) | ||
| 1063 | .collect(); | ||
| 1064 | let mut end = name.len().min(48); | ||
| 1065 | while !name.is_char_boundary(end) { | ||
| 1066 | end -= 1; | ||
| 1067 | } | ||
| 1068 | let name = name[..end].trim_matches(|c: char| c.is_whitespace() || c == '.'); | ||
| 1069 | // Windows reserves these names for devices, with or without an extension. | ||
| 1070 | let stem = name | ||
| 1071 | .split('.') | ||
| 1072 | .next() | ||
| 1073 | .unwrap_or_default() | ||
| 1074 | .to_ascii_uppercase(); | ||
| 1075 | let reserved = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL") | ||
| 1076 | || (stem.len() == 4 | ||
| 1077 | && (stem.starts_with("COM") || stem.starts_with("LPT")) | ||
| 1078 | && stem.as_bytes()[3].is_ascii_digit()); | ||
| 1079 | match name { | ||
| 1080 | "" => "Untitled".to_owned(), | ||
| 1081 | name if reserved => match name.split_once('.') { | ||
| 1082 | Some((stem, extension)) => format!("{stem}_.{extension}"), | ||
| 1083 | None => format!("{name}_"), | ||
| 1084 | }, | ||
| 1085 | name => name.to_owned(), | ||
| 1086 | } | ||
| 1087 | } | ||
| 1088 | |||
| 1089 | /// `path` as a URL path: every byte but unreserved characters and `/` percent-encoded. | ||
| 1090 | fn href(path: &str) -> String { | ||
| 1091 | let mut encoded = String::with_capacity(path.len()); | ||
| 1092 | for byte in path.bytes() { | ||
| 1093 | match byte { | ||
| 1094 | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' | b'/' => { | ||
| 1095 | encoded.push(byte as char) | ||
| 1096 | } | ||
| 1097 | byte => { | ||
| 1098 | let _ = write!(encoded, "%{byte:02X}"); | ||
| 1099 | } | ||
| 1100 | } | ||
| 1101 | } | ||
| 1102 | encoded | ||
| 1103 | } | ||
| 1104 | |||
| 1105 | /// Text as HTML shows it, also inside a quoted attribute. | ||
| 1106 | fn text(value: &str) -> String { | ||
| 1107 | escape(value, &mut false) | ||
| 1108 | } | ||
| 1109 | |||
| 1110 | fn hex(color: u32) -> String { | ||
| 1111 | let [red, green, blue] = draw::srgb_bytes(colorref(color)); | ||
| 1112 | format!("#{red:02X}{green:02X}{blue:02X}") | ||
| 1113 | } | ||
| 1114 | |||
| 1115 | fn digest(bytes: &[u8]) -> String { | ||
| 1116 | Sha256::digest(bytes)[..8] | ||
| 1117 | .iter() | ||
| 1118 | .map(|byte| format!("{byte:02x}")) | ||
| 1119 | .collect() | ||
| 1120 | } | ||
| 1121 | |||
| 1122 | #[cfg(test)] | ||
| 1123 | mod tests { | ||
| 1124 | use super::*; | ||
| 1125 | |||
| 1126 | /// A section of a corpus file, listed as the app lists it, and its pages. | ||
| 1127 | fn section(name: &str, groups: &[&str], bytes: &[u8]) -> (Section, Vec<Page>) { | ||
| 1128 | let arena = onestore::Arena::default(); | ||
| 1129 | let mut stored = onestore::Section::open(&arena, bytes.to_vec()).unwrap(); | ||
| 1130 | let (mut listings, mut pages) = (Vec::new(), Vec::new()); | ||
| 1131 | for (space, title, level) in stored.pages().unwrap() { | ||
| 1132 | let page = stored.page(space).unwrap(); | ||
| 1133 | listings.push(Listing { | ||
| 1134 | title, | ||
| 1135 | level, | ||
| 1136 | identity: page.identity, | ||
| 1137 | }); | ||
| 1138 | pages.push(page); | ||
| 1139 | } | ||
| 1140 | let section = Section { | ||
| 1141 | groups: groups.iter().map(|group| (*group).to_owned()).collect(), | ||
| 1142 | name: name.to_owned(), | ||
| 1143 | color: Some(0x00d6a37c), | ||
| 1144 | identity: Some(onestore::Header::parse(&bytes[..1024]).unwrap().file_id), | ||
| 1145 | pages: Some(listings), | ||
| 1146 | }; | ||
| 1147 | (section, pages) | ||
| 1148 | } | ||
| 1149 | |||
| 1150 | /// The site's files, written a section at a time. | ||
| 1151 | fn written(sections: Vec<(Section, Vec<Page>)>) -> BTreeMap<String, Vec<u8>> { | ||
| 1152 | let mut files = BTreeMap::new(); | ||
| 1153 | let mut write = |name: &str, bytes: &[u8]| { | ||
| 1154 | assert!( | ||
| 1155 | files.insert(name.to_owned(), bytes.to_vec()).is_none(), | ||
| 1156 | "{name} written twice" | ||
| 1157 | ); | ||
| 1158 | Ok(()) | ||
| 1159 | }; | ||
| 1160 | let (listed, pages): (Vec<_>, Vec<_>) = sections.into_iter().unzip(); | ||
| 1161 | let mut site = Site::new("Notebook", listed); | ||
| 1162 | let mut engine = TextEngine::default(); | ||
| 1163 | for (section, pages) in pages.into_iter().enumerate() { | ||
| 1164 | for (at, page) in pages.into_iter().enumerate() { | ||
| 1165 | site.page([section, at], page, &mut engine, &mut write) | ||
| 1166 | .unwrap(); | ||
| 1167 | } | ||
| 1168 | } | ||
| 1169 | site.finish(&mut write).unwrap(); | ||
| 1170 | files | ||
| 1171 | } | ||
| 1172 | |||
| 1173 | /// Every `href` and `src` of the site's pages, each with the page holding it. | ||
| 1174 | fn references(files: &BTreeMap<String, Vec<u8>>) -> Vec<(&str, String)> { | ||
| 1175 | let mut references = Vec::new(); | ||
| 1176 | for (name, bytes) in files.iter().filter(|(name, _)| name.ends_with(".html")) { | ||
| 1177 | let page = std::str::from_utf8(bytes).unwrap(); | ||
| 1178 | for attribute in ["href=\"", "src=\""] { | ||
| 1179 | for (at, _) in page.match_indices(attribute) { | ||
| 1180 | let value = &page[at + attribute.len()..]; | ||
| 1181 | let value = &value[..value.find('"').unwrap()]; | ||
| 1182 | references.push((name.as_str(), value.to_owned())); | ||
| 1183 | } | ||
| 1184 | } | ||
| 1185 | } | ||
| 1186 | references | ||
| 1187 | } | ||
| 1188 | |||
| 1189 | /// The site's file `link` from page `name` leads to, and the anchor it names. | ||
| 1190 | fn resolved(name: &str, link: &str) -> (String, Option<String>) { | ||
| 1191 | let (path, anchor) = match link.split_once('#') { | ||
| 1192 | Some((path, anchor)) => (path, Some(anchor.to_owned())), | ||
| 1193 | None => (link, None), | ||
| 1194 | }; | ||
| 1195 | let mut file = std::path::Path::new(name).parent().unwrap().to_path_buf(); | ||
| 1196 | for component in percent_decoded(path).split('/') { | ||
| 1197 | match component { | ||
| 1198 | ".." => assert!(file.pop(), "{name} reaches past the site: {link}"), | ||
| 1199 | component => file.push(component), | ||
| 1200 | } | ||
| 1201 | } | ||
| 1202 | (file.to_str().unwrap().to_owned(), anchor) | ||
| 1203 | } | ||
| 1204 | |||
| 1205 | /// Every page of a notebook with tagged tables, pictures, files and a recording is written, | ||
| 1206 | /// and everything a page or the index points at lies in the site: nothing is asked of a | ||
| 1207 | /// server. | ||
| 1208 | #[test] | ||
| 1209 | fn a_site_holds_everything_its_pages_point_at() { | ||
| 1210 | let sections = vec![ | ||
| 1211 | section( | ||
| 1212 | "Tables", | ||
| 1213 | &[], | ||
| 1214 | include_bytes!("../../../corpus/table-tags/candidate/Tables.one"), | ||
| 1215 | ), | ||
| 1216 | section( | ||
| 1217 | "Features", | ||
| 1218 | &["Group", "Inner"], | ||
| 1219 | include_bytes!("../../../corpus/media-edit/cold/notebook/Features.one"), | ||
| 1220 | ), | ||
| 1221 | ]; | ||
| 1222 | let pages: usize = sections.iter().map(|(_, pages)| pages.len()).sum(); | ||
| 1223 | let files = written(sections); | ||
| 1224 | let html = files.keys().filter(|name| name.ends_with(".html")).count(); | ||
| 1225 | assert_eq!(html, pages + 1); | ||
| 1226 | assert!(files.contains_key("Group/Inner/Features/10 Files and recording.html")); | ||
| 1227 | assert!(files.keys().any(|name| name.starts_with("tags/"))); | ||
| 1228 | assert_eq!( | ||
| 1229 | files.keys().any(|name| name.starts_with("fonts/")), | ||
| 1230 | crate::layout::bundled("Calibri").is_some() | ||
| 1231 | ); | ||
| 1232 | for (name, link) in references(&files) { | ||
| 1233 | if link.contains(':') { | ||
| 1234 | continue; | ||
| 1235 | } | ||
| 1236 | let (path, _) = resolved(name, &link); | ||
| 1237 | assert!(files.contains_key(&path), "{name} points at missing {path}"); | ||
| 1238 | } | ||
| 1239 | // Links may lead out of the site; nothing a page shows comes from outside it. | ||
| 1240 | for (name, bytes) in &files { | ||
| 1241 | let text = String::from_utf8_lossy(bytes); | ||
| 1242 | assert!( | ||
| 1243 | !text.contains("src=\"http") && !text.contains("url(http"), | ||
| 1244 | "{name}" | ||
| 1245 | ); | ||
| 1246 | } | ||
| 1247 | let index = String::from_utf8_lossy(&files["index.html"]); | ||
| 1248 | assert!(index.contains("<h2 class=section"), "{index}"); | ||
| 1249 | assert!(index.contains("<h2>Group</h2>") && index.contains("<h3>Inner</h3>")); | ||
| 1250 | assert!(index.contains("<h4 class=section"), "{index}"); | ||
| 1251 | let page = String::from_utf8_lossy(&files["Tables/01 Check a table.html"]); | ||
| 1252 | assert!(page.contains("<html lang=en>"), "{page}"); | ||
| 1253 | assert!(page.contains("role=heading aria-level=1"), "{page}"); | ||
| 1254 | } | ||
| 1255 | |||
| 1256 | /// Links to a page and a section in the export lead to their files; links into the | ||
| 1257 | /// notebook outside it, or to anything but the web or mail, stay text. | ||
| 1258 | #[test] | ||
| 1259 | fn links_into_the_notebook_lead_to_the_exported_pages() { | ||
| 1260 | let files = written(vec![ | ||
| 1261 | section( | ||
| 1262 | "Internal", | ||
| 1263 | &[], | ||
| 1264 | include_bytes!("../../../corpus/link-edit/internal/candidate/links.one"), | ||
| 1265 | ), | ||
| 1266 | section( | ||
| 1267 | "Native", | ||
| 1268 | &["Group"], | ||
| 1269 | include_bytes!("../../../corpus/link-edit/native-links/notebook/links.one"), | ||
| 1270 | ), | ||
| 1271 | ]); | ||
| 1272 | let mut rewritten = 0; | ||
| 1273 | for (name, link) in references(&files) { | ||
| 1274 | assert!(!link.starts_with("onenote:"), "{name} keeps {link}"); | ||
| 1275 | if link.contains(':') || name == "index.html" { | ||
| 1276 | continue; | ||
| 1277 | } | ||
| 1278 | let (path, _) = resolved(name, &link); | ||
| 1279 | assert!(files.contains_key(&path), "{name} points at missing {path}"); | ||
| 1280 | rewritten += 1; | ||
| 1281 | } | ||
| 1282 | assert!(rewritten > 0); | ||
| 1283 | // The page, paragraph and section links of the native page, beside its page list. | ||
| 1284 | let native = | ||
| 1285 | String::from_utf8_lossy(&files["Group/Native/01 Read about Rust the Rust site.html"]); | ||
| 1286 | for (link, count) in [ | ||
| 1287 | ("02%20Link%20target.html\"", 2), | ||
| 1288 | ("02%20Link%20target.html#p", 1), | ||
| 1289 | ("01%20Read%20about%20Rust%20the%20Rust%20site.html\"", 2), | ||
| 1290 | ] { | ||
| 1291 | assert_eq!(native.matches(link).count(), count, "{link} in {native}"); | ||
| 1292 | } | ||
| 1293 | } | ||
| 1294 | |||
| 1295 | /// A link to a paragraph leads to its anchor on the exported page. | ||
| 1296 | #[test] | ||
| 1297 | fn a_paragraph_link_leads_to_its_anchor() { | ||
| 1298 | use onestore::page::link::{LinkTarget, internal_link}; | ||
| 1299 | let (section, pages) = section( | ||
| 1300 | "Internal", | ||
| 1301 | &[], | ||
| 1302 | include_bytes!("../../../corpus/link-edit/internal/candidate/links.one"), | ||
| 1303 | ); | ||
| 1304 | let paragraph = pages[1] | ||
| 1305 | .objects | ||
| 1306 | .iter() | ||
| 1307 | .find_map(|object| match object { | ||
| 1308 | PageObject::Outline(outline) => outline.paragraphs.first(), | ||
| 1309 | PageObject::Title(title) => title.outlines.first()?.paragraphs.first(), | ||
| 1310 | _ => None, | ||
| 1311 | }) | ||
| 1312 | .unwrap() | ||
| 1313 | .id; | ||
| 1314 | let target = LinkTarget::Object { | ||
| 1315 | identity: pages[1].identity.unwrap(), | ||
| 1316 | title: "", | ||
| 1317 | object: paragraph, | ||
| 1318 | }; | ||
| 1319 | let link = internal_link(section.identity.unwrap(), "", target); | ||
| 1320 | let site = Site::new("Notebook", vec![section]); | ||
| 1321 | let resolved = site.links.link(&link, "../").unwrap(); | ||
| 1322 | assert_eq!( | ||
| 1323 | resolved, | ||
| 1324 | format!("../Internal/02%20Link%20target.html#{}", anchor(paragraph)) | ||
| 1325 | ); | ||
| 1326 | let files = written(vec![self::section( | ||
| 1327 | "Internal", | ||
| 1328 | &[], | ||
| 1329 | include_bytes!("../../../corpus/link-edit/internal/candidate/links.one"), | ||
| 1330 | )]); | ||
| 1331 | let target = String::from_utf8_lossy(&files["Internal/02 Link target.html"]); | ||
| 1332 | assert!(target.contains(&format!("<a id={}>", anchor(paragraph)))); | ||
| 1333 | } | ||
| 1334 | |||
| 1335 | /// A locked section is listed with its name and colour and a note, and has no pages. | ||
| 1336 | #[test] | ||
| 1337 | fn a_locked_section_is_listed_as_locked() { | ||
| 1338 | let files = written(vec![( | ||
| 1339 | Section { | ||
| 1340 | groups: Vec::new(), | ||
| 1341 | name: "Diary".into(), | ||
| 1342 | color: Some(0x000000ff), | ||
| 1343 | identity: None, | ||
| 1344 | pages: None, | ||
| 1345 | }, | ||
| 1346 | Vec::new(), | ||
| 1347 | )]); | ||
| 1348 | let index = String::from_utf8(files["index.html"].clone()).unwrap(); | ||
| 1349 | assert!( | ||
| 1350 | index.contains("<h2 class=section style='border-color:#FF0000'>Diary</h2>"), | ||
| 1351 | "{index}" | ||
| 1352 | ); | ||
| 1353 | assert!(index.contains("<p class=locked>Locked</p>")); | ||
| 1354 | assert_eq!( | ||
| 1355 | files.keys().filter(|name| name.ends_with(".html")).count(), | ||
| 1356 | 1 | ||
| 1357 | ); | ||
| 1358 | } | ||
| 1359 | |||
| 1360 | /// Fonts, link targets, titles and names stored on a page can't put script, handlers or | ||
| 1361 | /// outside requests into its file. | ||
| 1362 | #[test] | ||
| 1363 | fn hostile_strings_in_a_page_stay_inert() { | ||
| 1364 | let (mut listed, mut pages) = section( | ||
| 1365 | "Sec'tion\" <b>", | ||
| 1366 | &["Gro'up"], | ||
| 1367 | include_bytes!("../../../corpus/media-edit/cold/notebook/Features.one"), | ||
| 1368 | ); | ||
| 1369 | let hostile = [ | ||
| 1370 | "Evil' tabindex=1 autofocus onfocus='alert(1)//", | ||
| 1371 | "A B\";background-image:url(https://evil.example/px.png);x:\"", | ||
| 1372 | ]; | ||
| 1373 | let link = |target: &str| { | ||
| 1374 | let code = onestore::document::Format { | ||
| 1375 | hyperlink: Some(true), | ||
| 1376 | hidden: Some(true), | ||
| 1377 | ..Default::default() | ||
| 1378 | }; | ||
| 1379 | let label = onestore::document::Format { | ||
| 1380 | hyperlink: Some(true), | ||
| 1381 | hyperlink_label: Some(true), | ||
| 1382 | ..Default::default() | ||
| 1383 | }; | ||
| 1384 | [ | ||
| 1385 | (format!("\u{fddf}HYPERLINK \"{target}\""), code), | ||
| 1386 | ("label".to_owned(), label), | ||
| 1387 | ] | ||
| 1388 | }; | ||
| 1389 | fn poison( | ||
| 1390 | paragraphs: &mut [PageParagraph], | ||
| 1391 | font: &str, | ||
| 1392 | runs: &[(String, onestore::document::Format)], | ||
| 1393 | ) { | ||
| 1394 | for paragraph in paragraphs { | ||
| 1395 | if let ParagraphContent::Text(text) = &mut paragraph.content { | ||
| 1396 | let mut all: Vec<_> = (text.text.spans().iter()) | ||
| 1397 | .scan(0, |start, span| { | ||
| 1398 | let run = text.text.text()[*start..span.end].to_owned(); | ||
| 1399 | *start = span.end; | ||
| 1400 | let mut format = span.format.clone(); | ||
| 1401 | format.font = Some(font.to_owned()); | ||
| 1402 | Some((run, format)) | ||
| 1403 | }) | ||
| 1404 | .collect(); | ||
| 1405 | all.extend(runs.iter().cloned()); | ||
| 1406 | text.text = onestore::page::text::Paragraph::from_runs(all); | ||
| 1407 | } | ||
| 1408 | } | ||
| 1409 | } | ||
| 1410 | let runs: Vec<_> = [ | ||
| 1411 | "javascript:alert(document.domain)", | ||
| 1412 | "data:text/html,x", | ||
| 1413 | "file:///etc/passwd", | ||
| 1414 | ] | ||
| 1415 | .into_iter() | ||
| 1416 | .flat_map(link) | ||
| 1417 | .collect(); | ||
| 1418 | for (at, page) in pages.iter_mut().enumerate() { | ||
| 1419 | for object in &mut page.objects { | ||
| 1420 | match object { | ||
| 1421 | PageObject::Outline(outline) => { | ||
| 1422 | poison(&mut outline.paragraphs, hostile[at % 2], &runs) | ||
| 1423 | } | ||
| 1424 | PageObject::Image(image) => image.link = Some("javascript:alert(2)".into()), | ||
| 1425 | _ => {} | ||
| 1426 | } | ||
| 1427 | } | ||
| 1428 | } | ||
| 1429 | for listing in listed.pages.iter_mut().flatten() { | ||
| 1430 | listing.title = "it's \"<script>alert(3)</script>".into(); | ||
| 1431 | } | ||
| 1432 | listed.name = "Sec'tion\" <b>".into(); | ||
| 1433 | let files = written(vec![(listed, pages)]); | ||
| 1434 | for (name, bytes) in &files { | ||
| 1435 | if !name.ends_with(".html") { | ||
| 1436 | continue; | ||
| 1437 | } | ||
| 1438 | let html = String::from_utf8_lossy(bytes); | ||
| 1439 | for bad in [ | ||
| 1440 | "onfocus", | ||
| 1441 | "autofocus", | ||
| 1442 | "url(", | ||
| 1443 | "javascript", | ||
| 1444 | "data:text", | ||
| 1445 | "file:", | ||
| 1446 | "<script", | ||
| 1447 | "<b>", | ||
| 1448 | "Evil", | ||
| 1449 | "evil.example", | ||
| 1450 | ] { | ||
| 1451 | assert!(!html.contains(bad), "{bad} in {name}"); | ||
| 1452 | } | ||
| 1453 | } | ||
| 1454 | } | ||
| 1455 | |||
| 1456 | /// Sections whose names a file system would take for the same folder, or refuse, get | ||
| 1457 | /// folders of their own, and deep groups stay short. | ||
| 1458 | #[test] | ||
| 1459 | fn sections_get_folders_of_their_own() { | ||
| 1460 | let named = |groups: &[&str], name: &str| Section { | ||
| 1461 | groups: groups.iter().map(|group| (*group).to_owned()).collect(), | ||
| 1462 | name: name.to_owned(), | ||
| 1463 | color: None, | ||
| 1464 | identity: None, | ||
| 1465 | pages: Some(vec![Listing { | ||
| 1466 | title: "Page".into(), | ||
| 1467 | level: 1, | ||
| 1468 | identity: None, | ||
| 1469 | }]), | ||
| 1470 | }; | ||
| 1471 | let long = "A rather long group name that goes on for quite a while"; | ||
| 1472 | let site = Site::new( | ||
| 1473 | "Notebook", | ||
| 1474 | vec![ | ||
| 1475 | named(&[], "Plans #1"), | ||
| 1476 | named(&[], "plans %1"), | ||
| 1477 | named(&[], "CON"), | ||
| 1478 | named(&[], "com1.txt"), | ||
| 1479 | named(&[], " . . "), | ||
| 1480 | named(&[], "Cafe\u{301}"), | ||
| 1481 | named(&[], "Caf\u{e9}"), | ||
| 1482 | named(&[long, long, long, long], long), | ||
| 1483 | ], | ||
| 1484 | ); | ||
| 1485 | let folders: Vec<&str> = site | ||
| 1486 | .listed | ||
| 1487 | .iter() | ||
| 1488 | .map(|(folder, _)| folder.as_str()) | ||
| 1489 | .collect(); | ||
| 1490 | assert_eq!( | ||
| 1491 | folders[..5], | ||
| 1492 | ["Plans -1", "plans -1 2", "CON_", "com1_.txt", "Untitled"] | ||
| 1493 | ); | ||
| 1494 | assert_eq!(folders[6], "Caf\u{e9} 2"); | ||
| 1495 | assert!(folders[7].len() <= 5 * 49, "{}", folders[7]); | ||
| 1496 | } | ||
| 1497 | |||
| 1498 | /// A page alone is the page as `index.html`, with no header or page list, its pictures, | ||
| 1499 | /// files and fonts beside it. | ||
| 1500 | #[test] | ||
| 1501 | fn a_page_alone_is_the_page_and_nothing_else() { | ||
| 1502 | let (mut section, mut pages) = section( | ||
| 1503 | "Features", | ||
| 1504 | &["Group"], | ||
| 1505 | include_bytes!("../../../corpus/media-edit/cold/notebook/Features.one"), | ||
| 1506 | ); | ||
| 1507 | let page = pages.remove(0); | ||
| 1508 | section.pages.as_mut().unwrap().truncate(1); | ||
| 1509 | let mut files = BTreeMap::new(); | ||
| 1510 | let mut write = |name: &str, bytes: &[u8]| { | ||
| 1511 | files.insert(name.to_owned(), bytes.to_vec()); | ||
| 1512 | Ok(()) | ||
| 1513 | }; | ||
| 1514 | let mut site = Site::page_alone("Notebook", section); | ||
| 1515 | site.page([0, 0], page, &mut TextEngine::default(), &mut write) | ||
| 1516 | .unwrap(); | ||
| 1517 | site.finish(&mut write).unwrap(); | ||
| 1518 | let html = String::from_utf8_lossy(&files["index.html"]); | ||
| 1519 | assert!( | ||
| 1520 | !html.contains("<header>") && !html.contains("<nav"), | ||
| 1521 | "{html}" | ||
| 1522 | ); | ||
| 1523 | assert!(html.contains("<main class=page"), "{html}"); | ||
| 1524 | assert!(html.contains("href=\"style.css\""), "{html}"); | ||
| 1525 | assert!(files.keys().any(|name| name.starts_with("files/"))); | ||
| 1526 | assert!( | ||
| 1527 | files | ||
| 1528 | .keys() | ||
| 1529 | .all(|name| !name.ends_with(".html") || name == "index.html") | ||
| 1530 | ); | ||
| 1531 | for (name, link) in references(&files) { | ||
| 1532 | if !link.contains(':') { | ||
| 1533 | let (path, _) = resolved(name, &link); | ||
| 1534 | assert!(files.contains_key(&path), "{name} points at missing {path}"); | ||
| 1535 | } | ||
| 1536 | } | ||
| 1537 | } | ||
| 1538 | |||
| 1539 | fn percent_decoded(link: &str) -> String { | ||
| 1540 | let bytes = link.as_bytes(); | ||
| 1541 | let mut decoded = Vec::new(); | ||
| 1542 | let mut at = 0; | ||
| 1543 | while at < bytes.len() { | ||
| 1544 | if bytes[at] == b'%' { | ||
| 1545 | decoded.push(u8::from_str_radix(&link[at + 1..at + 3], 16).unwrap()); | ||
| 1546 | at += 3; | ||
| 1547 | } else { | ||
| 1548 | decoded.push(bytes[at]); | ||
| 1549 | at += 1; | ||
| 1550 | } | ||
| 1551 | } | ||
| 1552 | String::from_utf8(decoded).unwrap() | ||
| 1553 | } | ||
| 1554 | } | ||
crates/notebook/src/lib.rs+5| ... | @@ -417,6 +417,11 @@ impl Replica { | ... | @@ -417,6 +417,11 @@ impl Replica { |
| 417 | self.ask(|reply| working::Request::Pages { reply }) | 417 | self.ask(|reply| working::Request::Pages { reply }) |
| 418 | } | 418 | } |
| 419 | 419 | ||
| 420 | /// Each page's notebook-management identity, which internal links name. | ||
| 421 | pub fn identities(&self) -> Result<Vec<(ExGuid, Option<[u8; 16]>)>> { | ||
| 422 | self.ask(|reply| working::Request::Identities { reply }) | ||
| 423 | } | ||
| 424 | |||
| 420 | /// The conflict pages of each page that has them (`onestore::Section::conflicts`). | 425 | /// The conflict pages of each page that has them (`onestore::Section::conflicts`). |
| 421 | pub fn conflicts(&self) -> Result<Vec<(ExGuid, Vec<onestore::ConflictPage>)>> { | 426 | pub fn conflicts(&self) -> Result<Vec<(ExGuid, Vec<onestore::ConflictPage>)>> { |
| 422 | self.ask(|reply| working::Request::Conflicts { reply }) | 427 | self.ask(|reply| working::Request::Conflicts { reply }) |
crates/notebook/src/session.rs+5| ... | @@ -2995,6 +2995,11 @@ impl Section { | ... | @@ -2995,6 +2995,11 @@ impl Section { |
| 2995 | self.replica.page(space) | 2995 | self.replica.page(space) |
| 2996 | } | 2996 | } |
| 2997 | 2997 | ||
| 2998 | /// Each page's notebook-management identity, which internal links name. | ||
| 2999 | pub fn identities(&self) -> Result<Vec<(ExGuid, Option<[u8; 16]>)>> { | ||
| 3000 | self.replica.identities() | ||
| 3001 | } | ||
| 3002 | |||
| 2998 | /// Copies a page (usually from another section) to the end of this section under | 3003 | /// Copies a page (usually from another section) to the end of this section under |
| 2999 | /// fresh identities, queued like the user's own edits. Returns the new page's space. | 3004 | /// fresh identities, queued like the user's own edits. Returns the new page's space. |
| 3000 | /// Content outside the model refuses to copy. | 3005 | /// Content outside the model refuses to copy. |
crates/notebook/src/working.rs+6| ... | @@ -36,6 +36,9 @@ pub(crate) enum Request { | ... | @@ -36,6 +36,9 @@ pub(crate) enum Request { |
| 36 | Pages { | 36 | Pages { |
| 37 | reply: Reply<Vec<(ExGuid, String, u32)>>, | 37 | reply: Reply<Vec<(ExGuid, String, u32)>>, |
| 38 | }, | 38 | }, |
| 39 | Identities { | ||
| 40 | reply: Reply<Vec<(ExGuid, Option<[u8; 16]>)>>, | ||
| 41 | }, | ||
| 39 | Conflicts { | 42 | Conflicts { |
| 40 | reply: Reply<Vec<(ExGuid, Vec<onestore::ConflictPage>)>>, | 43 | reply: Reply<Vec<(ExGuid, Vec<onestore::ConflictPage>)>>, |
| 41 | }, | 44 | }, |
| ... | @@ -123,6 +126,7 @@ impl Request { | ... | @@ -123,6 +126,7 @@ impl Request { |
| 123 | Self::Apply(Accepted { reply, .. }) => reply(Err(error())), | 126 | Self::Apply(Accepted { reply, .. }) => reply(Err(error())), |
| 124 | Self::Page { reply, .. } => reply(Err(error())), | 127 | Self::Page { reply, .. } => reply(Err(error())), |
| 125 | Self::Pages { reply } => reply(Err(error())), | 128 | Self::Pages { reply } => reply(Err(error())), |
| 129 | Self::Identities { reply } => reply(Err(error())), | ||
| 126 | Self::Conflicts { reply } => reply(Err(error())), | 130 | Self::Conflicts { reply } => reply(Err(error())), |
| 127 | Self::Versions { reply } => reply(Err(error())), | 131 | Self::Versions { reply } => reply(Err(error())), |
| 128 | Self::Version { reply, .. } => reply(Err(error())), | 132 | Self::Version { reply, .. } => reply(Err(error())), |
| ... | @@ -814,6 +818,7 @@ impl<'a> Working<'a> { | ... | @@ -814,6 +818,7 @@ impl<'a> Working<'a> { |
| 814 | } | 818 | } |
| 815 | Request::Page { .. } | 819 | Request::Page { .. } |
| 816 | | Request::Pages { .. } | 820 | | Request::Pages { .. } |
| 821 | | Request::Identities { .. } | ||
| 817 | | Request::Conflicts { .. } | 822 | | Request::Conflicts { .. } |
| 818 | | Request::Versions { .. } | 823 | | Request::Versions { .. } |
| 819 | | Request::Version { .. } | 824 | | Request::Version { .. } |
| ... | @@ -881,6 +886,7 @@ impl<'a> Working<'a> { | ... | @@ -881,6 +886,7 @@ impl<'a> Working<'a> { |
| 881 | match request { | 886 | match request { |
| 882 | Request::Page { space, reply } => reply(self.section.page(space).map_err(Into::into)), | 887 | Request::Page { space, reply } => reply(self.section.page(space).map_err(Into::into)), |
| 883 | Request::Pages { reply } => reply(self.section.pages().map_err(Into::into)), | 888 | Request::Pages { reply } => reply(self.section.pages().map_err(Into::into)), |
| 889 | Request::Identities { reply } => reply(self.section.identities().map_err(Into::into)), | ||
| 884 | Request::Conflicts { reply } => reply(self.section.conflicts().map_err(Into::into)), | 890 | Request::Conflicts { reply } => reply(self.section.conflicts().map_err(Into::into)), |
| 885 | Request::Versions { reply } => reply(self.section.versions().map_err(Into::into)), | 891 | Request::Versions { reply } => reply(self.section.versions().map_err(Into::into)), |
| 886 | Request::Version { | 892 | Request::Version { |
crates/onestore/src/page/mod.rs+6| ... | @@ -778,6 +778,12 @@ impl Page { | ... | @@ -778,6 +778,12 @@ impl Page { |
| 778 | .roots | 778 | .roots |
| 779 | .get(&2) | 779 | .get(&2) |
| 780 | .and_then(|id| revision.nodes.get(id)) | 780 | .and_then(|id| revision.nodes.get(id)) |
| 781 | .and_then(Self::metadata_identity) | ||
| 782 | } | ||
| 783 | |||
| 784 | /// The identity page metadata element `metadata` holds. | ||
| 785 | pub(crate) fn metadata_identity(metadata: &Element<'_>) -> Option<[u8; 16]> { | ||
| 786 | Some(metadata) | ||
| 781 | .filter(|node| matches!(node.kind, Kind::Metadata { .. })) | 787 | .filter(|node| matches!(node.kind, Kind::Metadata { .. })) |
| 782 | .and_then(|node| node.extra.first()) | 788 | .and_then(|node| node.extra.first()) |
| 783 | .and_then(|fields| fields.iter().find(|field| field.id == 0x1c001c30)) | 789 | .and_then(|fields| fields.iter().find(|field| field.id == 0x1c001c30)) |
crates/onestore/src/section.rs+42| ... | @@ -451,6 +451,34 @@ impl<'a> Section<'a> { | ... | @@ -451,6 +451,34 @@ impl<'a> Section<'a> { |
| 451 | .collect()) | 451 | .collect()) |
| 452 | } | 452 | } |
| 453 | 453 | ||
| 454 | /// Each listed page's notebook-management identity, which internal links name, read | ||
| 455 | /// from its metadata alone. | ||
| 456 | pub fn identities(&mut self) -> Result<Vec<(ExGuid, Option<[u8; 16]>)>> { | ||
| 457 | let spaces: Vec<ExGuid> = self.series()?.into_keys().collect(); | ||
| 458 | let mut identities = Vec::new(); | ||
| 459 | for space in spaces { | ||
| 460 | let revision = self.revision(space)?; | ||
| 461 | let identity = match (revision.roots.get(&2)).and_then(|id| revision.objects.get(id)) { | ||
| 462 | Some(metadata) => { | ||
| 463 | let metadata = crate::document::Element::parse_with( | ||
| 464 | metadata, | ||
| 465 | FileType::Section, | ||
| 466 | &mut |_| { | ||
| 467 | Err(Error { | ||
| 468 | offset: 0, | ||
| 469 | message: "Page metadata holds no payload", | ||
| 470 | }) | ||
| 471 | }, | ||
| 472 | )?; | ||
| 473 | crate::page::Page::metadata_identity(&metadata) | ||
| 474 | } | ||
| 475 | None => None, | ||
| 476 | }; | ||
| 477 | identities.push((space, identity)); | ||
| 478 | } | ||
| 479 | Ok(identities) | ||
| 480 | } | ||
| 481 | |||
| 454 | /// Page spaces in section order with the title and outline level (1 at the top) the | 482 | /// Page spaces in section order with the title and outline level (1 at the top) the |
| 455 | /// page list shows, read from each page's metadata alone. | 483 | /// page list shows, read from each page's metadata alone. |
| 456 | pub fn pages(&mut self) -> Result<Vec<(ExGuid, String, u32)>> { | 484 | pub fn pages(&mut self) -> Result<Vec<(ExGuid, String, u32)>> { |
| ... | @@ -1210,6 +1238,20 @@ mod tests { | ... | @@ -1210,6 +1238,20 @@ mod tests { |
| 1210 | const { std::cell::Cell::new(None) }; | 1238 | const { std::cell::Cell::new(None) }; |
| 1211 | } | 1239 | } |
| 1212 | 1240 | ||
| 1241 | /// Page identities read from metadata alone are those the whole page holds. | ||
| 1242 | #[test] | ||
| 1243 | fn identities_are_those_the_pages_hold() { | ||
| 1244 | let bytes = include_bytes!("../../../corpus/link-edit/native-links/notebook/links.one"); | ||
| 1245 | let arena = Arena::default(); | ||
| 1246 | let mut section = Section::open(&arena, bytes.to_vec()).unwrap(); | ||
| 1247 | let identities = section.identities().unwrap(); | ||
| 1248 | assert_eq!(identities.len(), section.pages().unwrap().len()); | ||
| 1249 | for (space, identity) in identities { | ||
| 1250 | assert!(identity.is_some()); | ||
| 1251 | assert_eq!(identity, section.page(space).unwrap().identity); | ||
| 1252 | } | ||
| 1253 | } | ||
| 1254 | |||
| 1213 | /// `f` with `fresh_guid` counting from `seed`. | 1255 | /// `f` with `fresh_guid` counting from `seed`. |
| 1214 | fn seeded<T>(seed: u64, f: impl FnOnce() -> T) -> T { | 1256 | fn seeded<T>(seed: u64, f: impl FnOnce() -> T) -> T { |
| 1215 | let outer = GUIDS.replace(Some(seed)); | 1257 | let outer = GUIDS.replace(Some(seed)); |
crates/snowbound/src/art.rs+1| ... | @@ -120,6 +120,7 @@ pub const CUSTOMIZE_TAGS: &[&str] = art!("icons/tag", "icons/badge-edit"); | ... | @@ -120,6 +120,7 @@ pub const CUSTOMIZE_TAGS: &[&str] = art!("icons/tag", "icons/badge-edit"); |
| 120 | pub const DELETE: &[&str] = art!("icons/delete"); | 120 | pub const DELETE: &[&str] = art!("icons/delete"); |
| 121 | pub const EMPTY_RECYCLE_BIN: &[&str] = art!("icons/recycle-bin", "icons/badge-remove"); | 121 | pub const EMPTY_RECYCLE_BIN: &[&str] = art!("icons/recycle-bin", "icons/badge-remove"); |
| 122 | pub const EXPORT_PDF: &[&str] = art!("icons/pdf"); | 122 | pub const EXPORT_PDF: &[&str] = art!("icons/pdf"); |
| 123 | pub const EXPORT_WEBSITE: &[&str] = art!("icons/page", "icons/badge-link"); | ||
| 123 | pub const FAST_FORWARD: &[&str] = art!("icons/fast-forward"); | 124 | pub const FAST_FORWARD: &[&str] = art!("icons/fast-forward"); |
| 124 | pub const FIND: &[&str] = art!("icons/page", "icons/badge-search"); | 125 | pub const FIND: &[&str] = art!("icons/page", "icons/badge-search"); |
| 125 | pub const FULL_PAGE: &[&str] = art!("icons/full-page"); | 126 | pub const FULL_PAGE: &[&str] = art!("icons/full-page"); |
crates/snowbound/src/commands.rs+13-1| ... | @@ -49,6 +49,8 @@ pub enum Id { | ... | @@ -49,6 +49,8 @@ pub enum Id { |
| 49 | ShowUnread, | 49 | ShowUnread, |
| 50 | NextUnread, | 50 | NextUnread, |
| 51 | ExportPdf, | 51 | ExportPdf, |
| 52 | /// Save As on the notebook as a website. | ||
| 53 | ExportWebsite, | ||
| 52 | Print, | 54 | Print, |
| 53 | Undo, | 55 | Undo, |
| 54 | Redo, | 56 | Redo, |
| ... | @@ -328,6 +330,7 @@ pub const COMMANDS: &[Command] = &[ | ... | @@ -328,6 +330,7 @@ pub const COMMANDS: &[Command] = &[ |
| 328 | ), | 330 | ), |
| 329 | row!(Id::NextUnread, "Next Unread", NONE, NONE), | 331 | row!(Id::NextUnread, "Next Unread", NONE, NONE), |
| 330 | row!(Id::ExportPdf, "Export as PDF", NONE, NONE), | 332 | row!(Id::ExportPdf, "Export as PDF", NONE, NONE), |
| 333 | row!(Id::ExportWebsite, "Export as Website", NONE, NONE), | ||
| 331 | // Go to takes OneNote's Ctrl+P, and Pause its Ctrl+Alt+P. | 334 | // Go to takes OneNote's Ctrl+P, and Pause its Ctrl+Alt+P. |
| 332 | row!( | 335 | row!( |
| 333 | Id::Print, | 336 | Id::Print, |
| ... | @@ -1143,7 +1146,8 @@ impl State { | ... | @@ -1143,7 +1146,8 @@ impl State { |
| 1143 | || self.printing.open() | 1146 | || self.printing.open() |
| 1144 | || self.link.is_some() | 1147 | || self.link.is_some() |
| 1145 | || self.tag_list.is_some() | 1148 | || self.tag_list.is_some() |
| 1146 | || self.server.is_some(); | 1149 | || self.server.is_some() |
| 1150 | || self.exporting.is_some(); | ||
| 1147 | #[cfg(any(windows, target_os = "linux"))] | 1151 | #[cfg(any(windows, target_os = "linux"))] |
| 1148 | let modal = modal || self.prompt.strong_count() != 0; | 1152 | let modal = modal || self.prompt.strong_count() != 0; |
| 1149 | let page = (session.is_some() || self.temporary) && !modal; | 1153 | let page = (session.is_some() || self.temporary) && !modal; |
| ... | @@ -1219,6 +1223,9 @@ impl State { | ... | @@ -1219,6 +1223,9 @@ impl State { |
| 1219 | Id::LiveShare => enabled(false), | 1223 | Id::LiveShare => enabled(false), |
| 1220 | Id::PasswordProtect => enabled(!modal && self.shown_section().is_some()), | 1224 | Id::PasswordProtect => enabled(!modal && self.shown_section().is_some()), |
| 1221 | Id::SaveAs => enabled(!modal && self.notebook().is_some()), | 1225 | Id::SaveAs => enabled(!modal && self.notebook().is_some()), |
| 1226 | Id::ExportWebsite => { | ||
| 1227 | enabled(!modal && cfg!(not(target_arch = "wasm32")) && self.notebook().is_some()) | ||
| 1228 | } | ||
| 1222 | Id::RecycleBin => Status { | 1229 | Id::RecycleBin => Status { |
| 1223 | enabled: !modal | 1230 | enabled: !modal |
| 1224 | && self | 1231 | && self |
| ... | @@ -1595,6 +1602,11 @@ impl State { | ... | @@ -1595,6 +1602,11 @@ impl State { |
| 1595 | self.open_save_as(library, None, scope); | 1602 | self.open_save_as(library, None, scope); |
| 1596 | return Ok(()); | 1603 | return Ok(()); |
| 1597 | } | 1604 | } |
| 1605 | Id::ExportWebsite => { | ||
| 1606 | let library = Arc::clone(self.notebook().ok_or("No notebook is open")?); | ||
| 1607 | self.open_export_website(library); | ||
| 1608 | return Ok(()); | ||
| 1609 | } | ||
| 1598 | Id::RecycleBin | Id::EmptyRecycleBin | Id::MarkNotebookRead | Id::ShowUnread => { | 1610 | Id::RecycleBin | Id::EmptyRecycleBin | Id::MarkNotebookRead | Id::ShowUnread => { |
| 1599 | let library = Arc::clone(self.notebook().ok_or("No notebook is open")?); | 1611 | let library = Arc::clone(self.notebook().ok_or("No notebook is open")?); |
| 1600 | match id { | 1612 | match id { |
crates/snowbound/src/main.rs+5| ... | @@ -999,6 +999,8 @@ struct State { | ... | @@ -999,6 +999,8 @@ struct State { |
| 999 | symbols: Option<symbol::Symbols>, | 999 | symbols: Option<symbol::Symbols>, |
| 1000 | /// Save As while it is open. | 1000 | /// Save As while it is open. |
| 1001 | save_as: Option<save_as::Dialog>, | 1001 | save_as: Option<save_as::Dialog>, |
| 1002 | /// The website export under way, which a dialog shows. | ||
| 1003 | exporting: Option<Arc<save_as::Exporting>>, | ||
| 1002 | /// Unpack Notebook while it is open. | 1004 | /// Unpack Notebook while it is open. |
| 1003 | unpacking: Option<unpack::Dialog>, | 1005 | unpacking: Option<unpack::Dialog>, |
| 1004 | /// Snowbound's own dialogs, first the one shown, where the desktop has none. | 1006 | /// Snowbound's own dialogs, first the one shown, where the desktop has none. |
| ... | @@ -1491,6 +1493,7 @@ impl State { | ... | @@ -1491,6 +1493,7 @@ impl State { |
| 1491 | properties: None, | 1493 | properties: None, |
| 1492 | symbols: None, | 1494 | symbols: None, |
| 1493 | save_as: None, | 1495 | save_as: None, |
| 1496 | exporting: None, | ||
| 1494 | unpacking: None, | 1497 | unpacking: None, |
| 1495 | #[cfg(target_os = "linux")] | 1498 | #[cfg(target_os = "linux")] |
| 1496 | asking: Default::default(), | 1499 | asking: Default::default(), |
| ... | @@ -1750,6 +1753,7 @@ impl State { | ... | @@ -1750,6 +1753,7 @@ impl State { |
| 1750 | self.properties_dialog(); | 1753 | self.properties_dialog(); |
| 1751 | self.symbols_dialog(); | 1754 | self.symbols_dialog(); |
| 1752 | self.save_as_dialog(); | 1755 | self.save_as_dialog(); |
| 1756 | self.exporting_dialog(); | ||
| 1753 | self.unpack_dialog(); | 1757 | self.unpack_dialog(); |
| 1754 | self.password_dialog()?; | 1758 | self.password_dialog()?; |
| 1755 | #[cfg(target_os = "linux")] | 1759 | #[cfg(target_os = "linux")] |
| ... | @@ -6393,6 +6397,7 @@ fn artwork(id: commands::Id) -> Option<&'static [&'static str]> { | ... | @@ -6393,6 +6397,7 @@ fn artwork(id: commands::Id) -> Option<&'static [&'static str]> { |
| 6393 | Cmd::ShowUnread => art::SHOW_UNREAD, | 6397 | Cmd::ShowUnread => art::SHOW_UNREAD, |
| 6394 | Cmd::NextUnread => art::NEXT_UNREAD, | 6398 | Cmd::NextUnread => art::NEXT_UNREAD, |
| 6395 | Cmd::ExportPdf => art::EXPORT_PDF, | 6399 | Cmd::ExportPdf => art::EXPORT_PDF, |
| 6400 | Cmd::ExportWebsite => art::EXPORT_WEBSITE, | ||
| 6396 | Cmd::Print => art::PRINT, | 6401 | Cmd::Print => art::PRINT, |
| 6397 | Cmd::SelectAll => art::SELECT_ALL, | 6402 | Cmd::SelectAll => art::SELECT_ALL, |
| 6398 | Cmd::Find => art::FIND, | 6403 | Cmd::Find => art::FIND, |
crates/snowbound/src/menubar.rs+1| ... | @@ -83,6 +83,7 @@ const MENUS: &[Item] = &[ | ... | @@ -83,6 +83,7 @@ const MENUS: &[Item] = &[ |
| 83 | S, | 83 | S, |
| 84 | C(Id::SaveAs), | 84 | C(Id::SaveAs), |
| 85 | C(Id::ExportPdf), | 85 | C(Id::ExportPdf), |
| 86 | C(Id::ExportWebsite), | ||
| 86 | S, | 87 | S, |
| 87 | C(Id::Print), | 88 | C(Id::Print), |
| 88 | ], | 89 | ], |
crates/snowbound/src/print.rs+14-11| ... | @@ -2,7 +2,11 @@ | ... | @@ -2,7 +2,11 @@ |
| 2 | //! preview, then the chosen pages laid on paper as OneNote prints them (`canvas::print`), | 2 | //! preview, then the chosen pages laid on paper as OneNote prints them (`canvas::print`), |
| 3 | //! handed to the system's printing or saved. | 3 | //! handed to the system's printing or saved. |
| 4 | 4 | ||
| 5 | use crate::{State, UserEvent, library::Library, platform, printer}; | 5 | use crate::{ |
| 6 | State, UserEvent, | ||
| 7 | library::{Library, Tab}, | ||
| 8 | platform, printer, | ||
| 9 | }; | ||
| 6 | use accesskit::Role; | 10 | use accesskit::Role; |
| 7 | use canvas::print::Footer; | 11 | use canvas::print::Footer; |
| 8 | use notebook::discover::Folder; | 12 | use notebook::discover::Folder; |
| ... | @@ -347,7 +351,7 @@ impl State { | ... | @@ -347,7 +351,7 @@ impl State { |
| 347 | this.into_iter().collect() | 351 | this.into_iter().collect() |
| 348 | } else { | 352 | } else { |
| 349 | let mut sections = Vec::new(); | 353 | let mut sections = Vec::new(); |
| 350 | for (path, name) in others { | 354 | for Tab { path, name, .. } in others { |
| 351 | if path == open_tab.0 | 355 | if path == open_tab.0 |
| 352 | && let Some(open) = this.take() | 356 | && let Some(open) = this.take() |
| 353 | { | 357 | { |
| ... | @@ -422,15 +426,14 @@ fn group(levels: &[u32], at: usize) -> std::ops::Range<usize> { | ... | @@ -422,15 +426,14 @@ fn group(levels: &[u32], at: usize) -> std::ops::Range<usize> { |
| 422 | start..end | 426 | start..end |
| 423 | } | 427 | } |
| 424 | 428 | ||
| 425 | /// Every readable section of `library` but the recycle bin's, catalog path and name, in the | 429 | /// Every readable section of `library` but the recycle bin's, in the order each folder's TOC |
| 426 | /// order each folder's TOC lists its sections and groups, as OneNote's notebook PDF prints them. | 430 | /// lists its sections and groups, as OneNote's notebook PDF prints them. |
| 427 | fn notebook_tabs(library: &Library) -> Vec<(String, String)> { | 431 | pub(crate) fn notebook_tabs(library: &Library) -> Vec<Tab> { |
| 428 | fn walk(library: &Library, folder: &Folder, tabs: &mut Vec<(String, String)>) { | 432 | fn walk(library: &Library, folder: &Folder, tabs: &mut Vec<Tab>) { |
| 429 | let mut sections = library.tabs(&folder.path); | 433 | let mut sections = library.tabs(&folder.path); |
| 430 | for path in &folder.order { | 434 | for path in &folder.order { |
| 431 | if let Some(at) = sections.iter().position(|tab| tab.path == *path) { | 435 | if let Some(at) = sections.iter().position(|tab| tab.path == *path) { |
| 432 | let tab = sections.remove(at); | 436 | tabs.push(sections.remove(at)); |
| 433 | tabs.push((tab.path, tab.name)); | ||
| 434 | } else if let Some(group) = (folder.groups.iter()) | 437 | } else if let Some(group) = (folder.groups.iter()) |
| 435 | .find(|group| group.path == *path && !crate::library::recycle_bin(&group.path)) | 438 | .find(|group| group.path == *path && !crate::library::recycle_bin(&group.path)) |
| 436 | { | 439 | { |
| ... | @@ -441,7 +444,7 @@ fn notebook_tabs(library: &Library) -> Vec<(String, String)> { | ... | @@ -441,7 +444,7 @@ fn notebook_tabs(library: &Library) -> Vec<(String, String)> { |
| 441 | let mut tabs = Vec::new(); | 444 | let mut tabs = Vec::new(); |
| 442 | match library.catalog() { | 445 | match library.catalog() { |
| 443 | Some(catalog) => walk(library, catalog, &mut tabs), | 446 | Some(catalog) => walk(library, catalog, &mut tabs), |
| 444 | None => tabs.extend(library.tabs("").into_iter().map(|tab| (tab.path, tab.name))), | 447 | None => tabs.extend(library.tabs("")), |
| 445 | } | 448 | } |
| 446 | tabs | 449 | tabs |
| 447 | } | 450 | } |
| ... | @@ -570,7 +573,7 @@ mod tests { | ... | @@ -570,7 +573,7 @@ mod tests { |
| 570 | library.close_kept(); | 573 | library.close_kept(); |
| 571 | drop(library); | 574 | drop(library); |
| 572 | let _ = notebook::fs::remove_dir_all(&temporary); | 575 | let _ = notebook::fs::remove_dir_all(&temporary); |
| 573 | let paths: Vec<&str> = tabs.iter().map(|(path, _)| path.as_str()).collect(); | 576 | let paths: Vec<&str> = tabs.iter().map(|tab| tab.path.as_str()).collect(); |
| 574 | assert_eq!(paths, ["A.one", "G/C.one", "B.one"]); | 577 | assert_eq!(paths, ["A.one", "G/C.one", "B.one"]); |
| 575 | } | 578 | } |
| 576 | 579 | ||
| ... | @@ -631,7 +634,7 @@ mod tests { | ... | @@ -631,7 +634,7 @@ mod tests { |
| 631 | let library = Library::created(root.to_str().unwrap(), notebook, &cache); | 634 | let library = Library::created(root.to_str().unwrap(), notebook, &cache); |
| 632 | let paths: Vec<String> = notebook_tabs(&library) | 635 | let paths: Vec<String> = notebook_tabs(&library) |
| 633 | .into_iter() | 636 | .into_iter() |
| 634 | .map(|(path, _)| path) | 637 | .map(|tab| tab.path) |
| 635 | .collect(); | 638 | .collect(); |
| 636 | notebook::fs::remove_dir_all(&temporary).unwrap(); | 639 | notebook::fs::remove_dir_all(&temporary).unwrap(); |
| 637 | assert_eq!(paths, ["New Section 1.one", "Group/Inner.one"]); | 640 | assert_eq!(paths, ["New Section 1.one", "Group/Inner.one"]); |
crates/snowbound/src/save_as.rs+494-10| ... | @@ -1,11 +1,15 @@ | ... | @@ -1,11 +1,15 @@ |
| 1 | //! File, Save As, as OneNote 2010's: the page, its section or its notebook, as a OneNote | 1 | //! File, Save As, as OneNote 2010's: the page, its section or its notebook, as a OneNote |
| 2 | //! section (`.one`), a package (`.onepkg`) or a PDF. A page or section saved as a section is | 2 | //! section (`.one`), a package (`.onepkg`), a PDF or a website. A page or section saved as a |
| 3 | //! a copy outside any notebook; a notebook's package holds its sections as they stand here, | 3 | //! section is a copy outside any notebook; a notebook's package holds its sections as they |
| 4 | //! the open one's queued edits included (`notebook::package`). | 4 | //! stand here, the open one's queued edits included (`notebook::package`). A website is a |
| 5 | //! folder of web pages (`canvas::site`), offered where OneNote offers its Single File Web Page. | ||
| 5 | 6 | ||
| 6 | use crate::{Library, State, UserEvent, platform, print}; | 7 | use crate::{Library, State, UserEvent, platform, print}; |
| 7 | use accesskit::Role; | 8 | use accesskit::Role; |
| 8 | use notebook::package; | 9 | use notebook::package; |
| 10 | use onestore::{ExGuid, page::Page}; | ||
| 11 | use std::path::{Path, PathBuf}; | ||
| 12 | use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; | ||
| 9 | use std::{error::Error, sync::Arc}; | 13 | use std::{error::Error, sync::Arc}; |
| 10 | use ui::{Anchor, Axis, Id, Spec, children, fill, popup::Item, px}; | 14 | use ui::{Anchor, Axis, Id, Spec, children, fill, popup::Item, px}; |
| 11 | use winit::keyboard::NamedKey; | 15 | use winit::keyboard::NamedKey; |
| ... | @@ -24,20 +28,35 @@ const SCOPES: [(Scope, &str); 3] = [ | ... | @@ -24,20 +28,35 @@ const SCOPES: [(Scope, &str); 3] = [ |
| 24 | (Scope::Notebook, "Notebook"), | 28 | (Scope::Notebook, "Notebook"), |
| 25 | ]; | 29 | ]; |
| 26 | 30 | ||
| 27 | /// OneNote 2010's formats for each scope, as Save As lists them. | 31 | /// The formats for each scope, as Save As lists them: OneNote 2010's, then a website, which |
| 28 | fn formats(scope: Scope) -> [(&'static str, &'static str); 2] { | 32 | /// has no extension, being a folder. |
| 29 | match scope { | 33 | fn formats(scope: Scope) -> &'static [(&'static str, &'static str)] { |
| 30 | Scope::Notebook => [ | 34 | let formats: &[_] = match scope { |
| 35 | Scope::Notebook => &[ | ||
| 31 | ("OneNote Package (*.onepkg)", "onepkg"), | 36 | ("OneNote Package (*.onepkg)", "onepkg"), |
| 32 | ("PDF (*.pdf)", "pdf"), | 37 | ("PDF (*.pdf)", "pdf"), |
| 38 | ("Website (folder)", ""), | ||
| 33 | ], | 39 | ], |
| 34 | _ => [ | 40 | _ => &[ |
| 35 | ("OneNote 2010 Section (*.one)", "one"), | 41 | ("OneNote 2010 Section (*.one)", "one"), |
| 36 | ("PDF (*.pdf)", "pdf"), | 42 | ("PDF (*.pdf)", "pdf"), |
| 43 | ("Website (folder)", ""), | ||
| 37 | ], | 44 | ], |
| 45 | }; | ||
| 46 | // A browser keeps what it saves in its own storage, where a website is no use. | ||
| 47 | match cfg!(target_arch = "wasm32") { | ||
| 48 | true => &formats[..formats.len() - 1], | ||
| 49 | false => formats, | ||
| 38 | } | 50 | } |
| 39 | } | 51 | } |
| 40 | 52 | ||
| 53 | /// Where `formats` lists the website for `scope`, where it does. | ||
| 54 | fn website(scope: Scope) -> Option<usize> { | ||
| 55 | formats(scope) | ||
| 56 | .iter() | ||
| 57 | .position(|(_, extension)| extension.is_empty()) | ||
| 58 | } | ||
| 59 | |||
| 41 | /// The dialog's choices while it is open: the section a scope of Section saves, by catalog | 60 | /// The dialog's choices while it is open: the section a scope of Section saves, by catalog |
| 42 | /// path, and the place in `formats` chosen. | 61 | /// path, and the place in `formats` chosen. |
| 43 | pub struct Dialog { | 62 | pub struct Dialog { |
| ... | @@ -73,6 +92,14 @@ impl State { | ... | @@ -73,6 +92,14 @@ impl State { |
| 73 | self.ui.open_popup(id()); | 92 | self.ui.open_popup(id()); |
| 74 | } | 93 | } |
| 75 | 94 | ||
| 95 | /// Opens Save As on `library`'s notebook as a website, as Export as Website does. | ||
| 96 | pub(crate) fn open_export_website(&mut self, library: Arc<Library>) { | ||
| 97 | self.open_save_as(library, None, Scope::Notebook); | ||
| 98 | if let Some(dialog) = &mut self.save_as { | ||
| 99 | dialog.format = website(Scope::Notebook).unwrap_or_default(); | ||
| 100 | } | ||
| 101 | } | ||
| 102 | |||
| 76 | /// Builds Save As while it is open; Save As… asks where, then writes on a thread. | 103 | /// Builds Save As while it is open; Save As… asks where, then writes on a thread. |
| 77 | pub(crate) fn save_as_dialog(&mut self) { | 104 | pub(crate) fn save_as_dialog(&mut self) { |
| 78 | let Some(dialog) = &mut self.save_as else { | 105 | let Some(dialog) = &mut self.save_as else { |
| ... | @@ -128,9 +155,11 @@ impl State { | ... | @@ -128,9 +155,11 @@ impl State { |
| 128 | let names: Vec<&str> = offered.iter().map(|(_, name)| *name).collect(); | 155 | let names: Vec<&str> = offered.iter().map(|(_, name)| *name).collect(); |
| 129 | if let Some(at) = choose(ui, "Save current", &names, current.unwrap_or(0)) { | 156 | if let Some(at) = choose(ui, "Save current", &names, current.unwrap_or(0)) { |
| 130 | dialog.scope = offered[at].0; | 157 | dialog.scope = offered[at].0; |
| 131 | dialog.format = 0; | ||
| 132 | } | 158 | } |
| 133 | let names = formats(dialog.scope).map(|(name, _)| name); | 159 | let names: Vec<&str> = formats(dialog.scope) |
| 160 | .iter() | ||
| 161 | .map(|(name, _)| *name) | ||
| 162 | .collect(); | ||
| 134 | if let Some(at) = choose(ui, "Format", &names, dialog.format) { | 163 | if let Some(at) = choose(ui, "Format", &names, dialog.format) { |
| 135 | dialog.format = at; | 164 | dialog.format = at; |
| 136 | } | 165 | } |
| ... | @@ -153,6 +182,9 @@ impl State { | ... | @@ -153,6 +182,9 @@ impl State { |
| 153 | /// goes through Export as PDF's settings. | 182 | /// goes through Export as PDF's settings. |
| 154 | fn save(&mut self, dialog: Dialog) -> Result<(), Box<dyn Error>> { | 183 | fn save(&mut self, dialog: Dialog) -> Result<(), Box<dyn Error>> { |
| 155 | let (_, extension) = formats(dialog.scope)[dialog.format]; | 184 | let (_, extension) = formats(dialog.scope)[dialog.format]; |
| 185 | if extension.is_empty() { | ||
| 186 | return self.export_website(dialog); | ||
| 187 | } | ||
| 156 | if extension == "pdf" { | 188 | if extension == "pdf" { |
| 157 | self.export_pdf(match dialog.scope { | 189 | self.export_pdf(match dialog.scope { |
| 158 | Scope::Page => print::Scope::Page, | 190 | Scope::Page => print::Scope::Page, |
| ... | @@ -233,6 +265,398 @@ impl State { | ... | @@ -233,6 +265,398 @@ impl State { |
| 233 | } | 265 | } |
| 234 | } | 266 | } |
| 235 | 267 | ||
| 268 | /// Where an exported section's pages are read from: the open page as the editor holds it, a | ||
| 269 | /// replica open already, or the section opened anew, at most one at a time. | ||
| 270 | enum Source { | ||
| 271 | Page(Page), | ||
| 272 | /// A replica, and the page the editor holds of it. | ||
| 273 | Replica(Arc<notebook::Replica>, Option<(ExGuid, Page)>), | ||
| 274 | Section(String), | ||
| 275 | } | ||
| 276 | |||
| 277 | /// A source made readable: for `Source::Section`, the replica a parked pane holds of it, or | ||
| 278 | /// the section opened anew and closed when this is dropped. | ||
| 279 | enum Reader<'a> { | ||
| 280 | Source(&'a Source), | ||
| 281 | Held(Arc<notebook::Replica>), | ||
| 282 | Section(notebook::session::Section), | ||
| 283 | } | ||
| 284 | |||
| 285 | impl Reader<'_> { | ||
| 286 | /// Each page's space, title and level, and the identity links name it by. | ||
| 287 | fn listing(&self) -> Result<Vec<(ExGuid, canvas::site::Listing)>, Box<dyn Error>> { | ||
| 288 | let (pages, identities) = match self { | ||
| 289 | Self::Source(Source::Page(page)) => { | ||
| 290 | let listing = canvas::site::Listing { | ||
| 291 | title: page.title.clone(), | ||
| 292 | level: 1, | ||
| 293 | identity: page.identity, | ||
| 294 | }; | ||
| 295 | return Ok(vec![(ExGuid::default(), listing)]); | ||
| 296 | } | ||
| 297 | Self::Source(Source::Replica(replica, _)) | Self::Held(replica) => { | ||
| 298 | (replica.pages()?, replica.identities()?) | ||
| 299 | } | ||
| 300 | Self::Section(section) => (section.pages()?, section.identities()?), | ||
| 301 | Self::Source(Source::Section(_)) => unreachable!("Sections are opened to be read"), | ||
| 302 | }; | ||
| 303 | let identities: std::collections::BTreeMap<_, _> = identities.into_iter().collect(); | ||
| 304 | Ok((pages.into_iter()) | ||
| 305 | .map(|(space, title, level)| { | ||
| 306 | let identity = identities.get(&space).copied().flatten(); | ||
| 307 | let listing = canvas::site::Listing { | ||
| 308 | title, | ||
| 309 | level, | ||
| 310 | identity, | ||
| 311 | }; | ||
| 312 | (space, listing) | ||
| 313 | }) | ||
| 314 | .collect()) | ||
| 315 | } | ||
| 316 | |||
| 317 | fn page(&self, space: ExGuid) -> Result<Page, Box<dyn Error>> { | ||
| 318 | Ok(match self { | ||
| 319 | Self::Source(Source::Page(page)) => page.clone(), | ||
| 320 | Self::Source(Source::Replica(_, Some((open, page)))) if *open == space => page.clone(), | ||
| 321 | Self::Source(Source::Replica(replica, _)) | Self::Held(replica) => { | ||
| 322 | replica.page(space)? | ||
| 323 | } | ||
| 324 | Self::Section(section) => section.page(space)?, | ||
| 325 | Self::Source(Source::Section(_)) => unreachable!("Sections are opened to be read"), | ||
| 326 | }) | ||
| 327 | } | ||
| 328 | } | ||
| 329 | |||
| 330 | impl Source { | ||
| 331 | /// The source made readable; a section opens once, so one that `held`, the parked panes' | ||
| 332 | /// replicas, holds is read from there. | ||
| 333 | async fn reader( | ||
| 334 | &self, | ||
| 335 | library: &Library, | ||
| 336 | held: &[(String, Arc<notebook::Replica>)], | ||
| 337 | ) -> Result<Reader<'_>, Box<dyn Error>> { | ||
| 338 | Ok(match self { | ||
| 339 | Self::Section(path) => match held.iter().find(|(held, _)| held == path) { | ||
| 340 | Some((_, replica)) => Reader::Held(Arc::clone(replica)), | ||
| 341 | None => Reader::Section(library.open_async(path, || {}).await?), | ||
| 342 | }, | ||
| 343 | source => Reader::Source(source), | ||
| 344 | }) | ||
| 345 | } | ||
| 346 | } | ||
| 347 | |||
| 348 | /// A website export under way: the pages listed and written, and whether it was cancelled. | ||
| 349 | #[derive(Default)] | ||
| 350 | pub struct Exporting { | ||
| 351 | listed: AtomicBool, | ||
| 352 | written: AtomicUsize, | ||
| 353 | pages: AtomicUsize, | ||
| 354 | cancelled: AtomicBool, | ||
| 355 | } | ||
| 356 | |||
| 357 | fn exporting_id() -> Id { | ||
| 358 | Id::ROOT.child("exporting") | ||
| 359 | } | ||
| 360 | |||
| 361 | /// Why a website can't go in `folder`: inside a notebook, whose table of contents lies in a | ||
| 362 | /// folder holding it however the path reaches it, or holding files already. | ||
| 363 | fn unfit(folder: &Path) -> Option<&'static str> { | ||
| 364 | let existing = folder.ancestors().find(|path| path.exists())?; | ||
| 365 | let resolved = notebook::fs::canonicalize(existing).unwrap_or_else(|_| existing.to_owned()); | ||
| 366 | let notebook = |dir: &Path| { | ||
| 367 | notebook::fs::read_dir(dir).is_ok_and(|entries| { | ||
| 368 | entries.flatten().any(|entry| { | ||
| 369 | (entry.path().extension()) | ||
| 370 | .is_some_and(|extension| extension.eq_ignore_ascii_case("onetoc2")) | ||
| 371 | }) | ||
| 372 | }) | ||
| 373 | }; | ||
| 374 | if resolved.ancestors().any(notebook) { | ||
| 375 | return Some("A website can't go in a notebook's folder."); | ||
| 376 | } | ||
| 377 | notebook::fs::read_dir(folder) | ||
| 378 | .is_ok_and(|mut entries| entries.next().is_some()) | ||
| 379 | .then_some("A website needs a folder of its own, and this one already holds files.") | ||
| 380 | } | ||
| 381 | |||
| 382 | /// Removes what an export wrote, files and then the folders it made, deepest first, leaving | ||
| 383 | /// whatever else they hold. | ||
| 384 | fn remove_written(written: &[PathBuf]) { | ||
| 385 | for path in written.iter().rev() { | ||
| 386 | let _ = if path.is_dir() { | ||
| 387 | notebook::fs::remove_dir(path) | ||
| 388 | } else { | ||
| 389 | notebook::fs::remove_file(path) | ||
| 390 | }; | ||
| 391 | } | ||
| 392 | } | ||
| 393 | |||
| 394 | impl State { | ||
| 395 | /// Asks where to put the website `dialog` chose, then reads its pages and writes the site's | ||
| 396 | /// folder on a thread of its own, a page at a time, showing how far it has got: the open page | ||
| 397 | /// as the editor holds it, the rest as stored. Password-protected sections are listed as | ||
| 398 | /// locked, unlocked here or not, as a website is for publishing. | ||
| 399 | fn export_website(&mut self, dialog: Dialog) -> Result<(), Box<dyn Error>> { | ||
| 400 | if self.exporting.is_some() { | ||
| 401 | return Err("A website is being exported already.".into()); | ||
| 402 | } | ||
| 403 | let library = dialog.library; | ||
| 404 | let open = match (self.session.as_ref()) | ||
| 405 | .filter(|session| Arc::ptr_eq(&session.library, &library)) | ||
| 406 | { | ||
| 407 | Some(session) => Some(( | ||
| 408 | session.tabs[session.tab].path.clone(), | ||
| 409 | Arc::clone(session.section.replica()), | ||
| 410 | self.pane.showing.space, | ||
| 411 | self.pane.view.editor.page()?, | ||
| 412 | )), | ||
| 413 | None => None, | ||
| 414 | }; | ||
| 415 | let scope = dialog.scope; | ||
| 416 | let section = dialog.section.unwrap_or_default(); | ||
| 417 | let (title, tabs) = match scope { | ||
| 418 | Scope::Notebook => (library.name.clone(), print::notebook_tabs(&library)), | ||
| 419 | _ => { | ||
| 420 | if library.protected(&section) { | ||
| 421 | return Err("A password-protected section isn't published as a website.".into()); | ||
| 422 | } | ||
| 423 | let tab = (library | ||
| 424 | .tabs(crate::menus::folder(&section).as_str()) | ||
| 425 | .into_iter()) | ||
| 426 | .find(|tab| tab.path == section) | ||
| 427 | .ok_or("No section is open")?; | ||
| 428 | let title = match (scope, &open) { | ||
| 429 | (Scope::Page, Some((.., page))) => page.title.clone(), | ||
| 430 | (Scope::Page, None) => return Err("No page is open".into()), | ||
| 431 | _ => tab.name.clone(), | ||
| 432 | }; | ||
| 433 | (title, vec![tab]) | ||
| 434 | } | ||
| 435 | }; | ||
| 436 | // Sections parked panes show are open already, and read from their replicas. | ||
| 437 | let held = self.held(&library.location); | ||
| 438 | let (listed, sources): (Vec<_>, Vec<_>) = (tabs.into_iter()) | ||
| 439 | .map(|tab| { | ||
| 440 | let source = match &open { | ||
| 441 | _ if library.protected(&tab.path) => None, | ||
| 442 | Some((path, _, _, page)) if *path == tab.path && scope == Scope::Page => { | ||
| 443 | Some(Source::Page(page.clone())) | ||
| 444 | } | ||
| 445 | Some((path, replica, space, page)) if *path == tab.path => Some( | ||
| 446 | Source::Replica(Arc::clone(replica), Some((*space, page.clone()))), | ||
| 447 | ), | ||
| 448 | _ => Some(Source::Section(tab.path.clone())), | ||
| 449 | }; | ||
| 450 | let mut groups: Vec<String> = tab.path.split('/').map(str::to_owned).collect(); | ||
| 451 | groups.pop(); | ||
| 452 | let section = canvas::site::Section { | ||
| 453 | groups, | ||
| 454 | name: tab.name, | ||
| 455 | color: tab.color, | ||
| 456 | identity: library.section_identity(&tab.path), | ||
| 457 | pages: None, | ||
| 458 | }; | ||
| 459 | (section, source) | ||
| 460 | }) | ||
| 461 | .unzip(); | ||
| 462 | let name = print::file_name(&title); | ||
| 463 | let reply = self.reply(move |state, folder: PathBuf| { | ||
| 464 | if let Some(unfit) = unfit(&folder) { | ||
| 465 | platform::alert("Choose a new folder", unfit); | ||
| 466 | return Ok(()); | ||
| 467 | } | ||
| 468 | let progress = Arc::new(Exporting::default()); | ||
| 469 | state.exporting = Some(Arc::clone(&progress)); | ||
| 470 | state.ui.open_popup(exporting_id()); | ||
| 471 | let (layouts, proxy) = (Arc::clone(&state.layouts), state.proxy.clone()); | ||
| 472 | crate::spawn_async(move || async move { | ||
| 473 | let written = std::cell::RefCell::new(Vec::new()); | ||
| 474 | let exported = async { | ||
| 475 | let cancelled = || progress.cancelled.load(Ordering::Relaxed); | ||
| 476 | // First what each section lists, which its metadata alone gives, so that | ||
| 477 | // links between pages lead where they will be written. | ||
| 478 | let mut spaces = Vec::new(); | ||
| 479 | let mut listed = listed; | ||
| 480 | for (section, source) in listed.iter_mut().zip(&sources) { | ||
| 481 | if cancelled() { | ||
| 482 | return Ok(()); | ||
| 483 | } | ||
| 484 | let mut kept = Vec::new(); | ||
| 485 | if let Some(source) = source { | ||
| 486 | let listing = source.reader(&library, &held).await?.listing()?; | ||
| 487 | progress.pages.fetch_add(listing.len(), Ordering::Relaxed); | ||
| 488 | let (each, listings) = listing.into_iter().unzip(); | ||
| 489 | kept = each; | ||
| 490 | section.pages = Some(listings); | ||
| 491 | } | ||
| 492 | spaces.push(kept); | ||
| 493 | } | ||
| 494 | progress.listed.store(true, Ordering::Relaxed); | ||
| 495 | let _ = proxy.send_event(UserEvent::Redraw); | ||
| 496 | // The page in view keeps its own layout engine while this one works. | ||
| 497 | let mut engine = layouts.lock().map_err(|_| "Page layout failed")?.clone(); | ||
| 498 | let mut write = |name: &str, bytes: &[u8]| { | ||
| 499 | let path = folder.join(name); | ||
| 500 | let parent = path.parent().unwrap_or(&folder); | ||
| 501 | let mut made: Vec<PathBuf> = (parent.ancestors()) | ||
| 502 | .take_while(|dir| !dir.exists()) | ||
| 503 | .map(Path::to_owned) | ||
| 504 | .collect(); | ||
| 505 | made.reverse(); | ||
| 506 | notebook::fs::create_dir_all(parent)?; | ||
| 507 | written.borrow_mut().extend(made); | ||
| 508 | notebook::fs::write(&path, bytes)?; | ||
| 509 | written.borrow_mut().push(path); | ||
| 510 | Ok(()) | ||
| 511 | }; | ||
| 512 | // A page goes alone, without the notebook's header and page list. | ||
| 513 | let mut site = match scope { | ||
| 514 | Scope::Page => canvas::site::Site::page_alone( | ||
| 515 | &title, | ||
| 516 | listed.into_iter().next().ok_or("No page is open")?, | ||
| 517 | ), | ||
| 518 | _ => canvas::site::Site::new(&title, listed), | ||
| 519 | }; | ||
| 520 | for (at, (source, spaces)) in sources.iter().zip(spaces).enumerate() { | ||
| 521 | let Some(source) = source else { | ||
| 522 | continue; | ||
| 523 | }; | ||
| 524 | // Each section opened is closed once its pages are written. | ||
| 525 | let reader = source.reader(&library, &held).await?; | ||
| 526 | for (page, space) in spaces.into_iter().enumerate() { | ||
| 527 | if cancelled() { | ||
| 528 | return Ok(()); | ||
| 529 | } | ||
| 530 | site.page([at, page], reader.page(space)?, &mut engine, &mut write)?; | ||
| 531 | progress.written.fetch_add(1, Ordering::Relaxed); | ||
| 532 | let _ = proxy.send_event(UserEvent::Redraw); | ||
| 533 | } | ||
| 534 | } | ||
| 535 | site.finish(&mut write)?; | ||
| 536 | Ok::<_, Box<dyn Error>>(()) | ||
| 537 | } | ||
| 538 | .await; | ||
| 539 | let cancelled = progress.cancelled.load(Ordering::Relaxed); | ||
| 540 | if cancelled || exported.is_err() { | ||
| 541 | remove_written(&written.borrow()); | ||
| 542 | } | ||
| 543 | let exported = exported.map_err(|error| crate::plain(&*error, "file")); | ||
| 544 | let _ = proxy.send_event(UserEvent::Then(Box::new(move |state| { | ||
| 545 | state.exporting = None; | ||
| 546 | state.ui.close_popup(exporting_id()); | ||
| 547 | match exported { | ||
| 548 | Ok(()) if !cancelled => { | ||
| 549 | // A replay leaves the file manager alone. | ||
| 550 | #[cfg(not(target_arch = "wasm32"))] | ||
| 551 | if !crate::automated() { | ||
| 552 | platform::show_file(&folder.join("index.html")); | ||
| 553 | } | ||
| 554 | } | ||
| 555 | Ok(()) => {} | ||
| 556 | Err(error) => { | ||
| 557 | platform::alert("Couldn't export the website", &error); | ||
| 558 | return Err(error.into()); | ||
| 559 | } | ||
| 560 | } | ||
| 561 | Ok(()) | ||
| 562 | }))); | ||
| 563 | }); | ||
| 564 | Ok(()) | ||
| 565 | }); | ||
| 566 | platform::pick_new("Export as Website", &name, "Export", None, reply); | ||
| 567 | Ok(()) | ||
| 568 | } | ||
| 569 | |||
| 570 | /// Shows how far a website export has got while it runs; Cancel stops it. | ||
| 571 | pub(crate) fn exporting_dialog(&mut self) { | ||
| 572 | let Some(progress) = &self.exporting else { | ||
| 573 | return; | ||
| 574 | }; | ||
| 575 | let ui = &mut self.ui; | ||
| 576 | // Only Cancel stops an export: a press beside the dialog, which closes popups, or | ||
| 577 | // Escape leaves it running. | ||
| 578 | if !ui.popup_open(exporting_id()) { | ||
| 579 | ui.open_popup(exporting_id()); | ||
| 580 | } | ||
| 581 | let theme = ui.theme.clone(); | ||
| 582 | let (written, pages) = ( | ||
| 583 | progress.written.load(Ordering::Relaxed), | ||
| 584 | progress.pages.load(Ordering::Relaxed), | ||
| 585 | ); | ||
| 586 | ui.open_as( | ||
| 587 | exporting_id(), | ||
| 588 | Spec { | ||
| 589 | axis: Axis::Y, | ||
| 590 | size: [px(320.0), children()], | ||
| 591 | fill: Some(theme.popup), | ||
| 592 | border: Some(theme.chip), | ||
| 593 | shadow: Some(theme.shadow), | ||
| 594 | radius: 8.0, | ||
| 595 | pad: [16.0, 12.0], | ||
| 596 | gap: 8.0, | ||
| 597 | anchor: Some(Anchor::Dialog), | ||
| 598 | role: Some(Role::Dialog), | ||
| 599 | ..Spec::default() | ||
| 600 | }, | ||
| 601 | ); | ||
| 602 | if let Some(node) = ui.access(exporting_id()) { | ||
| 603 | node.set_label("Exporting Website"); | ||
| 604 | } | ||
| 605 | ui.leaf( | ||
| 606 | "title", | ||
| 607 | Spec { | ||
| 608 | size: [fill(), px(theme.font_size * 2.0)], | ||
| 609 | text: Some("Exporting Website"), | ||
| 610 | bold: true, | ||
| 611 | role: Some(Role::Heading), | ||
| 612 | ..Spec::default() | ||
| 613 | }, | ||
| 614 | ); | ||
| 615 | let status = match progress.listed.load(Ordering::Relaxed) { | ||
| 616 | false => "Listing pages…".to_owned(), | ||
| 617 | true => format!("Page {} of {pages}", (written + 1).min(pages.max(1))), | ||
| 618 | }; | ||
| 619 | ui.leaf( | ||
| 620 | "status", | ||
| 621 | Spec { | ||
| 622 | size: [fill(), px(theme.font_size * 1.5)], | ||
| 623 | text: Some(&status), | ||
| 624 | color: Some(theme.text_dim), | ||
| 625 | ..Spec::default() | ||
| 626 | }, | ||
| 627 | ); | ||
| 628 | let bar = ui.id("bar"); | ||
| 629 | ui.open_as( | ||
| 630 | bar, | ||
| 631 | Spec { | ||
| 632 | size: [fill(), px(6.0)], | ||
| 633 | fill: Some(theme.chip), | ||
| 634 | radius: 3.0, | ||
| 635 | role: Some(Role::ProgressIndicator), | ||
| 636 | ..Spec::default() | ||
| 637 | }, | ||
| 638 | ); | ||
| 639 | let fraction = written as f32 / pages.max(1) as f32; | ||
| 640 | let width = ui.laid_out(bar).map_or(0.0, |rect| rect[2] - rect[0]); | ||
| 641 | ui.mark([0.0, 0.0, width * fraction, 6.0], theme.accent, 3.0); | ||
| 642 | if let Some(node) = ui.access(bar) { | ||
| 643 | node.set_label("Export progress"); | ||
| 644 | node.set_min_numeric_value(0.0); | ||
| 645 | node.set_max_numeric_value(100.0); | ||
| 646 | node.set_numeric_value(f64::from((fraction * 100.0).round())); | ||
| 647 | } | ||
| 648 | ui.close(); | ||
| 649 | crate::buttons(ui); | ||
| 650 | let cancel = ui::button(ui, "cancel", "Cancel").clicked; | ||
| 651 | ui.close(); | ||
| 652 | ui.close(); | ||
| 653 | if cancel { | ||
| 654 | progress.cancelled.store(true, Ordering::Relaxed); | ||
| 655 | self.ui.close_popup(exporting_id()); | ||
| 656 | } | ||
| 657 | } | ||
| 658 | } | ||
| 659 | |||
| 236 | fn file_name(path: &std::path::Path) -> String { | 660 | fn file_name(path: &std::path::Path) -> String { |
| 237 | path.file_name() | 661 | path.file_name() |
| 238 | .map(|name| name.to_string_lossy().into_owned()) | 662 | .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 | ... | @@ -275,3 +699,63 @@ fn choose(ui: &mut ui::Ui, label: &str, names: &[&str], current: usize) -> Optio |
| 275 | ui.close(); | 699 | ui.close(); |
| 276 | chosen | 700 | chosen |
| 277 | } | 701 | } |
| 702 | |||
| 703 | #[cfg(test)] | ||
| 704 | mod tests { | ||
| 705 | use super::*; | ||
| 706 | |||
| 707 | /// A website never goes in a notebook, however the folder is reached, nor in a folder | ||
| 708 | /// holding files; a new folder, or an empty one, is fine. | ||
| 709 | #[test] | ||
| 710 | fn a_website_needs_a_folder_outside_every_notebook() { | ||
| 711 | let root = std::env::temp_dir().join(format!("snowbound-unfit-{}", std::process::id())); | ||
| 712 | let _ = notebook::fs::remove_dir_all(&root); | ||
| 713 | let notebook = root.join("Notebook"); | ||
| 714 | notebook::fs::create_dir_all(notebook.join("Group")).unwrap(); | ||
| 715 | notebook::fs::write(notebook.join("Open Notebook.onetoc2"), b"").unwrap(); | ||
| 716 | notebook::fs::create_dir_all(root.join("used")).unwrap(); | ||
| 717 | notebook::fs::write(root.join("used/kept.txt"), b"kept").unwrap(); | ||
| 718 | notebook::fs::create_dir_all(root.join("empty")).unwrap(); | ||
| 719 | #[cfg(unix)] | ||
| 720 | std::os::unix::fs::symlink(&notebook, root.join("link")).unwrap(); | ||
| 721 | assert!(unfit(&notebook.join("Site")).is_some()); | ||
| 722 | assert!(unfit(&notebook.join("Group/New/Site")).is_some()); | ||
| 723 | #[cfg(unix)] | ||
| 724 | assert!(unfit(&root.join("link/Site")).is_some()); | ||
| 725 | assert!(unfit(&root.join("used")).is_some()); | ||
| 726 | assert!(unfit(&root.join("empty")).is_none()); | ||
| 727 | assert!(unfit(&root.join("new/Site")).is_none()); | ||
| 728 | notebook::fs::remove_dir_all(&root).unwrap(); | ||
| 729 | } | ||
| 730 | |||
| 731 | /// Taking back an export removes what it wrote and the folders it made, and leaves | ||
| 732 | /// whatever else they or the folder chosen hold. | ||
| 733 | #[test] | ||
| 734 | fn taking_back_an_export_leaves_what_it_did_not_write() { | ||
| 735 | let root = std::env::temp_dir().join(format!("snowbound-taken-{}", std::process::id())); | ||
| 736 | let _ = notebook::fs::remove_dir_all(&root); | ||
| 737 | notebook::fs::create_dir_all(&root).unwrap(); | ||
| 738 | let written = [ | ||
| 739 | root.join("Section"), | ||
| 740 | root.join("Section/01 Page.html"), | ||
| 741 | root.join("files"), | ||
| 742 | root.join("files/a.png"), | ||
| 743 | root.join("index.html"), | ||
| 744 | ]; | ||
| 745 | for path in &written { | ||
| 746 | if path.extension().is_some() { | ||
| 747 | notebook::fs::write(path, b"").unwrap(); | ||
| 748 | } else { | ||
| 749 | notebook::fs::create_dir_all(path).unwrap(); | ||
| 750 | } | ||
| 751 | } | ||
| 752 | notebook::fs::write(root.join("files/added.txt"), b"added meanwhile").unwrap(); | ||
| 753 | remove_written(&written); | ||
| 754 | let left: Vec<_> = (notebook::fs::read_dir(&root).unwrap()) | ||
| 755 | .map(|entry| entry.unwrap().file_name()) | ||
| 756 | .collect(); | ||
| 757 | assert_eq!(left, ["files"]); | ||
| 758 | assert!(root.join("files/added.txt").is_file()); | ||
| 759 | notebook::fs::remove_dir_all(&root).unwrap(); | ||
| 760 | } | ||
| 761 | } |
crates/snowbound/tests/replay.rs+72| ... | @@ -1863,6 +1863,78 @@ fn escape_closes_save_as() { | ... | @@ -1863,6 +1863,78 @@ fn escape_closes_save_as() { |
| 1863 | assert!(!closed.contains(r#"Dialog "Save As""#), "{closed}"); | 1863 | assert!(!closed.contains(r#"Dialog "Save As""#), "{closed}"); |
| 1864 | } | 1864 | } |
| 1865 | 1865 | ||
| 1866 | /// File > Export as Website through the palette, its Save As taken with Enter and its save | ||
| 1867 | /// panel answered with `site`. | ||
| 1868 | fn export_website(site: &Path) -> Vec<String> { | ||
| 1869 | [ | ||
| 1870 | "modifiers shift command", | ||
| 1871 | "key p", | ||
| 1872 | "modifiers", | ||
| 1873 | "settle", | ||
| 1874 | "type Export as Website", | ||
| 1875 | "settle", | ||
| 1876 | "key Enter", | ||
| 1877 | "settle", | ||
| 1878 | "wait 300", | ||
| 1879 | &format!("answer {}", site.display()), | ||
| 1880 | "key Enter", | ||
| 1881 | "settle", | ||
| 1882 | "wait 500", | ||
| 1883 | "settle", | ||
| 1884 | "accessibility after", | ||
| 1885 | ] | ||
| 1886 | .map(str::to_owned) | ||
| 1887 | .to_vec() | ||
| 1888 | } | ||
| 1889 | |||
| 1890 | /// Export as Website writes every section and page of the notebook into the folder chosen, | ||
| 1891 | /// lists its password-protected sections as locked, and shows no dialog once done. | ||
| 1892 | #[test] | ||
| 1893 | fn a_notebook_exports_as_a_website() { | ||
| 1894 | let scratch = Scratch::new("export-website"); | ||
| 1895 | let notebook = Path::new(env!("CARGO_MANIFEST_DIR")) | ||
| 1896 | .join("../../corpus/protected-sections/candidate/notebook"); | ||
| 1897 | let site = scratch.0.join("site"); | ||
| 1898 | let steps = export_website(&site); | ||
| 1899 | let steps: Vec<&str> = steps.iter().map(String::as_str).collect(); | ||
| 1900 | let [after] = replay(&scratch, Some(&notebook), &steps) | ||
| 1901 | .try_into() | ||
| 1902 | .unwrap(); | ||
| 1903 | assert!(!after.contains("Exporting Website"), "{after}"); | ||
| 1904 | let index = std::fs::read_to_string(site.join("index.html")).unwrap(); | ||
| 1905 | for section in ["New Section 1", "Protected", "Removed", "Changed"] { | ||
| 1906 | assert!( | ||
| 1907 | index.contains(&format!(">{section}<")), | ||
| 1908 | "{section} missing: {index}" | ||
| 1909 | ); | ||
| 1910 | } | ||
| 1911 | assert_eq!( | ||
| 1912 | index.matches("<p class=locked>Locked</p>").count(), | ||
| 1913 | 4, | ||
| 1914 | "{index}" | ||
| 1915 | ); | ||
| 1916 | assert!(site.join("New Section 1/01 Gate.html").is_file()); | ||
| 1917 | assert!(!site.join("Protected").exists()); | ||
| 1918 | } | ||
| 1919 | |||
| 1920 | /// A website never goes into a notebook's folder or a folder already holding files. | ||
| 1921 | #[test] | ||
| 1922 | fn a_website_needs_a_folder_of_its_own() { | ||
| 1923 | let scratch = Scratch::new("export-website-guard"); | ||
| 1924 | let notebook = | ||
| 1925 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus/cross-container/candidate"); | ||
| 1926 | let used = scratch.0.join("used"); | ||
| 1927 | std::fs::create_dir_all(&used).unwrap(); | ||
| 1928 | std::fs::write(used.join("keep.txt"), "kept").unwrap(); | ||
| 1929 | let mut steps = export_website(&scratch.0.join("notebook").join("inside")); | ||
| 1930 | steps.extend(export_website(&used)); | ||
| 1931 | let steps: Vec<&str> = steps.iter().map(String::as_str).collect(); | ||
| 1932 | replay(&scratch, Some(&notebook), &steps); | ||
| 1933 | assert!(!scratch.0.join("notebook/inside").exists()); | ||
| 1934 | let kept: Vec<_> = std::fs::read_dir(&used).unwrap().collect(); | ||
| 1935 | assert_eq!(kept.len(), 1); | ||
| 1936 | } | ||
| 1937 | |||
| 1866 | /// A layout of panes as the settings keep it, on pages of `notebook`'s sections: a pane on | 1938 | /// A layout of panes as the settings keep it, on pages of `notebook`'s sections: a pane on |
| 1867 | /// the first, then a part below it, the second above the third. A page of `None` is gone. | 1939 | /// the first, then a part below it, the second above the third. A page of `None` is gone. |
| 1868 | fn layout(notebook: &Path, panes: [(&str, Option<&str>); 3]) -> serde_json::Value { | 1940 | fn layout(notebook: &Path, panes: [(&str, Option<&str>); 3]) -> serde_json::Value { |