render_tree/stylesheet/
mod.rs

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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
mod accumulator;
mod color;
mod format;
mod style;

use self::format::{DisplayStyle, NodeDetails};
use crate::utils::CommaArray;
use crate::PadItem;
use itertools::Itertools;
use log::*;
use std::collections::HashMap;

pub use self::accumulator::ColorAccumulator;
pub use self::color::Color;
pub use self::style::{Style, WriteStyle};

pub struct Selector {
    segments: Vec<Segment>,
}

impl Selector {
    pub fn new() -> Selector {
        Selector { segments: vec![] }
    }

    pub fn glob() -> GlobSelector {
        Selector::new().add_glob()
    }

    pub fn star() -> Selector {
        Selector::new().add_star()
    }

    pub fn name(name: &'static str) -> Selector {
        Selector::new().add(name)
    }

    pub fn add_glob(self) -> GlobSelector {
        let mut segments = self.segments;
        segments.push(Segment::Glob);
        GlobSelector { segments }
    }

    pub fn add_star(mut self) -> Selector {
        self.segments.push(Segment::Star);
        self
    }

    pub fn add(mut self, segment: &'static str) -> Selector {
        self.segments.push(Segment::Name(segment));
        self
    }
}

/// This type statically prevents appending a glob right after another glob,
/// which is illegal. It shares the `add_star` and `add` methods with
/// `Selector`, but does not have an `add_glob` method.
pub struct GlobSelector {
    segments: Vec<Segment>,
}

impl GlobSelector {
    pub fn add_star(self) -> Selector {
        let mut segments = self.segments;
        segments.push(Segment::Star);
        Selector { segments }
    }

    pub fn add(self, segment: &'static str) -> Selector {
        let mut segments = self.segments;
        segments.push(Segment::Name(segment));
        Selector { segments }
    }
}

impl IntoIterator for Selector {
    type Item = Segment;
    type IntoIter = ::std::vec::IntoIter<Segment>;

    fn into_iter(self) -> ::std::vec::IntoIter<Segment> {
        self.segments.into_iter()
    }
}

impl IntoIterator for GlobSelector {
    type Item = Segment;
    type IntoIter = ::std::vec::IntoIter<Segment>;

    fn into_iter(self) -> ::std::vec::IntoIter<Segment> {
        self.segments.into_iter()
    }
}

impl From<&'static str> for Selector {
    fn from(from: &'static str) -> Selector {
        let segments = from.split(' ');
        let segments = segments.map(|part| part.into());

        Selector {
            segments: segments.collect(),
        }
    }
}

/// A Segment is one of:
///
/// - Root: The root node
/// - Star: `*`, matches exactly one section names
/// - Glob: `**`, matches zero or more section names
/// - Name: A named segment, matches a section name that exactly matches the name
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Segment {
    Root,
    Star,
    Glob,
    Name(&'static str),
}

impl From<&'static str> for Segment {
    fn from(from: &'static str) -> Segment {
        if from == "**" {
            Segment::Glob
        } else if from == "*" {
            Segment::Star
        } else {
            Segment::Name(from)
        }
    }
}

/// A Node represents a segment, child segments, and an optional associated style.
#[derive(Debug)]
struct Node {
    segment: Segment,
    children: HashMap<Segment, Node>,
    declarations: Option<Style>,
}

impl Node {
    fn new(segment: Segment) -> Node {
        Node {
            segment,
            children: HashMap::new(),
            declarations: None,
        }
    }

