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
//! AST of a bard songbook

use std::collections::BTreeMap;

use image::image_dimensions;
use serde::Serialize;

use crate::music::Notation;
use crate::prelude::*;
use crate::project::Settings;
use crate::util::{sort_lexical_by, BStr, ImgCache};

pub mod version;
mod xml;

#[derive(Serialize, Debug)]
#[serde(tag = "type")]
pub enum Block {
    #[serde(rename = "b-verse")]
    Verse(Verse),
    #[serde(rename = "b-bullet-list")]
    BulletList(BulletList),
    #[serde(rename = "b-horizontal-line")]
    HorizontalLine,
    #[serde(rename = "b-pre")]
    Pre { text: BStr },
    /// An HTML block contains inlines which can only be `Text`, `HtmlTag`, or `Break`.
    #[serde(rename = "b-html-block")]
    HtmlBlock(Inlines),
}

impl Block {
    pub fn chorus_num(&self) -> Option<u32> {
        if let Self::Verse(Verse {
            label: VerseLabel::Chorus(num),
            ..
        }) = self
        {
            *num
        } else {
            None
        }
    }

    /// Used to remove chorus numbers in case there's one chorus.
    pub fn remove_chorus_num(&mut self) {
        if let Self::Verse(verse) = self {
            if let VerseLabel::Chorus(num) = &mut verse.label {
                *num = None;
            }

            verse
                .paragraphs
                .iter_mut()
                .flat_map(|p| p.iter_mut())
                .for_each(Inline::remove_chorus_num);
        }
    }

    fn verse(&self) -> Option<&Verse> {
        match self {
            Self::Verse(verse) => Some(verse),
            _ => None,
        }
    }

    fn verse_mut(&mut self) -> Option<&mut Verse> {
        match self {
            Self::Verse(verse) => Some(verse),
            _ => None,
        }
    }
}

/// Needed for Inline enum tagging in JSON and similar...
#[derive(Serialize, Debug)]
pub struct Inlines {
    pub inlines: Box<[Inline]>,
}

impl Inlines {
    pub fn new(inlines: Box<[Inline]>) -> Self {
        Self { inlines }
    }

    fn remove_chorus_num(&mut self) {
        self.inlines.iter_mut().for_each(Inline::remove_chorus_num);
    }
}

impl From<Vec<Inline>> for Inlines {
    fn from(inlines: Vec<Inline>) -> Self {
        Self {
            inlines: inlines.into(),
        }
    }
}

impl AsRef<[Inline]> for Inlines {
    fn as_ref(&self) -> &[Inline] {
        self.inlines.as_ref()
    }
}

#[derive(Serialize, Debug)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "type")]
pub enum Inline {
    #[serde(rename = "i-text")]
    Text { text: BStr },
    #[serde(rename = "i-chord")]
    Chord(Chord),
    /// All line breaks are considered hard breaks
    #[serde(rename = "i-break")]
    Break,
    #[serde(rename = "i-emph")]
    Emph(Inlines),
    #[serde(rename = "i-strong")]
    Strong(Inlines),
    #[serde(rename = "i-link")]
    Link(Link),
    #[serde(rename = "i-image")]
    Image(Image),
    #[serde(rename = "i-chorus-ref")]
    ChorusRef(ChorusRef),
    #[serde(rename = "i-tag")]
    HtmlTag(HtmlTag),

    /// Only used internally by the parser to apply transposition.
    /// Removed from the resulting AST, except in tests where this
    /// is used to verify transposition extensions parsing.
    #[serde(rename = "i-transpose")]
    Transpose(Transpose),
}

impl Inline {
    pub fn text(text: impl Into<BStr>) -> Self {
        Self::Text { text: text.into() }
    }

    pub fn is_break(&self) -> bool {
        matches!(self, Self::Break)
    }

    pub fn is_xpose(&self) -> bool {
        matches!(self, Self::Transpose(..))
    }

    pub fn unwrap_xpose(&self) -> Transpose {
        match self {
            Self::Transpose(xpose) => *xpose,
            _ => panic!("Unexpected inline: {:?}", self),
        }
    }

    fn remove_chorus_num(&mut self) {
        match self {
            Inline::Chord(c) => c.remove_chorus_num(),
            Inline::Emph(e) => e.remove_chorus_num(),
            Inline::Strong(s) => s.remove_chorus_num(),
            Inline::ChorusRef(cr) => cr.num = None,
            _ => {}
        }
    }

