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
use std::ops::{Index, IndexMut};
use std::rc::Rc;

use pango;

use super::cell::Cell;
use super::item::Item;
use crate::color;
use crate::render;
use crate::highlight::{HighlightMap, Highlight};

pub struct Line {
    pub line: Box<[Cell]>,

    // format of item line is
    // [Item1, Item2, None, None, Item3]
    // Item2 take 3 cells and renders as one
    pub item_line: Box<[Option<Item>]>,
    cell_to_item: Box<[i32]>,

    pub dirty_line: bool,
}

impl Line {
    pub fn new(columns: usize) -> Self {
        Line {
            line: vec![Cell::new_empty(); columns].into_boxed_slice(),
            item_line: vec![None; columns].into_boxed_slice(),
            cell_to_item: vec![-1; columns].into_boxed_slice(),
            dirty_line: true,
        }
    }

    pub fn swap_with(&mut self, target: &mut Self, left: usize, right: usize) {
        // swap is faster then clone
        target.line[left..right + 1].swap_with_slice(&mut self.line[left..right + 1]);

        // this is because copy can change Item layout
        target.dirty_line = true;
        for cell in &mut target.line[left..right + 1] {
            cell.dirty = true;
        }
    }

    pub fn clear(&mut self, left: usize, right: usize, default_hl: &Rc<Highlight>) {
        for cell in &mut self.line[left..right + 1] {
            cell.clear(default_hl.clone());
        }
        self.dirty_line = true;
    }

    pub fn clear_glyphs(&mut self) {
        for i in 0..self.item_line.len() {
            self.item_line[i] = None;
            self.cell_to_item[i] = -1;
        }
        self.dirty_line = true;
    }

    fn set_cell_to_empty(&mut self, cell_idx: usize) -> bool {
        if self.is_binded_to_item(cell_idx) {
            self.item_line[cell_idx] = None;
            self.cell_to_item[cell_idx] = -1;
            self.line[cell_idx].dirty = true;
            true
        } else {
            false
        }
    }

    fn set_cell_to_item(&mut self, new_item: &PangoItemPosition) -> bool {
        let start_item_idx = self.cell_to_item(new_item.start_cell);
        let start_item_cells_count = if start_item_idx >= 0 {
            self.item_line[start_item_idx as usize]
                .as_ref()
                .map_or(-1, |item| item.cells_count as i32)
        } else {
            -1
        };

        let end_item_idx = self.cell_to_item(new_item.end_cell);

        // start_item == idx of item start cell
        // in case different item length was in previous iteration
        // mark all item as dirty
        if start_item_idx != new_item.start_cell as i32
            || new_item.cells_count() != start_item_cells_count
            || start_item_idx == -1
            || end_item_idx == -1
        {
            self.initialize_cell_item(new_item.start_cell, new_item.end_cell, new_item.item);
            true
        } else {
            // update only if cell marked as dirty
            if self.line[new_item.start_cell..new_item.end_cell + 1]
                .iter()
                .any(|c| c.dirty)
            {
                self.item_line[new_item.start_cell]
                    .as_mut()
                    .unwrap()
                    .update(new_item.item.clone());
                self.line[new_item.start_cell].dirty = true;
                true
            } else {
                false
            }
        }
    }

    pub fn merge(&mut self, old_items: &StyledLine, pango_items: &[pango::Item]) {
        let mut pango_item_iter = pango_items
            .iter()
            .map(|item| PangoItemPosition::new(old_items, item));

        let mut next_item = pango_item_iter.next();
        let mut move_to_next_item = false;

        let mut cell_idx = 0;
        while cell_idx < self.line.len() {
            let dirty = match next_item {
                None => self.set_cell_to_empty(cell_idx),
                Some(ref new_item) => {
                    if cell_idx < new_item.start_cell {
                        self.set_cell_to_empty(cell_idx)
                    } else if cell_idx == new_item.start_cell {
                        move_to_next_item = true;
                        self.set_cell_to_item(new_item)
                    } else {
                        false
                    }
                }
            };

            self.dirty_line = self.dirty_line || dirty;
            if move_to_next_item {
                let new_item = next_item.unwrap();
                cell_idx += new_item.end_cell - new_item.start_cell + 1;
                next_item = pango_item_iter.next();
                move_to_next_item = false;
            } else {
                cell_idx += 1;
            }
        }
    }

