Skip to main content

postext/
commands.rs

1//! The commands of the postext command line: a builder each, made by the
2//! client's method of the same name.
3
4use std::ffi::OsStr;
5use std::fmt::Display;
6
7use serde_json::Value;
8
9use crate::args::{Book, Books, join};
10use crate::client::Postext;
11use crate::command::{Command, Kind, OutMode, ReadsBook, TakesFonts, WritesFile, sealed::Sealed};
12use crate::report::{
13    CheckReport, DesignReport, ImageReport, ImportDocxReport, ImportIdmlReport, InfoReport, Report, UnpackReport,
14};
15
16/// The commands, as types: `Command<'_, kind::Pdf>` builds a `pdf` run.
17pub mod kind {
18    macro_rules! kinds {
19        ($($(#[$m:meta])* $name:ident;)*) => {$(
20            $(#[$m])*
21            #[derive(Debug, Clone, Copy)]
22            pub struct $name;
23        )*};
24    }
25
26    kinds! {
27        /// `postext pdf`
28        Pdf;
29        /// `postext html`
30        Html;
31        /// `postext epub`
32        Epub;
33        /// `postext image`
34        Image;
35        /// `postext images`
36        Images;
37        /// `postext docx`
38        Docx;
39        /// `postext pack`
40        Pack;
41        /// `postext design`
42        Design;
43        /// `postext idml`
44        Idml;
45        /// `postext info`
46        Info;
47        /// `postext check`
48        Check;
49        /// `postext build`
50        Build;
51        /// `postext import-docx`
52        ImportDocx;
53        /// `postext unpack`
54        Unpack;
55        /// `postext import-idml`
56        ImportIdml;
57    }
58}
59
60macro_rules! kind {
61    ($name:ident, $command:literal, $report:ty, $out:ident $(, input = $input:literal)? $(, font_defaults = $fd:literal)?; $($marker:ident),*) => {
62        impl Sealed for kind::$name {}
63        impl Kind for kind::$name {
64            const COMMAND: &'static str = $command;
65            $(const INPUT: &'static str = $input;)?
66            const OUT: OutMode = OutMode::$out;
67            $(const FONT_DEFAULTS: bool = $fd;)?
68            type Report = $report;
69        }
70        $(impl $marker for kind::$name {})*
71    };
72}
73
74kind!(Pdf, "pdf", Report, File; ReadsBook, TakesFonts, WritesFile);
75kind!(Html, "html", Report, File; ReadsBook, TakesFonts, WritesFile);
76kind!(Epub, "epub", Report, File; ReadsBook, TakesFonts, WritesFile);
77kind!(Image, "image", ImageReport, File; ReadsBook, TakesFonts, WritesFile);
78kind!(Images, "images", Report, Required; ReadsBook, TakesFonts);
79kind!(Docx, "docx", Report, File; ReadsBook, TakesFonts, WritesFile);
80kind!(Pack, "pack", Report, File; ReadsBook, TakesFonts, WritesFile);
81kind!(Design, "design", DesignReport, File; ReadsBook, TakesFonts, WritesFile);
82kind!(Idml, "idml", Report, File; ReadsBook, WritesFile);
83kind!(Info, "info", InfoReport, Never; ReadsBook, TakesFonts);
84kind!(Check, "check", CheckReport, Never; ReadsBook, TakesFonts);
85kind!(Build, "build", Report, Never; ReadsBook, TakesFonts);
86kind!(ImportDocx, "import-docx", ImportDocxReport, Required, input = "book.docx", font_defaults = false;);
87kind!(Unpack, "unpack", UnpackReport, Required, font_defaults = false;);
88kind!(ImportIdml, "import-idml", ImportIdmlReport, Required, input = "document.idml";);
89
90macro_rules! options {
91    ($kind:ident { $($(#[$m:meta])* $fn:ident: $how:ident $flag:literal;)* }) => {
92        impl Command<'_, kind::$kind> {
93            $(options!(@one $(#[$m])* $fn $how $flag);)*
94        }
95    };
96    (@one $(#[$m:meta])* $fn:ident text $flag:literal) => {
97        $(#[$m])*
98        pub fn $fn(self, value: impl AsRef<OsStr>) -> Self {
99            self.opt($flag, value)
100        }
101    };
102    (@one $(#[$m:meta])* $fn:ident switch $flag:literal) => {
103        $(#[$m])*
104        pub fn $fn(self, on: bool) -> Self {
105            self.flag($flag, on)
106        }
107    };
108    (@one $(#[$m:meta])* $fn:ident count $flag:literal) => {
109        $(#[$m])*
110        pub fn $fn(self, value: u32) -> Self {
111            self.opt($flag, value.to_string())
112        }
113    };
114    (@one $(#[$m:meta])* $fn:ident real $flag:literal) => {
115        $(#[$m])*
116        pub fn $fn(self, value: impl Into<f64>) -> Self {
117            self.opt($flag, value.into().to_string())
118        }
119    };
120}
121
122options!(Pdf {
123    /// Tagged PDF/UA (default: the book's setting).
124    accessible: switch "accessible";
125    /// `rgb`, `cmyk` or `grayscale`.
126    color_space: text "color-space";
127    /// `none`, `x1a` or `x4`.
128    pdfx: text "pdfx";
129    /// `fogra39`, `fogra51`, `swop5`, `gracol2006`… or an `.icc` file.
130    profile: text "profile";
131    /// The book's outline as PDF bookmarks.
132    outlines: switch "outlines";
133    /// Pages printed in negative.
134    page_negative: switch "page-negative";
135});
136
137options!(Html {
138    /// `single` (one column) or `multi` (side by side).
139    mode: text "mode";
140    /// `embed` or `folder`.
141    assets: text "assets";
142});
143
144options!(Epub {
145    /// `fixed` (default) or `reflowable`.
146    layout: text "layout";
147    /// A cover picture.
148    cover: text "cover";
149});
150
151options!(Image {
152    /// `png`, `jpeg` or `webp`.
153    format: text "format";
154    /// Resolution (default 150).
155    dpi: real "dpi";
156    /// JPEG and WebP quality, 1 to 100.
157    quality: count "quality";
158    /// The page as printed: trim, bleed and print colours.
159    print_preview: switch "print-preview";
160});
161
162options!(Images {
163    /// Pages to render: `"1-10"`, `"#1-#20"` (default: all).
164    pages: text "pages";
165    /// File names: `"page-{n}"`, `"p-{label}"`…
166    pattern: text "pattern";
167    /// Pages rendered at once.
168    jobs: count "jobs";
169    /// `png`, `jpeg` or `webp`.
170    format: text "format";
171    /// Resolution (default 150).
172    dpi: real "dpi";
173    /// JPEG and WebP quality, 1 to 100.
174    quality: count "quality";
175    /// The pages as printed: trim, bleed and print colours.
176    print_preview: switch "print-preview";
177});
178
179options!(Docx {
180    /// `semantic` (content only, in plain styles), `formatted` (the book's
181    /// design, the default) or `facsimile` (the PDF's pages in text boxes).
182    variant: text "variant";
183    /// Embed the book's faces (default on; `false` names them only).
184    embed_fonts: switch "embed-fonts";
185});
186
187options!(Pack {
188    /// The bundle's id.
189    id: text "id";
190    /// The bundle's description.
191    description: text "description";
192    /// A thumbnail picture.
193    thumbnail: text "thumbnail";
194    /// Render the first page as the thumbnail.
195    auto_thumbnail: switch "auto-thumbnail";
196});
197
198options!(Design {
199    /// The design file's name.
200    design_name: text "design-name";
201    /// Its id.
202    id: text "id";
203    /// Its description.
204    description: text "description";
205});
206
207options!(Idml {
208    /// `embed` (inside the file, default) or `link` (beside it in `Links/`).
209    images: text "images";
210    /// `keep` (lines as Postext broke them, default) or `reflow` (left to
211    /// InDesign's composer).
212    lines: text "lines";
213    /// `facing` or `single` (default: facing for mirrored margins).
214    spreads: text "spreads";
215    /// Write the font files beside the package, in `Document fonts/` (needs
216    /// a file `out`).
217    fonts: switch "fonts";
218});
219
220options!(Info {
221    /// Lay the book out to count its pages.
222    pages: switch "pages";
223});
224
225options!(Check {
226    /// Any warning fails the check.
227    strict: switch "strict";
228    /// The print preflight too (resolution, colour, fonts).
229    preflight: switch "preflight";
230});
231
232options!(Build {
233    /// A PDF here.
234    pdf: text "pdf";
235    /// HTML here.
236    html: text "html";
237    /// An EPUB here.
238    epub: text "epub";
239    /// Page images in this folder.
240    images: text "images";
241    /// A Word document here.
242    docx: text "docx";
243    /// As [`variant`](Command::<kind::Docx>::variant) in `docx`.
244    docx_variant: text "docx-variant";
245    /// As `embed_fonts` in `docx`.
246    docx_fonts: switch "docx-fonts";
247    /// An InDesign package here.
248    idml: text "idml";
249    /// As `images` in `idml`.
250    idml_images: text "idml-images";
251    /// As `lines` in `idml`.
252    idml_lines: text "idml-lines";
253    /// As `spreads` in `idml`.
254    idml_spreads: text "idml-spreads";
255    /// As `fonts` in `idml`.
256    idml_fonts: switch "idml-fonts";
257    /// Pages to render as images.
258    pages: text "pages";
259    /// Image file names.
260    pattern: text "pattern";
261    /// Pages rendered at once.
262    jobs: count "jobs";
263    /// As in `pdf`.
264    accessible: switch "accessible";
265    /// As in `pdf`.
266    color_space: text "color-space";
267    /// As in `pdf`.
268    pdfx: text "pdfx";
269    /// As in `pdf`.
270    profile: text "profile";
271    /// As in `pdf`.
272    outlines: switch "outlines";
273    /// As in `pdf`.
274    page_negative: switch "page-negative";
275    /// As in `html`.
276    mode: text "mode";
277    /// As in `html`.
278    assets: text "assets";
279    /// As in `epub`.
280    layout: text "layout";
281    /// As in `epub`.
282    cover: text "cover";
283    /// As in `images`.
284    format: text "format";
285    /// As in `images`.
286    dpi: real "dpi";
287    /// As in `images`.
288    quality: count "quality";
289    /// As in `images`.
290    print_preview: switch "print-preview";
291});
292
293options!(ImportDocx {
294    /// Only report the edits; change nothing.
295    dry_run: switch "dry-run";
296    /// The pictures folder.
297    resources: text "resources";
298    /// A book whose design the new book takes.
299    template: text "template";
300    /// One chapter per heading of the top level.
301    split: switch "split";
302    /// The book's language.
303    locale: text "locale";
304    /// A configuration file.
305    config: text "config";
306    /// The book's title.
307    name: text "name";
308    /// The import's quality report.
309    quality_report: switch "report";
310    /// Render the first page as the thumbnail.
311    auto_thumbnail: switch "auto-thumbnail";
312});
313
314options!(Unpack {
315    /// Write over a folder that is not empty.
316    force: switch "force";
317});
318
319options!(ImportIdml {
320    /// In a package with several IDML documents, the one to import (`Book/Book.idml`).
321    document: text "document";
322    /// `pages` (composed pages as in the document), `flow` (a flowing book)
323    /// or `auto` (default).
324    layout: text "layout";
325    /// Where the linked pictures are.
326    links: text "links";
327    /// The book's title.
328    name: text "name";
329    /// The book's language.
330    locale: text "locale";
331    /// Read hidden objects too.
332    hidden: switch "hidden";
333    /// Read the pasteboard too.
334    pasteboard: switch "pasteboard";
335    /// Read non-printing objects too.
336    non_printing: switch "non-printing";
337    /// `visible` (default) or `all`.
338    conditions: text "conditions";
339    /// Tracked changes: `accept` (default) or `reject`.
340    changes: text "changes";
341    /// `false` leaves master-page items out.
342    masters: switch "masters";
343    /// The import's quality report.
344    quality_report: switch "report";
345    /// Render the first page as the thumbnail.
346    auto_thumbnail: switch "auto-thumbnail";
347    /// Where downloaded fonts are kept.
348    cache_dir: text "cache-dir";
349});
350
351impl Command<'_, kind::Design> {
352    /// The parts to take (`["page", "text", "headings"]`; default: all).
353    pub fn parts<I, S>(self, parts: I) -> Self
354    where
355        I: IntoIterator<Item = S>,
356        S: AsRef<str>,
357    {
358        self.opt("parts", join(parts))
359    }
360}
361
362impl Command<'_, kind::Check> {
363    /// Return the report when the check finds problems, instead of
364    /// [`Error::ProblemsFound`](crate::Error::ProblemsFound) (`passed` is
365    /// then `false`).
366    pub fn allow_problems(self) -> Self {
367        self.problems_allowed()
368    }
369}
370
371impl Command<'_, kind::ImportDocx> {
372    /// Merge the edits made in Word into this book (a folder or `.postext`),
373    /// instead of making a new book at `out`.
374    pub fn into_book(self, book: impl AsRef<OsStr>) -> Self {
375        self.input(book)
376    }
377
378    /// A configuration given as JSON.
379    pub fn config_json(self, config: &Value) -> Self {
380        self.json_opt("config", config, "config.json")
381    }
382
383    /// Return the report when an edit could not be applied, instead of
384    /// [`Error::ProblemsFound`](crate::Error::ProblemsFound).
385    pub fn allow_problems(self) -> Self {
386        self.problems_allowed()
387    }
388}
389
390impl Command<'_, kind::ImportIdml> {
391    /// Where the cover finds the document's fonts (repeats; replaces the
392    /// client's). For a package, faces found there are carried instead of
393    /// the package's.
394    pub fn font_dir(self, dir: impl AsRef<OsStr>) -> Self {
395        self.add_font_dir(dir)
396    }
397
398    /// Never download fonts from Google Fonts (default: the client's).
399    pub fn offline(self, offline: bool) -> Self {
400        self.set_offline(offline)
401    }
402}
403
404impl Postext {
405    /// Typeset the book into a PDF.
406    pub fn pdf(&self, book: impl Into<Books>) -> Command<'_, kind::Pdf> {
407        Command::new(self, book.into())
408    }
409
410    /// The laid-out pages as HTML: a path ending in `.html` (or `"-"`) gets
411    /// one self-contained file, any other path a folder.
412    pub fn html(&self, book: impl Into<Books>) -> Command<'_, kind::Html> {
413        Command::new(self, book.into())
414    }
415
416    /// An EPUB 3 book.
417    pub fn epub(&self, book: impl Into<Books>) -> Command<'_, kind::Epub> {
418        Command::new(self, book.into())
419    }
420
421    /// One page as an image. `page`: as printed (`"12"`, `"iv"`, or a number)
422    /// or by position (`"#1"`).
423    pub fn image(&self, book: impl Into<Books>, page: impl Display) -> Command<'_, kind::Image> {
424        Command::new(self, book.into()).opt("page", page.to_string())
425    }
426
427    /// Every page (or [`pages`](Command::<kind::Images>::pages)) as images in
428    /// the folder `out`. [`Report::outputs`] lists the files.
429    pub fn images(&self, book: impl Into<Books>) -> Command<'_, kind::Images> {
430        Command::new(self, book.into())
431    }
432
433    /// A Word document.
434    pub fn docx(&self, book: impl Into<Books>) -> Command<'_, kind::Docx> {
435        Command::new(self, book.into())
436    }
437
438    /// Pack a book folder, or loose Markdown files (the chapters, in
439    /// order), into a `.postext` bundle.
440    pub fn pack(&self, book: impl Into<Books>) -> Command<'_, kind::Pack> {
441        Command::new(self, book.into())
442    }
443
444    /// Take the book's design into a design file (default
445    /// `<book>.design.postext`): a `.postext` with no chapters, holding the
446    /// settings of the parts asked for and the font files and colour
447    /// profile they name. Give it to any book with `design()`.
448    pub fn design(&self, book: impl Into<Books>) -> Command<'_, kind::Design> {
449        Command::new(self, book.into())
450    }
451
452    /// The laid-out pages as an InDesign Markup package.
453    pub fn idml(&self, book: impl Into<Books>) -> Command<'_, kind::Idml> {
454        Command::new(self, book.into())
455    }
456
457    /// Describe the book: chapters, resources, fonts, locales.
458    pub fn info(&self, book: impl Into<Books>) -> Command<'_, kind::Info> {
459        Command::new(self, book.into())
460    }
461
462    /// Lay the book out and report its problems. When it finds an error (any
463    /// warning with `strict`), the run is
464    /// [`Error::ProblemsFound`](crate::Error::ProblemsFound), whose report
465    /// lists them.
466    pub fn check(&self, book: impl Into<Books>) -> Command<'_, kind::Check> {
467        Command::new(self, book.into())
468    }
469
470    /// Lay the book out once and write several outputs. For `--watch`, use
471    /// [`run_inherit`](Postext::run_inherit).
472    pub fn build(&self, book: impl Into<Books>) -> Command<'_, kind::Build> {
473        Command::new(self, book.into())
474    }
475
476    /// Turn a Word document (a path or bytes) into a new book at `out` (a
477    /// folder or a `.postext` file), or with
478    /// [`into_book`](Command::<kind::ImportDocx>::into_book) merge the edits
479    /// made in Word to an exported file back into the book.
480    pub fn import_docx(&self, docx: impl Into<Book>) -> Command<'_, kind::ImportDocx> {
481        Command::new(self, Books(vec![docx.into()]))
482    }
483
484    /// Extract a `.postext` bundle into the folder `out`.
485    pub fn unpack(&self, bundle: impl Into<Book>) -> Command<'_, kind::Unpack> {
486        Command::new(self, Books(vec![bundle.into()]))
487    }
488
489    /// Turn an InDesign document (`.idml`), or a zipped InDesign package
490    /// that holds one, into a new book at `out` (a folder or a `.postext`
491    /// file). Given as bytes, linked pictures are found only through
492    /// [`links`](Command::<kind::ImportIdml>::links).
493    pub fn import_idml(&self, idml: impl Into<Book>) -> Command<'_, kind::ImportIdml> {
494        Command::new(self, Books(vec![idml.into()]))
495    }
496}