    fn display<'a>(&'a self) -> NodeDetails<'a> {
        NodeDetails::new(self.segment, &self.declarations)
    }

    /// Return a terminal node relative to the current node. If the current
    /// node has no children, it's the terminal node. Otherwise, if the
    /// current node has a glob child, that child is the terminal node.
    ///
    /// Otherwise, this node is not a terminal node.
    fn terminal(&self) -> Option<&Node> {
        match self.children.get(&Segment::Glob) {
            None => if self.children.is_empty() {
                return Some(self);
            } else {
                return None;
            },
            Some(glob) => return Some(glob),
        };
    }

    /// Add nodes for the segment path, and associate it with the provided style.
    fn add(&mut self, selector: impl IntoIterator<Item = Segment>, declarations: impl Into<Style>) {
        let mut path = selector.into_iter();

        match path.next() {
            None => {
                self.declarations = Some(declarations.into());
            }
            Some(name) => self
                .children
                .entry(name)
                .or_insert(Node::new(name))
                .add(path, declarations),
        }
    }

    /// Find a style for a section path. The resulting style is the merged result of all
    /// matches, with literals taking precedence over stars and stars taking precedence
    /// over globs.
    ///
    /// Earlier nodes take precedence over later nodes, so:
    ///
    /// `header *` takes precedence over `* code` for the section path `["header", "code"]`.
    ///
    /// Styles are merged per attribute, so the style attributes for a lower-precedence rule
    /// will appear in the merged style as long as they are not overridden by a
    /// higher-precedence rule.
    fn find<'a>(&self, names: &[&'static str], debug_nesting: usize) -> Option<Style> {
        trace!(
            "{}In {}, finding {:?} (children={})",
            PadItem("  ", debug_nesting),
            self,
            names.join(" "),
            CommaArray(self.children.keys().map(|k| k.to_string()).collect())
        );

        let next_name = match names.first() {
            None => {
                let terminal = self.terminal()?;

                trace!(
                    "{}Matched terminal {}",
                    PadItem("  ", debug_nesting),
                    terminal.display()
                );

                return terminal.declarations.clone();
            }

            Some(next_name) => next_name,
        };

        let matches = self.find_match(next_name);

        trace!("{}Matches: {}", PadItem("  ", debug_nesting), matches);

        // Accumulate styles from matches, in order of precedence.
        let mut style: Option<Style> = None;

        // A glob match means that a child node of the current node was a glob. Since
        // globs match zero or more segments, if a node has a glob child, it will
        // always match.
        if let Some(glob) = matches.glob {
            style = union(style, glob.find(&names[1..], debug_nesting + 1));
            trace!(
                "{}matched glob={}",
                PadItem("  ", debug_nesting),
                DisplayStyle(&style)
            );
        }

        // A star matches exactly one segment.
        if let Some(star) = matches.star {
            style = union(style, star.find(&names[1..], debug_nesting + 1));
            trace!(
                "{}matched star={}",
                PadItem("  ", debug_nesting),
                DisplayStyle(&style)
            );
        }

        if let Some(skipped_glob) = matches.skipped_glob {
            style = union(style, skipped_glob.find(&names[1..], debug_nesting + 1));
            trace!(
                "{}matched skipped_glob={}",
                PadItem("  ", debug_nesting),
                DisplayStyle(&style)
            );
        }

        if let Some(literal) = matches.literal {
            style = union(style, literal.find(&names[1..], debug_nesting + 1));
            trace!(
                "{}matched literal={}",
                PadItem("  ", debug_nesting),
                DisplayStyle(&style)
            );
        }

        style
    }

    /// Find a match in the current node for a section name.
    ///
    /// - If the current node is a glob, the current node is a match, since a
    ///   glob node can absorb arbitrarily many section names.alloc
    /// - If the current node has a glob child, it's a match. These two
    ///   conditions cannot occur at the same time, since a glob cannot
    ///   immediately follow a glob.
    /// - If the current node has a glob child, and it's immediately
    ///   followed by a literal node that matches the section, that
    ///   node is a match.
    /// - If the current node has a star child, it's a match
    ///
    /// The matches are applied in precedence order.
    fn find_match<'a>(&'a self, name: &'static str) -> Match<'a> {
        let glob;

        let mut skipped_glob = None;
        let star = self.children.get(&Segment::Star);
        let literal = self.children.get(&Segment::Name(name));

        // A glob always matches itself
        if self.segment == Segment::Glob {
            glob = Some(self);
        } else {
            glob = self.children.get(&Segment::Glob);

            if let Some(glob) = glob {
                skipped_glob = glob.children.get(&Segment::Name(name));
            }
        }

        Match {
            glob,
            star,
            skipped_glob,
            literal,
        }
    }
}

fn union(left: Option<Style>, right: Option<Style>) -> Option<Style> {
    match (left, right) {
        (None, None) => None,
        (Some(left), None) => Some(left),
        (None, Some(right)) => Some(right),
        (Some(left), Some(right)) => Some(left.union(right)),
    }
}

struct Match<'a> {
    glob: Option<&'a Node>,
    star: Option<&'a Node>,
    skipped_glob: Option<&'a Node>,
    literal: Option<&'a Node>,
}

#[derive(Debug)]
pub struct Stylesheet {
    styles: Node,
}

impl Stylesheet {
    /// Construct a new stylesheet
    pub fn new() -> Stylesheet {
        Stylesheet {
            styles: Node::new(Segment::Root),
        }
    }

    /// Add a segment to the stylesheet.
    ///
    /// Using style strings:
    ///
    /// ```
    /// # use render_tree::{Stylesheet, Style};
    ///
    /// let stylesheet = Stylesheet::new()
    ///     .add("message header * code", "weight: bold; fg: red");
    ///
    /// assert_eq!(stylesheet.get(&["message", "header", "error", "code"]),
    ///     Some(Style("weight: bold; fg: red")))
    /// ```
    ///
    /// Using typed styles:
    ///
    /// ```
    /// # use render_tree::{Color, Style, Stylesheet};
    /// #
    /// let stylesheet = Stylesheet::new()
    ///     .add("message header * code", Style::new().bold().fg(Color::Red));
    ///
    /// assert_eq!(stylesheet.get(&["message", "header", "error", "code"]),
    ///     Some(Style("weight: bold; fg: red")))
    /// ```
    pub fn add(mut self, name: impl Into<Selector>, declarations: impl Into<Style>) -> Stylesheet {
        self.styles.add(name.into(), declarations);

        self
    }