    fn initialize_cell_item(
        &mut self,
        start_cell: usize,
        end_cell: usize,
        new_item: &pango::Item,
    ) {
        for i in start_cell..end_cell + 1 {
            self.line[i].dirty = true;
            self.cell_to_item[i] = start_cell as i32;
        }
        for i in start_cell + 1..end_cell + 1 {
            self.item_line[i] = None;
        }
        self.item_line[start_cell] = Some(Item::new(new_item.clone(), end_cell - start_cell + 1));
    }

    pub fn get_item(&self, cell_idx: usize) -> Option<&Item> {
        let item_idx = self.cell_to_item(cell_idx);
        if item_idx >= 0 {
            self.item_line[item_idx as usize].as_ref()
        } else {
            None
        }
    }

    #[inline]
    pub fn cell_to_item(&self, cell_idx: usize) -> i32 {
        self.cell_to_item[cell_idx]
    }

    pub fn item_len_from_idx(&self, start_idx: usize) -> usize {
        debug_assert!(
            start_idx < self.line.len(),
            "idx={}, len={}",
            start_idx,
            self.line.len()
        );

        let item_idx = self.cell_to_item(start_idx);

        if item_idx >= 0 {
            let item_idx = item_idx as usize;
            let cells_count = self.item_line[item_idx].as_ref().unwrap().cells_count;
            let offset = start_idx - item_idx;

            cells_count - offset
        } else {
            1
        }
    }

    #[inline]
    pub fn is_binded_to_item(&self, cell_idx: usize) -> bool {
        self.cell_to_item[cell_idx] >= 0
    }
}

impl Index<usize> for Line {
    type Output = Cell;

    fn index(&self, index: usize) -> &Cell {
        &self.line[index]
    }
}

impl IndexMut<usize> for Line {
    fn index_mut(&mut self, index: usize) -> &mut Cell {
        &mut self.line[index]
    }
}

struct PangoItemPosition<'a> {
    item: &'a pango::Item,
    start_cell: usize,
    end_cell: usize,
}

impl<'a> PangoItemPosition<'a> {
    pub fn new(styled_line: &StyledLine, item: &'a pango::Item) -> Self {
        let offset = item.offset() as usize;
        let length = item.length() as usize;
        let start_cell = styled_line.cell_to_byte[offset];
        let end_cell = styled_line.cell_to_byte[offset + length - 1];

        PangoItemPosition {
            item,
            start_cell,
            end_cell,
        }
    }

    #[inline]
    fn cells_count(&self) -> i32 {
        (self.end_cell - self.start_cell) as i32 + 1
    }
}

pub struct StyledLine {
    pub line_str: String,
    cell_to_byte: Box<[usize]>,
    pub attr_list: pango::AttrList,
}

impl StyledLine {
    pub fn from(
        line: &Line,
        hl: &HighlightMap,
        font_features: &render::FontFeatures,
    ) -> Self {
        let average_capacity = line.line.len() * 4 * 2; // code bytes * grapheme cluster

        let mut line_str = String::with_capacity(average_capacity);
        let mut cell_to_byte = Vec::with_capacity(average_capacity);
        let attr_list = pango::AttrList::new();
        let mut byte_offset = 0;
        let mut style_attr = StyleAttr::new();

        for (cell_idx, cell) in line.line.iter().enumerate() {
            if cell.double_width {
                continue;
            }

            if !cell.ch.is_empty() {
                line_str.push_str(&cell.ch);
            } else {
                line_str.push(' ');
            }
            let len = line_str.len() - byte_offset;

            for _ in 0..len {
                cell_to_byte.push(cell_idx);
            }

            let next = style_attr.next(byte_offset, byte_offset + len, cell, hl);
            if let Some(next) = next {
                style_attr.insert_into(&attr_list);
                style_attr = next;
            }

            byte_offset += len;
        }

        style_attr.insert_into(&attr_list);
        font_features.insert_into(&attr_list);

        StyledLine {
            line_str,
            cell_to_byte: cell_to_byte.into_boxed_slice(),
            attr_list,
        }
    }
}