    fn image(&self) -> Option<&Image> {
        match self {
            Self::Image(image) => Some(image),
            _ => None,
        }
    }

    fn image_mut(&mut self) -> Option<&mut Image> {
        match self {
            Self::Image(image) => Some(image),
            _ => None,
        }
    }
}

#[derive(Serialize, Debug)]
pub struct Chord {
    pub chord: BStr,
    pub alt_chord: Option<BStr>,
    pub backticks: usize,
    pub baseline: bool,
    pub inlines: Box<[Inline]>,
}

impl Chord {
    pub fn new(
        chord: BStr,
        alt_chord: Option<BStr>,
        backticks: usize,
        baseline: bool,
        inlines: Vec<Inline>,
    ) -> Self {
        Self {
            chord,
            alt_chord,
            backticks,
            baseline,
            inlines: inlines.into(),
        }
    }

    fn remove_chorus_num(&mut self) {
        self.inlines.iter_mut().for_each(Inline::remove_chorus_num);
    }
}

#[derive(Serialize, Debug)]
pub struct Link {
    pub url: BStr,
    pub title: BStr,
    pub text: BStr,
}

impl Link {
    pub fn new(url: BStr, title: BStr, text: BStr) -> Self {
        Self { url, title, text }
    }
}

#[derive(Serialize, Debug)]
pub struct Image {
    pub path: BStr,
    pub title: BStr,
    pub class: BStr,
    /// Size in pixels, initially `0`, resolved during book postprocessing.
    pub width: u32,
    /// Size in pixels, initially `0`, resolved during book postprocessing.
    pub height: u32,

    /// Absolute path to the image file, resolved during book postprocessing,
    /// **not** part of the AST.
    #[serde(skip)]
    full_path: Option<PathBuf>,
}

impl Image {
    pub fn new(path: BStr, title: BStr, class: BStr) -> Self {
        Self {
            path,
            title,
            class,
            width: 0,
            height: 0,
            full_path: None,
        }
    }

    fn resolve(&mut self, output_dir: &Path, img_cache: &ImgCache) -> Result<()> {
        let path = Path::new(&*self.path);
        if self.path.contains("://") || path.is_absolute() {
            bail!("Image path has to be relative and pointing to a local file.");
        }

        let full_path = output_dir.join(path);
        let (w, h) = img_cache.try_get(&full_path, || {
            image_dimensions(&full_path)
                .with_context(|| format!("Couldn't read image file {:?}", full_path))
        })?;

        self.width = w;
        self.height = h;
        self.full_path = Some(full_path);

        Ok(())
    }

    pub fn full_path(&self) -> &Path {
        self.full_path.as_deref().unwrap()
    }
}

#[derive(Serialize, Debug)]
pub struct ChorusRef {
    pub num: Option<u32>,
    pub prefix_space: BStr,
}

impl ChorusRef {
    pub fn new(num: Option<u32>, prefix_space: bool) -> Self {
        Self {
            num,
            prefix_space: if prefix_space { " ".into() } else { "".into() },
        }
    }
}

#[derive(Serialize, Debug)]
pub struct HtmlTag {
    pub name: BStr,
    pub attrs: BTreeMap<BStr, BStr>,
}

/// Transposition extensions. See Comment in `Inline`.
#[derive(Serialize, Clone, Copy, Debug)]
pub enum Transpose {
    #[serde(rename = "t-transpose")]
    Transpose(i32),
    #[serde(rename = "t-notation")]
    Notation(Notation),
    #[serde(rename = "t-alt-transpose")]
    AltTranspose(i32),
    #[serde(rename = "t-alt-notation")]
    AltNotation(Notation),
    /// Turn off alt chords
    #[serde(rename = "t-alt-none")]
    AltNone,
}

#[derive(Serialize, Clone, PartialEq, Eq, Debug)]
#[serde(rename_all = "snake_case")]
pub enum VerseLabel {
    Verse(u32),
    Chorus(Option<u32>),
    Custom(BStr),
    None {},
}

impl VerseLabel {
    fn is_some(&self) -> bool {
        !matches!(self, Self::None {})
    }
}

pub type Paragraph = Box<[Inline]>;

#[derive(Serialize, Debug)]
pub struct Verse {
    pub label: VerseLabel,
    pub paragraphs: Vec<Paragraph>,
}

impl Verse {
    pub fn new(label: VerseLabel, paragraphs: Vec<Paragraph>) -> Self {
        Self { label, paragraphs }
    }

