summaryrefslogtreecommitdiffstats
path: root/packages/svgbob/src/buffer/fragment_buffer.rs
blob: e9bdddba398f6e7d97b871a536eee5558398f121 (plain)
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
use crate::buffer::Span;
use crate::Cell;
use crate::Merge;
use crate::Settings;
pub use direction::Direction;
pub use fragment::Fragment;
pub use fragment_span::FragmentSpan;
pub use fragment_tree::FragmentTree;
use itertools::Itertools;
use std::{
    collections::BTreeMap,
    ops::{Deref, DerefMut},
};

pub mod direction;
pub mod fragment;
mod fragment_span;
mod fragment_tree;

/// Fragment buffer contains the drawing fragments for each cell
/// Svg can be converted to fragment buffer
/// then from the fragment we can match which characters is best suited for
/// a particular set of fragment contained in a cell and then create a stringbuffer.
/// The stringbuffer becomes the ascii diagrams
///  SVG -> FragmentBuffer -> StringBuffer -> Ascii Diagrams
///
/// We can also create a reverse
///  Ascii Diagrams -> String Buffer -> Fragment Buffer -> SVG
///
/// ```ignore
///      0 1 2 3 4           B C D
///     0┌─┬─┬─┬─┐        A┌─┬─┬─┬─┐E
///     1├─┼─┼─┼─┤         │ │ │ │ │
///     2├─┼─┼─┼─┤        F├─G─H─I─┤J
///     3├─┼─┼─┼─┤         │ │ │ │ │
///     4├─┼─┼─┼─┤        K├─L─M─N─┤O
///     5├─┼─┼─┼─┤         │ │ │ │ │
///     6├─┼─┼─┼─┤        P├─Q─R─S─┤T
///     7├─┼─┼─┼─┤         │ │ │ │ │
///     8└─┴─┴─┴─┘        U└─┴─┴─┴─┘Y
/// ```                      V W X
#[derive(Debug)]
pub struct FragmentBuffer(BTreeMap<Cell, (char, Vec<Fragment>)>);

impl Deref for FragmentBuffer {
    type Target = BTreeMap<Cell, (char, Vec<Fragment>)>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for FragmentBuffer {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl FragmentBuffer {
    pub fn new() -> Self {
        FragmentBuffer(BTreeMap::new())
    }

    /// dump for debugging purpose only
    /// printling the fragments on this fragment buffer
    pub fn dump(&self) -> String {
        let mut buff = String::new();
        for (cell, (_ch, shapes)) in self.iter() {
            buff.push_str(&format!("\ncell: {} ", cell));
            for shape in shapes {
                buff.push_str(&format!("\n    {}", shape));
            }
        }
        buff
    }

    /// sort the fragments content in this cell
    fn sort_fragments_in_cell(&mut self, cell: Cell) {
        if let Some((_ch, fragments)) = &mut self.get_mut(&cell) {
            (*fragments).sort();
        }
    }

    fn bounds(&self) -> Option<(Cell, Cell)> {
        let xlimits =
            self.iter().map(|(cell, _)| cell.x).minmax().into_option();
        let ylimits =
            self.iter().map(|(cell, _)| cell.y).minmax().into_option();
        match (xlimits, ylimits) {
            (Some((min_x, max_x)), Some((min_y, max_y))) => {
                Some((Cell::new(min_x, min_y), Cell::new(max_x, max_y)))
            }
            _ => None,
        }
    }

    pub fn get_size(&self, settings: &Settings) -> (f32, f32) {
        let (_top_left, bottom_right) =
            self.bounds().unwrap_or((Cell::new(0, 0), Cell::new(0, 0)));
        let w = settings.scale * (bottom_right.x + 2) as f32 * Cell::width();
        let h = settings.scale * (bottom_right.y + 2) as f32 * Cell::height();
        (w, h)
    }

    /// Add a single fragment to this cell
    pub fn add_fragment_to_cell(
        &mut self,
        cell: Cell,
        ch: char,
        fragment: Fragment,
    ) {
        if let Some((ex_ch, existing)) = self.get_mut(&cell) {
            assert_eq!(*ex_ch, ch);
            existing.push(fragment);
        } else {
            self.insert(cell, (ch, vec![fragment]));
        }
        self.sort_fragments_in_cell(cell);
    }

    /// add multiple fragments to cell
    pub fn add_fragments_to_cell(
        &mut self,
        cell: Cell,
        ch: char,
        fragments: Vec<Fragment>,
    ) {
        if let Some((ex_ch, existing)) = self.get_mut(&cell) {
            assert_eq!(*ex_ch, ch);
            existing.extend(fragments);
        } else {
            self.insert(cell, (ch, fragments));
        }
        self.sort_fragments_in_cell(cell);
    }

    pub fn merge_fragment_spans(
        &self,
        settings: &Settings,
    ) -> Vec<FragmentSpan> {
        let fragment_spans = self.into_fragment_spans();
        FragmentSpan::merge_recursive(fragment_spans)
    }

    /// create a merged of fragments while preserving their cells
    fn into_fragment_spans(&self) -> Vec<FragmentSpan> {
        let mut fragment_spans: Vec<FragmentSpan> = vec![];
        for (cell, (ch, fragments)) in self.iter() {
            for frag in fragments.iter() {
                let abs_frag = frag.absolute_position(*cell);
                let span = Span::new(*cell, *ch);
                let abs_frag = FragmentSpan::new(span, abs_frag);
                let had_merged =
                    fragment_spans.iter_mut().rev().any(|frag_span| {
                        if let Some(new_merge) = frag_span.merge(&abs_frag) {
                            *frag_span = new_merge;
                            true
                        } else {
                            false
                        }
                    });

                if !had_merged {
                    fragment_spans.push(abs_frag);
                }
            }
        }
        fragment_spans
    }
}