    /// Get the style associated with a nesting.
    ///
    /// ```
    /// # use render_tree::{Stylesheet, Style};
    ///
    /// let stylesheet = Stylesheet::new()
    ///     .add("message ** code", "fg: blue")
    ///     .add("message header * code", "weight: bold; fg: red");
    ///
    /// let style = stylesheet.get(&["message", "header", "error", "code"]);
    /// ```
    pub fn get(&self, names: &[&'static str]) -> Option<Style> {
        if log_enabled!(::log::Level::Trace) {
            println!("\n");
        }

        trace!("Searching for `{}`", names.iter().join(" "));
        let style = self.styles.find(names, 0);

        match &style {
            None => trace!("No style found"),
            Some(style) => trace!("Found {}", style),
        }

        style
    }
}

#[cfg(test)]
mod tests {
    use super::style::Style;
    use crate::{Color, Stylesheet};
    use pretty_env_logger;

    fn init_logger() {
        pretty_env_logger::try_init().ok();
    }

    #[test]
    fn test_basic_lookup() {
        init_logger();

        let stylesheet =
            Stylesheet::new().add("message header error code", "fg: red; underline: false");

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(style, Some(Style("fg: red; underline: false")))
    }

    #[test]
    fn test_basic_with_typed_style() {
        init_logger();

        let stylesheet = Stylesheet::new().add(
            "message header error code",
            Style::new().bold().fg(Color::Red),
        );

        assert_eq!(
            stylesheet.get(&["message", "header", "error", "code"]),
            Some(Style("weight: bold; fg: red"))
        )
    }

    #[test]
    fn test_star() {
        init_logger();

        let stylesheet =
            Stylesheet::new().add("message header * code", "fg: red; underline: false");

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(style, Some(Style("fg: red; underline: false")))
    }

    #[test]
    fn test_star_with_typed_style() {
        init_logger();

        let stylesheet =
            Stylesheet::new().add("message header * code", Style::new().bold().fg(Color::Red));

        assert_eq!(
            stylesheet.get(&["message", "header", "error", "code"]),
            Some(Style("weight: bold; fg: red"))
        )
    }

    #[test]
    fn test_glob() {
        init_logger();

        let stylesheet = Stylesheet::new().add("message ** code", "fg: red; underline: false");

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(style, Some(Style("fg: red; underline: false")))
    }

    #[test]
    fn test_glob_with_typed_style() {
        init_logger();

        let stylesheet =
            Stylesheet::new().add("message ** code", Style::new().nounderline().fg(Color::Red));

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(style, Some(Style("fg: red; underline: false")))
    }

    #[test]
    fn test_glob_matches_no_segments() {
        init_logger();

        let stylesheet =
            Stylesheet::new().add("message ** header error code", "fg: red; underline: false");

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(style, Some(Style("fg: red; underline: false")))
    }

    #[test]
    fn test_glob_matches_no_segments_with_typed_style() {
        init_logger();

        let stylesheet = Stylesheet::new().add(
            "message ** header error code",
            Style::new().nounderline().fg(Color::Red),
        );

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(style, Some(Style("fg: red; underline: false")))
    }

    #[test]
    fn test_trailing_glob_is_terminal() {
        init_logger();

        let stylesheet = Stylesheet::new().add(
            "message header error **",
            Style::new().nounderline().fg(Color::Red),
        );

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(style, Some(Style("fg: red; underline: false")))
    }

    #[test]
    fn test_trailing_glob_is_terminal_with_typed_styles() {
        init_logger();

        let stylesheet = Stylesheet::new().add(
            "message header error **",
            Style::new().nounderline().fg(Color::Red),
        );

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(style, Some(Style::new().fg(Color::Red).nounderline()))
    }

    #[test]
    fn test_trailing_glob_is_terminal_and_matches_nothing() {
        init_logger();

        let stylesheet =
            Stylesheet::new().add("message header error code **", "fg: red; underline: false");

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(style, Some(Style::new().fg(Color::Red).nounderline()))
    }

    #[test]
    fn test_trailing_glob_is_terminal_and_matches_nothing_with_typed_style() {
        init_logger();

        let stylesheet = Stylesheet::new().add(
            "message header error code **",
            Style::new().nounderline().fg(Color::Red),
        );

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(style, Some(Style::new().fg(Color::Red).nounderline()))
    }

    #[test]
    fn test_priority() {
        init_logger();

        let stylesheet = Stylesheet::new()
            .add("message ** code", "fg: blue; weight: bold")
            .add("message header * code", "underline: true; bg: black")
            .add("message header error code", "fg: red; underline: false");

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(
            style,
            Some(
                Style::new()
                    .fg(Color::Red)
                    .bg(Color::Black)
                    .nounderline()
                    .bold()
            )
        )
    }

    #[test]
    fn test_priority_with_typed_style() {
        init_logger();

        let stylesheet = Stylesheet::new()
            .add("message ** code", Style::new().fg(Color::Blue).bold())
            .add(
                "message header * code",
                Style::new().underline().bg(Color::Black),
            ).add(
                "message header error code",
                Style::new().fg(Color::Red).nounderline(),
            );

        let style = stylesheet.get(&["message", "header", "error", "code"]);

        assert_eq!(
            style,
            Some(
                Style::new()
                    .fg(Color::Red)
                    .bg(Color::Black)
                    .nounderline()
                    .bold()
            )
        )
    }
}