mbook 0.3.5

Read, edit and create mbook files: Markdown chapters and AVIF pictures in one indexed container
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
//! Checking a book and writing it out.

use super::{Book, Chapter, Diagram, Formula, Picture, Slot, Toc, TocItem};
use crate::analysis::{self, Heading, Reference, ReferenceKind};
use crate::container::{self, Writer};
use crate::error::{Error, Problem, ProblemKind, Problems, ResolveError, Result};
use crate::format::{
    KIND_ANCHORS, KIND_DIAGRAM, KIND_FORMULA, KIND_LANDMARKS, KIND_PICTURE, KIND_SERVICE,
    KIND_TEXT, SERVICE_COUNT,
};
use crate::link::{self, Parsed};
use crate::options::{Limits, WriteOptions};
use crate::tables::{self, AnchorRow, LandmarkRow, ResourceRow, Tables, TocRow};
use crate::text;
use std::io::Write;
use std::path::Path;

/// One resource after the five fixed ones.
enum Content<'a> {
    /// The landmarks of the book, with every target resolved.
    Landmarks(Vec<LandmarkRow>),
    /// The anchor table of a chapter, which is the next resource.
    Anchors(&'a Chapter),
    Chapter(&'a Chapter),
    Picture(&'a Picture),
    Diagram(&'a Diagram),
    Formula(&'a Formula),
}

/// What a check works out and writing then uses: the four tables and the
/// resources in file order.
struct Layout<'a> {
    tables: Tables,
    contents: Vec<Content<'a>>,
}

/// A resource number or an offset; both fit once the limits are checked.
fn to_u32(value: usize) -> u32 {
    u32::try_from(value).unwrap_or(u32::MAX)
}

/// A problem that belongs to the book as a whole.
fn whole_book(kind: ProblemKind) -> Problem {
    Problem {
        path: None,
        offset: None,
        kind,
    }
}

/// Checking and saving a book.
impl Book {
    /// Checks the rules that connect the parts of a book, without writing it.
    ///
    /// # Errors
    ///
    /// Every problem found, not only the first: links and pictures that lead
    /// nowhere, raw HTML, a cover that is not in the book, contents items
    /// that do not resolve, a diagram or a formula without a source.
    pub fn check(&self) -> Result<(), Problems> {
        self.layout().map(drop)
    }

    /// Writes the book with the default options.
    ///
    /// # Errors
    ///
    /// As [`write_with`](Self::write_with).
    pub fn write(&self, writer: impl Write) -> Result<()> {
        self.write_with(writer, &WriteOptions::default())
    }

    /// Writes the book as one mbook file.
    ///
    /// The book is checked first, and nothing is written if the check fails.
    /// Writing the same book twice with the same options gives the same
    /// bytes. The landmarks come first, when the book has any, then the
    /// cover, then the chapters in reading order,
    /// each after its anchor table when it has extra anchors, then the other
    /// pictures, the diagrams and the formulas.
    ///
    /// # Errors
    ///
    /// [`Error::Invalid`] with every problem [`check`](Self::check) finds;
    /// the sink fails; a limit of `options` is exceeded.
    pub fn write_with(&self, writer: impl Write, options: &WriteOptions) -> Result<()> {
        let layout = self.layout()?;
        layout.check_limits(&options.limits)?;
        let mut compressor = container::compressor(options)?;
        let mut out = Writer::new(&mut compressor, writer)?;
        out.header()?;
        out.table(&layout.tables.meta_columns()?)?;
        out.table(&layout.tables.resource_columns()?)?;
        out.table(&layout.tables.toc_columns()?)?;
        out.table(&layout.tables.anchor_columns()?)?;
        for content in &layout.contents {
            match content {
                Content::Landmarks(rows) => out.table(&tables::landmark_columns(rows)?)?,
                Content::Anchors(chapter) => {
                    out.table(&tables::chapter_anchor_columns(&chapter.extra_anchors)?)?;
                }
                Content::Chapter(chapter) => out.text(&chapter.text)?,
                Content::Picture(picture) => out.stored(&picture.data)?,
                Content::Diagram(diagram) => out.text(&diagram.source)?,
                Content::Formula(formula) => out.text(&formula.source)?,
            }
        }
        out.finish()
    }

    /// Writes the book to a file.
    ///
    /// The book is written to a temporary file next to `path`, which is then
    /// renamed into place, so an interrupted save leaves the previous file
    /// intact. `path` may be the file the book was loaded from.
    ///
    /// # Errors
    ///
    /// As [`write`](Self::write), or the file cannot be created or renamed.
    pub fn save(&self, path: impl AsRef<Path>) -> Result<()> {
        let path = path.as_ref();
        let folder = path
            .parent()
            .filter(|folder| !folder.as_os_str().is_empty())
            .unwrap_or_else(|| Path::new("."));
        let mut builder = tempfile::Builder::new();
        builder.prefix(".mbook-").suffix(".tmp");
        // A temporary file is private by default; a book is an ordinary
        // file, left to the umask like any other the program creates.
        #[cfg(unix)]
        builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o666));
        // The temporary file removes itself unless it is renamed into place.
        let mut file = builder.tempfile_in(folder)?;
        self.write(file.as_file_mut())?;
        file.as_file().sync_all()?;
        file.persist(path).map_err(|failure| failure.error)?;
        Ok(())
    }

    /// Checks the book and lays it out as it will be written.
    fn layout(&self) -> Result<Layout<'_>, Problems> {
        let mut problems = Vec::new();
        let cover = self.meta.cover().map(|path| match self.slots.get(path) {
            Some(Slot::Picture(index)) => Some(*index),
            _ => None,
        });
        if cover == Some(None) {
            problems.push(whole_book(ProblemKind::MissingCover));
        }
        let cover = cover.flatten();
        // The landmarks, when there are any, take the first number after the
        // fixed resources, and the cover the next; chapters follow in
        // reading order, each after its anchor table when it has one.
        let has_landmarks = !self.landmarks.is_empty();
        let mut next = SERVICE_COUNT + usize::from(has_landmarks) + usize::from(cover.is_some());
        let numbers: Vec<u32> = self
            .chapters
            .iter()
            .map(|chapter| {
                next += usize::from(!chapter.extra_anchors.is_empty());
                next += 1;
                to_u32(next - 1)
            })
            .collect();
        let number_of = |chapter: usize| numbers.get(chapter).copied().unwrap_or(u32::MAX);

        let headings: Vec<Vec<Heading>> = self
            .chapters
            .iter()
            .map(|chapter| self.check_chapter(chapter, &mut problems))
            .collect();
        let toc = match &self.toc {
            Toc::FromHeadings { max_level } => {
                self.toc_from_headings(*max_level, &headings, number_of)
            }
            Toc::Explicit(items) => self.toc_from_items(items, number_of, &mut problems),
        };
        let landmarks = self.landmark_rows(number_of, &mut problems);
        let sources = self
            .diagrams
            .iter()
            .map(|diagram| (&diagram.path, &diagram.source))
            .chain(
                self.formulas
                    .iter()
                    .map(|formula| (&formula.path, &formula.source)),
            );
        for (path, source) in sources {
            check_source(path, source, &mut problems);
        }
        Problems::none_or(problems)?;

        let pictures = || (0..).zip(&self.pictures);
        let contents: Vec<Content<'_>> = has_landmarks
            .then_some(Content::Landmarks(landmarks))
            .into_iter()
            .chain(
                pictures()
                    .filter(|(index, _)| Some(*index) == cover)
                    .map(|(_, picture)| Content::Picture(picture)),
            )
            .chain(self.chapters.iter().flat_map(|chapter| {
                let table = (!chapter.extra_anchors.is_empty()).then_some(chapter);
                table
                    .map(Content::Anchors)
                    .into_iter()
                    .chain([Content::Chapter(chapter)])
            }))
            .chain(
                pictures()
                    .filter(|(index, _)| Some(*index) != cover)
                    .map(|(_, picture)| Content::Picture(picture)),
            )
            .chain(self.diagrams.iter().map(Content::Diagram))
            .chain(self.formulas.iter().map(Content::Formula))
            .collect();
        let service = (0..SERVICE_COUNT).map(|_| ResourceRow {
            kind: KIND_SERVICE,
            path: String::new(),
            width: 0,
            height: 0,
        });
        let tables = Tables {
            meta: self
                .meta
                .iter()
                .map(|(key, value)| (key.to_owned(), value.to_owned()))
                .collect(),
            resources: service.chain(contents.iter().map(Content::row)).collect(),
            toc,
            anchors: (0..)
                .zip(&self.chapters)
                .flat_map(|(index, chapter)| {
                    chapter.anchors.iter().map(move |anchor| AnchorRow {
                        resource: number_of(index),
                        offset: anchor.offset,
                        name: anchor.name.clone(),
                    })
                })
                .collect(),
        };
        Ok(Layout { tables, contents })
    }

    /// Checks the text of one chapter and what it refers to. Returns its
    /// headings, which the table of contents may be built from.
    fn check_chapter(&self, chapter: &Chapter, problems: &mut Vec<Problem>) -> Vec<Heading> {
        let mut report = |offset, kind| {
            problems.push(Problem {
                path: Some(chapter.path.clone()),
                offset: Some(offset),
                kind,
            });
        };
        // Text given through the API is stored clean; a loaded chapter is
        // kept as the file had it.
        if let Some(found) = text::violation(&chapter.text) {
            report(
                to_u32(found.offset),
                ProblemKind::ForbiddenCharacter(found.character),
            );
        }
        let analysis = analysis::analyse(&chapter.text);
        for &offset in &analysis.html {
            report(offset, ProblemKind::RawHtml);
        }
        for reference in &analysis.references {
            if let Some(kind) = self.reference_problem(chapter, reference) {
                report(reference.offset, kind);
            }
        }
        analysis.headings
    }

    /// What is wrong with a link or a picture of a chapter, if anything. A
    /// picture reference may name a diagram or a formula as well.
    fn reference_problem(&self, chapter: &Chapter, reference: &Reference) -> Option<ProblemKind> {
        let destination = || reference.destination.clone();
        let parsed = link::parse(&chapter.path, &reference.destination);
        match (reference.kind, parsed) {
            (ReferenceKind::Link, Ok(Parsed::External)) => None,
            (ReferenceKind::Link, Ok(Parsed::Internal { path, fragment })) => {
                let resolves = self.chapter(&path).is_some_and(|target| {
                    fragment
                        .as_deref()
                        .is_none_or(|name| target.has_anchor(name))
                });
                (!resolves).then(|| ProblemKind::UnresolvedLink(destination()))
            }
            (
                ReferenceKind::Picture,
                Ok(Parsed::Internal {
                    path,
                    fragment: None,
                }),
            ) if self.shows(&path) => None,
            // A picture may not name a network location at all.
            (ReferenceKind::Picture, Ok(Parsed::External))
            | (_, Err(ResolveError::ForbiddenScheme)) => {
                Some(ProblemKind::ForbiddenScheme(destination()))
            }
            (ReferenceKind::Link, Err(_)) => Some(ProblemKind::UnresolvedLink(destination())),
            (ReferenceKind::Picture, _) => Some(ProblemKind::UnresolvedPicture(destination())),
        }
    }

    /// Tells whether a chapter can show what has this path the way it shows
    /// a picture: a picture, a diagram or a formula of the book.
    fn shows(&self, path: &str) -> bool {
        matches!(
            self.slots.get(path),
            Some(Slot::Picture(_) | Slot::Diagram(_) | Slot::Formula(_))
        )
    }

    /// The contents as every heading down to `max_level`.
    ///
    /// Heading levels of the source may skip, so the level of a row is its
    /// depth among the headings that enclose it. A heading inside a chapter
    /// is listed only when it has an anchor, as the format requires.
    fn toc_from_headings(
        &self,
        max_level: u8,
        headings: &[Vec<Heading>],
        number_of: impl Fn(usize) -> u32,
    ) -> Vec<TocRow> {
        let mut rows = Vec::new();
        let mut enclosing: Vec<u8> = Vec::new();
        for (index, (chapter, headings)) in self.chapters.iter().zip(headings).enumerate() {
            for heading in headings {
                let anchored = chapter
                    .anchors
                    .binary_search_by_key(&heading.offset, |anchor| anchor.offset)
                    .is_ok();
                let listed = heading.depth <= max_level
                    && !heading.title.is_empty()
                    && (heading.offset == 0 || anchored);
                if !listed {
                    continue;
                }
                while enclosing
                    .last()
                    .is_some_and(|&depth| depth >= heading.depth)
                {
                    enclosing.pop();
                }
                enclosing.push(heading.depth);
                rows.push(TocRow {
                    level: u8::try_from(enclosing.len()).unwrap_or(u8::MAX),
                    title: heading.title.clone(),
                    resource: number_of(index),
                    offset: heading.offset,
                });
            }
        }
        rows
    }

    /// The contents as given, with every item resolved to a position.
    fn toc_from_items(
        &self,
        items: &[TocItem],
        number_of: impl Fn(usize) -> u32,
        problems: &mut Vec<Problem>,
    ) -> Vec<TocRow> {
        let mut rows = Vec::with_capacity(items.len());
        let mut previous_level = 0u8;
        let mut previous = (0, 0);
        for item in items {
            let mut report = |kind| problems.push(whole_book(kind));
            if item.title.is_empty() {
                report(ProblemKind::EmptyTocTitle);
            }
            if item.level == 0 || item.level > previous_level.saturating_add(1) {
                report(ProblemKind::TocLevel(item.title.clone()));
            }
            previous_level = item.level;
            let Some(position) = self.toc_position(item) else {
                report(ProblemKind::DanglingTocItem(item.title.clone()));
                continue;
            };
            let place = (number_of(position.0), position.1);
            if place < previous {
                report(ProblemKind::TocOrder(item.title.clone()));
            }
            previous = place;
            rows.push(TocRow {
                level: item.level,
                title: item.title.clone(),
                resource: place.0,
                offset: place.1,
            });
        }
        rows
    }

    /// The landmarks with every target resolved to a position. A landmark
    /// leads to a chapter, or to an anchor of it, of a heading or an extra
    /// one.
    fn landmark_rows(
        &self,
        number_of: impl Fn(usize) -> u32,
        problems: &mut Vec<Problem>,
    ) -> Vec<LandmarkRow> {
        let mut rows = Vec::with_capacity(self.landmarks.len());
        for landmark in &self.landmarks {
            let target = match self.slots.get(&landmark.chapter) {
                Some(Slot::Chapter(index)) => self.chapters.get(*index).zip(Some(*index)),
                _ => None,
            };
            let position = target.and_then(|(chapter, index)| {
                let offset = match &landmark.anchor {
                    None => 0,
                    Some(name) => chapter.anchor_offset(name)?,
                };
                Some((index, offset))
            });
            match position {
                Some((index, offset)) => rows.push(LandmarkRow {
                    kind: landmark.kind.clone(),
                    title: landmark.title.clone(),
                    resource: number_of(index),
                    offset,
                }),
                None => problems.push(whole_book(ProblemKind::DanglingLandmark(
                    landmark.kind.clone(),
                ))),
            }
        }
        rows
    }

    /// Where a contents item leads: the index of its chapter and an offset.
    ///
    /// Inside a chapter an item leads to a heading: the format wants a
    /// contents row to match a row of the `anchors` table, which holds the
    /// anchors of headings only.
    fn toc_position(&self, item: &TocItem) -> Option<(usize, u32)> {
        let Some(Slot::Chapter(index)) = self.slots.get(&item.chapter).copied() else {
            return None;
        };
        let offset = match &item.anchor {
            None => 0,
            Some(name) => {
                let anchors = &self.chapters.get(index)?.anchors;
                anchors.iter().find(|anchor| anchor.name == *name)?.offset
            }
        };
        Some((index, offset))
    }
}