    pub fn is_empty(&self) -> bool {
        self.paragraphs.is_empty()
    }

    fn inlines(&self) -> impl Iterator<Item = &Inline> {
        self.paragraphs.iter().flat_map(|p| p.iter())
    }

    fn inlines_mut(&mut self) -> impl Iterator<Item = &mut Inline> {
        self.paragraphs.iter_mut().flat_map(|p| p.iter_mut())
    }
}

#[derive(Serialize, Debug)]
pub struct BulletList {
    pub items: Box<[BStr]>,
}

#[derive(Serialize, Debug)]
pub struct Song {
    pub title: BStr,
    pub subtitles: Box<[BStr]>,
    pub blocks: Vec<Block>,
    pub notation: Notation,
}

impl Song {
    /// AST postprocessing.
    ///
    /// This entails removing empty paragraphs and verses
    /// which linger when transposition extensions are applied & removed.
    ///
    /// Distinct from `Book::postprocess()`, this is done by `Parser`.
    pub fn postprocess(&mut self) {
        // Remove paragraphs which contain nothing or linebreaks only
        for verse in self.blocks.iter_mut().filter_map(Block::verse_mut) {
            verse
                .paragraphs
                .retain(|para| para.iter().any(|inline| !inline.is_break()));
        }

        // Remove verses which have no paragraphs and no label
        self.blocks.retain(|block| match block {
            Block::Verse(verse) => verse.label.is_some() || !verse.paragraphs.is_empty(),
            _ => true,
        });
    }
}

#[derive(Serialize, Debug)]
pub struct SongRef {
    pub title: BStr,
    /// index of the song in the Book::songs vector
    pub idx: usize,
}

impl SongRef {
    pub fn new((idx, songs): (usize, &Song)) -> Self {
        Self {
            title: songs.title.clone(),
            idx,
        }
    }
}

#[derive(Debug)]
pub struct Book {
    pub songs: Vec<Song>,
    pub songs_sorted: Vec<SongRef>,
    pub notation: Notation,
}

impl Book {
    pub fn new(settings: &Settings) -> Book {
        Book {
            songs: vec![],
            songs_sorted: vec![],
            notation: settings.notation,
        }
    }

    pub fn add_songs(&mut self, mut songs: Vec<Song>) {
        self.songs.reserve(songs.len());
        self.songs.append(&mut songs);
    }

    /// Book-level postprocessing.
    ///
    /// Steps taken:
    /// 1. Generation of the songs_sorted vec,
    /// 2. Resolving of image elements (checking path, reading image dimensions).
    pub fn postprocess(&mut self, output_dir: &Path, img_cache: &ImgCache) -> Result<()> {
        self.songs.shrink_to_fit();
        self.songs_sorted = self.songs.iter().enumerate().map(SongRef::new).collect();
        sort_lexical_by(&mut self.songs_sorted, |songref| songref.title.as_ref());

        for image in self.iter_images_mut() {
            image.resolve(output_dir, img_cache)?;
        }

        Ok(())
    }

    pub fn iter_images(&self) -> impl Iterator<Item = &Image> {
        self.songs
            .iter()
            .flat_map(|s| s.blocks.iter())
            .filter_map(Block::verse)
            .flat_map(|v| v.inlines())
            .filter_map(Inline::image)
    }

    pub fn iter_images_mut(&mut self) -> impl Iterator<Item = &mut Image> {
        self.songs
            .iter_mut()
            .flat_map(|s| s.blocks.iter_mut())
            .filter_map(Block::verse_mut)
            .flat_map(|v| v.inlines_mut())
            .filter_map(Inline::image_mut)
    }
}

#[cfg(test)]
pub trait AssertJsonEq {
    fn assert_json_eq(&self, value: serde_json::Value);
}

#[cfg(test)]
impl<T> AssertJsonEq for T
where
    T: Serialize,
{
    #[track_caller]
    fn assert_json_eq(&self, value: serde_json::Value) {
        use assert_json_diff::{assert_json_matches_no_panic, CompareMode, Config};

        let config = Config::new(CompareMode::Strict);
        if let Err(diff) = assert_json_matches_no_panic(self, &value, config) {
            panic!(
                "JSON equality assertion failed: \n== LHS ==\n{}\n== RHS ==\n{}\n== DIFF \
                 ==\n{}\n\n",
                serde_json::to_string_pretty(self).unwrap(),
                serde_json::to_string_pretty(&value).unwrap(),
                diff
            )
        }
    }
}