boko 0.4.0

Fast native ebook converter for EPUB, KFX, AZW3, and MOBI — the only KFX writer that needs no Kindle Previewer
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
558
559
560
561
562
563
//! CSS property types and the enum_property! macro.
//!
//! This module contains all the CSS property value types that are used
//! in the style system.

use std::fmt::Write;
use std::hash::{Hash, Hasher};

use super::ToCss;

/// Macro for defining CSS keyword enums with automatic ToCss implementation.
///
/// Inspired by lightningcss's `enum_property!` macro, this reduces boilerplate
/// for enums that map directly to CSS keywords.
///
/// # Example
///
/// ```ignore
/// enum_property! {
///     /// Font style (normal, italic, oblique).
///     pub enum FontStyle {
///         #[default]
///         Normal => "normal",
///         Italic => "italic",
///         Oblique => "oblique",
///     }
/// }
/// ```
macro_rules! enum_property {
    (
        $(#[$meta:meta])*
        $vis:vis enum $name:ident {
            $(
                $(#[$variant_meta:meta])*
                $variant:ident => $css:literal
            ),* $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
        $vis enum $name {
            $(
                $(#[$variant_meta])*
                $variant,
            )*
        }

        impl $name {
            /// Returns the CSS keyword for this value.
            #[inline]
            pub fn as_str(&self) -> &'static str {
                match self {
                    $($name::$variant => $css,)*
                }
            }

            /// Parse a CSS keyword into this enum.
            #[inline]
            pub fn from_css(s: &str) -> Option<Self> {
                match s {
                    $($css => Some($name::$variant),)*
                    _ => None,
                }
            }
        }

        impl ToCss for $name {
            fn to_css(&self, buf: &mut String) {
                buf.push_str(self.as_str());
            }
        }
    };
}

// Export the macro for use within the crate
pub(crate) use enum_property;

/// CSS `font-weight` as a numeric weight (100-900).
///
/// `normal` parses to 400 and `bold` to 700; the derived default of 0 means
/// "unset". Serializes back to the `normal`/`bold` keywords where possible.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct FontWeight(
    /// Numeric weight (100-900); 0 means unset.
    pub u16,
);

impl FontWeight {
    /// `font-weight: normal` (400).
    pub const NORMAL: FontWeight = FontWeight(400);
    /// `font-weight: bold` (700).
    pub const BOLD: FontWeight = FontWeight(700);
}

impl ToCss for FontWeight {
    fn to_css(&self, buf: &mut String) {
        match self.0 {
            400 => buf.push_str("normal"),
            700 => buf.push_str("bold"),
            w => write!(buf, "{}", w).unwrap(),
        }
    }
}

enum_property! {
    /// CSS `font-style` values (normal, italic, oblique).
    pub enum FontStyle {
        /// Upright glyphs (CSS initial value).
        #[default]
        Normal => "normal",
        /// Cursive italic face.
        Italic => "italic",
        /// Slanted (oblique) face; treated as italic by exporters.
        Oblique => "oblique",
    }
}

enum_property! {
    /// CSS `font-variant` / `font-variant-caps` values.
    pub enum FontVariant {
        /// Regular glyphs (CSS initial value).
        #[default]
        Normal => "normal",
        /// Lowercase letters rendered as small capitals.
        SmallCaps => "small-caps",
    }
}

enum_property! {
    /// CSS `text-transform` values.
    pub enum TextTransform {
        /// No case transformation (CSS initial value).
        #[default]
        None => "none",
        /// Render all text in uppercase.
        Uppercase => "uppercase",
        /// Render all text in lowercase.
        Lowercase => "lowercase",
        /// Capitalize the first letter of each word.
        Capitalize => "capitalize",
    }
}

enum_property! {
    /// CSS `hyphens` values (automatic hyphenation mode).
    /// Default is `Manual` so that explicit `hyphens: auto` is emitted in KFX output.
    pub enum Hyphens {
        /// Break words at language-appropriate hyphenation points.
        Auto => "auto",
        /// Break only at explicit hyphenation characters (CSS initial value).
        #[default]
        Manual => "manual",
        /// Never hyphenate, even at explicit hyphenation characters.
        None => "none",
    }
}

enum_property! {
    /// CSS `text-decoration-style` values (how the decoration line is drawn).
    ///
    /// `None` is a boko extension meaning "unset" (CSS has no `none` keyword
    /// here; the CSS initial value is `solid`).
    pub enum DecorationStyle {
        /// Unset — no explicit decoration style (renders as solid).
        #[default]
        None => "none",
        /// A single solid line.
        Solid => "solid",
        /// A dotted line.
        Dotted => "dotted",
        /// A dashed line.
        Dashed => "dashed",
        /// A double line.
        Double => "double",
    }
}

enum_property! {
    /// CSS `float` values.
    pub enum Float {
        /// Not floated (CSS initial value).
        #[default]
        None => "none",
        /// Float to the left; content flows along the right side.
        Left => "left",
        /// Float to the right; content flows along the left side.
        Right => "right",
    }
}

enum_property! {
    /// CSS `break-before`/`break-after`/`break-inside` (and legacy
    /// `page-break-*`) values controlling pagination.
    pub enum BreakValue {
        /// No forced or avoided break (CSS initial value).
        #[default]
        Auto => "auto",
        /// Force a page break.
        Always => "always",
        /// Avoid a break if possible.
        Avoid => "avoid",
        /// Force a column break.
        Column => "column",
    }
}

enum_property! {
    /// CSS `border-style` values (per-side line style).
    pub enum BorderStyle {
        /// No border (CSS initial value).
        #[default]
        None => "none",
        /// A single solid line.
        Solid => "solid",
        /// A dotted line.
        Dotted => "dotted",
        /// A dashed line.
        Dashed => "dashed",
        /// Two parallel solid lines.
        Double => "double",
        /// Carved (3D grooved) appearance.
        Groove => "groove",
        /// Extruded (3D ridged) appearance.
        Ridge => "ridge",
        /// Embedded (3D inset) appearance.
        Inset => "inset",
        /// Embossed (3D outset) appearance.
        Outset => "outset",
    }
}

enum_property! {
    /// CSS `list-style-position` values (marker placement).
    pub enum ListStylePosition {
        /// Marker outside the list item's principal box (CSS initial value).
        #[default]
        Outside => "outside",
        /// Marker inside the list item's box, as the first inline content.
        Inside => "inside",
    }
}

enum_property! {
    /// CSS `visibility` values.
    pub enum Visibility {
        /// Element is rendered normally (CSS initial value).
        #[default]
        Visible => "visible",
        /// Element is invisible but still occupies layout space.
        Hidden => "hidden",
        /// Like `hidden`, but table rows/columns release their space.
        Collapse => "collapse",
    }
}

enum_property! {
    /// CSS box-sizing values.
    pub enum BoxSizing {
        /// Width/height include only content (CSS default)
        #[default]
        ContentBox => "content-box",
        /// Width/height include padding and border
        BorderBox => "border-box",
    }
}

enum_property! {
    /// CSS `clear` values for float clearing.
    pub enum Clear {
        /// Do not clear floats (CSS initial value).
        #[default]
        None => "none",
        /// Move below any left-floated boxes.
        Left => "left",
        /// Move below any right-floated boxes.
        Right => "right",
        /// Move below floated boxes on both sides.
        Both => "both",
    }
}

enum_property! {
    /// CSS `word-break` values (where lines may break within words).
    pub enum WordBreak {
        /// Default line-breaking rules (CSS initial value).
        #[default]
        Normal => "normal",
        /// Allow breaks between any two characters.
        BreakAll => "break-all",
        /// Disallow breaks within CJK words.
        KeepAll => "keep-all",
        /// Deprecated alias behaving like `overflow-wrap: break-word`.
        BreakWord => "break-word",
    }
}

enum_property! {
    /// CSS `overflow-wrap` values (emergency breaking of long words).
    pub enum OverflowWrap {
        /// Break only at normal word break points (CSS initial value).
        #[default]
        Normal => "normal",
        /// Break otherwise-unbreakable words if a line would overflow.
        BreakWord => "break-word",
        /// Like `break-word`, but soft-wrap opportunities affect
        /// min-content sizing.
        Anywhere => "anywhere",
    }
}

enum_property! {
    /// CSS white-space values.
    pub enum WhiteSpace {
        /// Normal whitespace handling: collapse whitespace, wrap lines.
        #[default]
        Normal => "normal",
        /// Collapse whitespace but don't wrap lines.
        Nowrap => "nowrap",
        /// Preserve whitespace and newlines, don't wrap lines.
        Pre => "pre",
        /// Preserve whitespace and newlines, wrap lines.
        PreWrap => "pre-wrap",
        /// Collapse whitespace except newlines, wrap lines.
        PreLine => "pre-line",
    }
}

enum_property! {
    /// CSS `vertical-align` values for inline and table-cell elements.
    ///
    /// `Super` and `Sub` are how boko represents superscript/subscript text
    /// (see `ComputedStyle::is_superscript`/`is_subscript`).
    pub enum VerticalAlign {
        /// Align with the parent's baseline (CSS initial value).
        #[default]
        Baseline => "baseline",
        /// Align with the top of the line box (or table cell).
        Top => "top",
        /// Align with the middle of the line box (or table cell).
        Middle => "middle",
        /// Align with the bottom of the line box (or table cell).
        Bottom => "bottom",
        /// Align with the top of the parent's font.
        TextTop => "text-top",
        /// Align with the bottom of the parent's font.
        TextBottom => "text-bottom",
        /// Superscript baseline shift.
        Super => "super",
        /// Subscript baseline shift.
        Sub => "sub",
    }
}

enum_property! {
    /// CSS border-collapse values for tables.
    pub enum BorderCollapse {
        /// Borders are separated (CSS default for tables).
        #[default]
        Separate => "separate",
        /// Adjacent borders are collapsed into a single border.
        Collapse => "collapse",
    }
}

enum_property! {
    /// CSS `text-align` values.
    pub enum TextAlign {
        /// Align toward the start of the writing direction (CSS initial value).
        #[default]
        Start => "start",
        /// Align toward the end of the writing direction.
        End => "end",
        /// Left-align inline content.
        Left => "left",
        /// Right-align inline content.
        Right => "right",
        /// Center inline content.
        Center => "center",
        /// Justify lines to both margins.
        Justify => "justify",
    }
}

enum_property! {
    /// CSS `display` values (the subset boko models).
    ///
    /// Note: the default is `Block`, not CSS's `inline` — boko assigns
    /// display per element role, so the struct default is only a fallback.
    pub enum Display {
        /// Block-level box.
        #[default]
        Block => "block",
        /// Inline box.
        Inline => "inline",
        /// Inline-level block container.
        InlineBlock => "inline-block",
        /// Element generates no boxes (removed from layout).
        None => "none",
        /// Block box with a list marker (`li`).
        ListItem => "list-item",
        /// Table cell box (`td`/`th`).
        TableCell => "table-cell",
        /// Table row box (`tr`).
        TableRow => "table-row",
    }
}

enum_property! {
    /// CSS list-style-type values.
    pub enum ListStyleType {
        /// No marker
        None => "none",
        /// Disc bullet (CSS default)
        #[default]
        Disc => "disc",
        /// Circle bullet
        Circle => "circle",
        /// Square bullet
        Square => "square",
        /// Decimal numbers (default for ol)
        Decimal => "decimal",
        /// Lowercase letters
        LowerAlpha => "lower-alpha",
        /// Uppercase letters
        UpperAlpha => "upper-alpha",
        /// Lowercase roman numerals
        LowerRoman => "lower-roman",
        /// Uppercase roman numerals
        UpperRoman => "upper-roman",
    }
}

/// RGBA color (8 bits per channel).
///
/// Parsed from any CSS color syntax (hex, `rgb()`/`rgba()`, named colors).
/// Serializes as `#rrggbb` when opaque, `transparent` when fully
/// transparent, and `rgba()` otherwise.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Color {
    /// Red channel (0-255).
    pub r: u8,
    /// Green channel (0-255).
    pub g: u8,
    /// Blue channel (0-255).
    pub b: u8,
    /// Alpha channel (0 = fully transparent, 255 = opaque).
    pub a: u8,
}

impl Color {
    /// Opaque black (`#000000`).
    pub const BLACK: Color = Color {
        r: 0,
        g: 0,
        b: 0,
        a: 255,
    };
    /// Opaque white (`#ffffff`).
    pub const WHITE: Color = Color {
        r: 255,
        g: 255,
        b: 255,
        a: 255,
    };
    /// Fully transparent (all channels zero).
    pub const TRANSPARENT: Color = Color {
        r: 0,
        g: 0,
        b: 0,
        a: 0,
    };

    /// Create a new opaque color.
    pub fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self { r, g, b, a: 255 }
    }

    /// Create a new color with alpha.
    pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> Self {
        Self { r, g, b, a }
    }
}