/// Checks the source of a diagram or of a formula. One given through the API
/// is stored clean; a loaded one is kept as the file had it.
fn check_source(path: &str, source: &str, problems: &mut Vec<Problem>) {
    let mut report = |offset, kind| {
        problems.push(Problem {
            path: Some(path.to_owned()),
            offset,
            kind,
        });
    };
    if let Some(found) = text::violation(source) {
        report(
            Some(to_u32(found.offset)),
            ProblemKind::ForbiddenCharacter(found.character),
        );
    }
    if source.trim().is_empty() {
        report(None, ProblemKind::EmptySource);
    }
}

impl Content<'_> {
    /// The row of the resource table that describes this resource.
    fn row(&self) -> ResourceRow {
        match self {
            Self::Landmarks(_) => ResourceRow {
                kind: KIND_LANDMARKS,
                path: String::new(),
                width: 0,
                height: 0,
            },
            Self::Anchors(_) => ResourceRow {
                kind: KIND_ANCHORS,
                path: String::new(),
                width: 0,
                height: 0,
            },
            Self::Chapter(chapter) => ResourceRow {
                kind: KIND_TEXT,
                path: chapter.path.clone(),
                width: 0,
                height: 0,
            },
            Self::Picture(picture) => ResourceRow {
                kind: KIND_PICTURE,
                path: picture.path.clone(),
                width: picture.size.width,
                height: picture.size.height,
            },
            Self::Diagram(diagram) => ResourceRow {
                kind: KIND_DIAGRAM,
                path: diagram.path.clone(),
                width: 0,
                height: 0,
            },
            Self::Formula(formula) => ResourceRow {
                kind: KIND_FORMULA,
                path: formula.path.clone(),
                width: 0,
                height: 0,
            },
        }
    }

    /// The decoded size of the resource.
    fn len(&self) -> usize {
        match self {
            // Two 32-bit numbers and two strings for every row.
            Self::Landmarks(rows) => rows
                .iter()
                .map(|row| row.kind.len() + row.title.len() + 8)
                .sum(),
            // One 32-bit offset and one name for every row.
            Self::Anchors(chapter) => chapter
                .extra_anchors
                .iter()
                .map(|anchor| anchor.name.len() + 4)
                .sum(),
            Self::Chapter(chapter) => chapter.text.len(),
            Self::Picture(picture) => picture.data.len(),
            Self::Diagram(diagram) => diagram.source.len(),
            Self::Formula(formula) => formula.source.len(),
        }
    }
}

impl Layout<'_> {
    /// A book must fit the limits it is written with; the size of the file
    /// is watched by the container as it grows.
    fn check_limits(&self, limits: &Limits) -> Result<()> {
        if self.tables.resources.len() > limits.max_resources {
            return Err(Error::Limit("the book has more resources than the limit"));
        }
        let fits = |content: &Content<'_>| {
            u64::try_from(content.len()).is_ok_and(|len| len <= limits.max_resource_bytes)
        };
        if self.contents.iter().all(fits) {
            Ok(())
        } else {
            Err(Error::Limit(
                "a chapter, a table, a picture, a diagram or a formula exceeds the resource limit",
            ))
        }
    }
}