summaryrefslogtreecommitdiffstats
path: root/svgbob/src/buffer/fragment_buffer/fragment/text.rs
blob: b2a444a1a7d0f398967050a870ca3b8375d81dfe (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
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
use crate::{
    buffer::{Cell, CellGrid},
    fragment::Bounds,
    Point,
};
use sauron::{html::*, svg, svg::attributes::*, Node};
use std::{borrow::Cow, cmp::Ordering, fmt};

/// A horizontal cell text
/// Operated based on cell
/// Text are threated differently
/// since scaling them losses the sense
/// of which text it adjacent to without keeping
/// track of the scale.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub struct CellText {
    pub start: Cell,
    pub content: String,
}

impl CellText {
    pub fn new(start: Cell, content: String) -> Self {
        CellText { start, content }
    }

    fn end_cell(&self) -> Cell {
        Cell::new(self.start.x + self.content.len() as i32, self.start.y)
    }

    /// get the cells of this text
    /// TODO: use iterator
    fn cells(&'_ self) -> impl IntoIterator<Item = Cell> + '_ {
        let range = self.start.x..(self.start.x + self.content.len() as i32);
        range.map(move |x| Cell::new(x, self.start.y))
    }

    fn is_adjacent_cell(&self, other_cell: Cell) -> bool {
        self.cells()
            .into_iter()
            .any(|cell| cell.y == other_cell.y && cell.is_adjacent(&other_cell))
    }

    /// cell text is groupable when they are adjacent
    pub(crate) fn is_contacting(&self, other: &Self) -> bool {
        self.cells()
            .into_iter()
            .any(|cell| other.is_adjacent_cell(cell))
    }

    /// text can merge if they are next to each other and at the same line
    pub(in crate) fn can_merge(&self, other: &Self) -> bool {
        self.start.y == other.start.y
            && (self.start.x + self.content.len() as i32 == other.start.x
                || other.start.x + other.content.len() as i32 == self.start.x)
    }

    pub(in crate) fn merge(&self, other: &Self) -> Option<Self> {
        if self.can_merge(other) {
            if self.start.x < other.start.x {
                Some(CellText::new(
                    self.start,
                    format!("{}{}", self.content, other.content),
                ))
            } else {
                Some(CellText::new(
                    other.start,
                    format!("{}{}", other.content, self.content),
                ))
            }
        } else {
            None
        }
    }

    pub(in crate) fn absolute_position(&self, cell: Cell) -> Self {
        CellText {
            start: Cell::new(self.start.x + cell.x, self.start.y + cell.y),
            ..self.clone()
        }
    }
}

impl Bounds for CellText {
    fn bounds(&self) -> (Point, Point) {
        (
            self.start.top_left_most(),
            self.end_cell().bottom_right_most(),
        )
    }
}

impl Into<Text> for CellText {
    fn into(self) -> Text {
        Text::new(self.start.q(), self.content)
    }
}

impl<MSG> Into<Node<MSG>> for CellText {
    fn into(self) -> Node<MSG> {
        let text: Text = self.into();
        text.into()
    }
}

impl fmt::Display for CellText {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "CT {} {}", self.start, self.content)
    }
}

/// This is ready to be scaled and drawn into the svg file
#[derive(Debug, Clone)]
pub struct Text {
    pub start: Point,
    pub text: String,
}

impl Text {
    pub fn new(start: Point, text: String) -> Self {
        Text { start, text }
    }

    /// get the textwidth in terms of cell grid points
    fn text_width(&self) -> f32 {
        self.text.len() as f32 * CellGrid::width()
    }

    pub(in crate) fn absolute_position(&self, cell: Cell) -> Self {
        Text {
            start: cell.absolute_position(self.start),
            ..self.clone()
        }
    }

    pub(in crate) fn scale(&self, scale: f32) -> Self {
        Text {
            start: self.start.scale(scale),
            ..self.clone()
        }
    }
}

fn replace_html_char<'a>(ch: char) -> Cow<'a, str> {
    match ch {
        '>' => Cow::from("&gt;"),
        '<' => Cow::from("&lt;"),
        '&' => Cow::from("&amp;"),
        '\'' => Cow::from("&#39;"),
        '"' => Cow::from("&quot;"),
        '\0' => Cow::from(""),
        _ => Cow::from(ch.to_string()),
    }
}

fn escape_html_text(s: &str) -> String {
    s.chars().map(|ch| replace_html_char(ch)).collect()
}

impl fmt::Display for Text {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "T {} {}", self.start, self.text)
    }
}

impl<MSG> Into<Node<MSG>> for Text {
    fn into(self) -> Node<MSG> {
        svg::tags::text(
            [x(self.start.x), y(self.start.y)],
            #[cfg(not(feature = "with-dom"))]
            [text(escape_html_text(&self.text))],
            #[cfg(feature = "with-dom")]
            [text(&self.text)],
        )
    }
}

impl Bounds for Text {
    fn bounds(&self) -> (Point, Point) {
        (
            self.start,
            Point::new(self.start.x + self.text_width(), self.start.y),
        )
    }
}

impl Eq for Text {}

/// This is needed since this struct contains f32 which rust doesn't provide Eq implementation
impl Ord for Text {
    fn cmp(&self, other: &Self) -> Ordering {
        self.start
            .cmp(&other.start)
            .then(self.text.cmp(&other.text))
    }
}

impl PartialOrd for Text {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Text {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        buffer::{Cell, CellBuffer, Contacts, Span},
        fragment::CellText,
        Settings,
    };

    #[test]
    fn test_cell_text_absolute_position() {
        let t1 = CellText::new(Cell::new(0, 0), "c".to_string());
        let t1_abs = t1.absolute_position(Cell::new(1, 1));
        assert_eq!(t1_abs.start, Cell::new(1, 1));

        let t2 = CellText::new(Cell::new(4, 3), "c".to_string());
        let t2_abs = t2.absolute_position(Cell::new(5, 7));
        assert_eq!(t2_abs.start, Cell::new(9, 10));
    }

    #[test]
    fn text_merge_point_base() {
        let c1 = Cell::new(1, 1);
        let c2 = Cell::new