struct StyleAttr<'c> {
    italic: bool,
    bold: bool,
    foreground: Option<&'c color::Color>,
    background: Option<&'c color::Color>,
    empty: bool,
    space: bool,

    start_idx: usize,
    end_idx: usize,
}

impl<'c> StyleAttr<'c> {
    fn new() -> Self {
        StyleAttr {
            italic: false,
            bold: false,
            foreground: None,
            background: None,
            empty: true,
            space: false,

            start_idx: 0,
            end_idx: 0,
        }
    }

    fn from(
        start_idx: usize,
        end_idx: usize,
        cell: &'c Cell,
        hl: &'c HighlightMap,
    ) -> Self {
        StyleAttr {
            italic: cell.hl.italic,
            bold: cell.hl.bold,
            foreground: hl.cell_fg(cell),
            background: hl.cell_bg(cell),
            empty: false,
            space: cell.ch.is_empty(),

            start_idx,
            end_idx,
        }
    }

    fn next(
        &mut self,
        start_idx: usize,
        end_idx: usize,
        cell: &'c Cell,
        hl: &'c HighlightMap,
    ) -> Option<StyleAttr<'c>> {
        // don't check attr for space
        if self.space && cell.ch.is_empty() {
            self.end_idx = end_idx;
            return None;
        }


        let style_attr = Self::from(start_idx, end_idx, cell, hl);

        if self != &style_attr {
            Some(style_attr)
        } else {
            self.end_idx = end_idx;
            None
        }
    }

    fn insert_into(&self, attr_list: &pango::AttrList) {
        if self.empty {
            return;
        }

        if self.italic {
            self.insert_attr(
                attr_list,
                pango::Attribute::new_style(pango::Style::Italic).unwrap(),
            );
        }

        if self.bold {
            self.insert_attr(
                attr_list,
                pango::Attribute::new_weight(pango::Weight::Bold).unwrap(),
            );
        }

        if let Some(fg) = self.foreground {
            let (r, g, b) = fg.to_u16();
            self.insert_attr(
                attr_list,
                pango::Attribute::new_foreground(r, g, b).unwrap(),
            );
        }

        if let Some(bg) = self.background {
            let (r, g, b) = bg.to_u16();
            self.insert_attr(
                attr_list,
                pango::Attribute::new_background(r, g, b).unwrap(),
            );
        }
    }

    #[inline]
    fn insert_attr(&self, attr_list: &pango::AttrList, mut attr: pango::Attribute) {
        attr.set_start_index(self.start_idx as u32);
        attr.set_end_index(self.end_idx as u32);
        attr_list.insert(attr);
    }
}

impl<'c> PartialEq for StyleAttr<'c> {
    fn eq(&self, other: &Self) -> bool {
        self.italic == other.italic
            && self.bold == other.bold
            && self.foreground == other.foreground
            && self.empty == other.empty
            && self.background == other.background
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_styled_line() {
        let mut line = Line::new(3);
        line[0].ch = "a".to_owned();
        line[1].ch = "b".to_owned();
        line[2].ch = "c".to_owned();

        let styled_line = StyledLine::from(
            &line,
            &HighlightMap::new(),
            &render::FontFeatures::new(),
        );
        assert_eq!("abc", styled_line.line_str);
        assert_eq!(3, styled_line.cell_to_byte.len());
        assert_eq!(0, styled_line.cell_to_byte[0]);
        assert_eq!(1, styled_line.cell_to_byte[1]);
        assert_eq!(2, styled_line.cell_to_byte[2]);
    }
}