impl ToCss for Color {
    fn to_css(&self, buf: &mut String) {
        if self.a == 255 {
            // Opaque: use #RRGGBB
            write!(buf, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b).unwrap();
        } else if self.a == 0 {
            buf.push_str("transparent");
        } else {
            // With alpha: use rgba()
            let alpha = self.a as f32 / 255.0;
            write!(buf, "rgba({},{},{},{:.2})", self.r, self.g, self.b, alpha).unwrap();
        }
    }
}

/// CSS length value with unit.
///
/// Supports absolute pixels, font-relative `em`/`rem`, and percentages.
/// At parse time `pt` is converted to `Px` (1pt = 96/72 px) and `ex` to
/// `Em` (~0.5em). `Auto` doubles as both CSS `auto` and "property unset" —
/// it is the `Default`, so a default-initialized field means the property
/// was never specified.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum Length {
    /// The `auto` keyword; also the default, meaning "unset".
    #[default]
    Auto,
    /// Absolute length in CSS pixels (other absolute units are converted).
    Px(f32),
    /// Length relative to the element's font size.
    Em(f32),
    /// Length relative to the root font size.
    Rem(f32),
    /// Percentage of the containing block's corresponding dimension.
    Percent(f32),
}

impl Eq for Length {}

impl Hash for Length {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Length::Auto => 0u8.hash(state),
            Length::Px(v) => {
                1u8.hash(state);
                v.to_bits().hash(state);
            }
            Length::Em(v) => {
                2u8.hash(state);
                v.to_bits().hash(state);
            }
            Length::Rem(v) => {
                3u8.hash(state);
                v.to_bits().hash(state);
            }
            Length::Percent(v) => {
                4u8.hash(state);
                v.to_bits().hash(state);
            }
        }
    }
}

impl ToCss for Length {
    fn to_css(&self, buf: &mut String) {
        match self {
            Length::Auto => buf.push_str("auto"),
            Length::Px(v) => {
                if *v == 0.0 {
                    buf.push('0');
                } else {
                    write!(buf, "{}px", v).unwrap();
                }
            }
            Length::Em(v) => write!(buf, "{}em", v).unwrap(),
            Length::Rem(v) => write!(buf, "{}rem", v).unwrap(),
            Length::Percent(v) => write!(buf, "{}%", v).unwrap(),
        }
    }
}