Struct cosmic_text::Buffer

source ·
pub struct Buffer<'a> {
    pub lines: Vec<BufferLine>,
    /* private fields */
}
Expand description

A buffer of text that is shaped and laid out

Fields§

§lines: Vec<BufferLine>

BufferLines (or paragraphs) of text in the buffer

Implementations§

Create a new Buffer with the provided FontSystem and Metrics

Pre-shape lines in the buffer, up to lines, return actual number of layout lines

Examples found in repository?
src/buffer.rs (line 284)
280
281
282
283
284
285
286
287
288
289
290
291
292
293
    pub fn shape_until_scroll(&mut self) {
        let lines = self.visible_lines();

        let scroll_end = self.scroll + lines;
        let total_layout = self.shape_until(scroll_end);

        self.scroll = cmp::max(
            0,
            cmp::min(
                total_layout - (lines - 1),
                self.scroll,
            ),
        );
    }

Shape lines until cursor, also scrolling to include cursor in view

Examples found in repository?
src/edit/editor.rs (line 87)
85
86
87
88
89
90
91
92
    fn shape_as_needed(&mut self) {
        if self.cursor_moved {
            self.buffer.shape_until_cursor(self.cursor);
            self.cursor_moved = false;
        } else {
            self.buffer.shape_until_scroll();
        }
    }

Shape lines until scroll

Examples found in repository?
src/edit/editor.rs (line 90)
85
86
87
88
89
90
91
92
    fn shape_as_needed(&mut self) {
        if self.cursor_moved {
            self.buffer.shape_until_cursor(self.cursor);
            self.cursor_moved = false;
        } else {
            self.buffer.shape_until_scroll();
        }
    }
More examples
Hide additional examples
src/buffer.rs (line 276)
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
    pub fn shape_until_cursor(&mut self, cursor: Cursor) {
        #[cfg(feature = "std")]
        let instant = std::time::Instant::now();

        let mut reshaped = 0;
        let mut layout_i = 0;
        for (line_i, line) in self.lines.iter_mut().enumerate() {
            if line_i > cursor.line {
                break;
            }

            if line.shape_opt().is_none() {
                reshaped += 1;
            }
            let layout = line.layout(
                self.font_system,
                self.metrics.font_size,
                self.width
            );
            if line_i == cursor.line {
                let layout_cursor = self.layout_cursor(&cursor);
                layout_i += layout_cursor.layout as i32;
                break;
            } else {
                layout_i += layout.len() as i32;
            }
        }

        if reshaped > 0 {
            #[cfg(feature = "std")]
            log::debug!("shape_until_cursor {}: {:?}", reshaped, instant.elapsed());
            self.redraw = true;
        }

        let lines = self.visible_lines();
        if layout_i < self.scroll {
            self.scroll = layout_i;
        } else if layout_i >= self.scroll + lines {
            self.scroll = layout_i - (lines - 1);
        }

        self.shape_until_scroll();
    }

    /// Shape lines until scroll
    pub fn shape_until_scroll(&mut self) {
        let lines = self.visible_lines();

        let scroll_end = self.scroll + lines;
        let total_layout = self.shape_until(scroll_end);

        self.scroll = cmp::max(
            0,
            cmp::min(
                total_layout - (lines - 1),
                self.scroll,
            ),
        );
    }

    pub fn layout_cursor(&self, cursor: &Cursor) -> LayoutCursor {
        let line = &self.lines[cursor.line];

        //TODO: ensure layout is done?
        let layout = line.layout_opt().as_ref().expect("layout not found");
        for (layout_i, layout_line) in layout.iter().enumerate() {
            for (glyph_i, glyph) in layout_line.glyphs.iter().enumerate() {
                if cursor.index == glyph.start {
                    return LayoutCursor::new(
                        cursor.line,
                        layout_i,
                        glyph_i
                    );
                }
            }
            match layout_line.glyphs.last() {
                Some(glyph) => {
                    if cursor.index == glyph.end {
                        return LayoutCursor::new(
                            cursor.line,
                            layout_i,
                            layout_line.glyphs.len()
                        );
                    }
                },
                None => {
                    return LayoutCursor::new(
                        cursor.line,
                        layout_i,
                        0
                    );
                }
            }
        }

        // Fall back to start of line
        //TODO: should this be the end of the line?
        LayoutCursor::new(
            cursor.line,
            0,
            0
        )
    }

    /// Get [`FontSystem`] used by this [`Buffer`]
    pub fn font_system(&self) -> &'a FontSystem {
        self.font_system
    }

    /// Shape the provided line index and return the result
    pub fn line_shape(&mut self, line_i: usize) -> Option<&ShapeLine> {
        let line = self.lines.get_mut(line_i)?;
        Some(line.shape(self.font_system))
    }

    /// Lay out the provided line index and return the result
    pub fn line_layout(&mut self, line_i: usize) -> Option<&[LayoutLine]> {
        let line = self.lines.get_mut(line_i)?;
        Some(line.layout(self.font_system, self.metrics.font_size, self.width))
    }

    /// Get the current [`Metrics`]
    pub fn metrics(&self) -> Metrics {
        self.metrics
    }

    /// Set the current [`Metrics`]
    pub fn set_metrics(&mut self, metrics: Metrics) {
        if metrics != self.metrics {
            self.metrics = metrics;
            self.relayout();
            self.shape_until_scroll();
        }
    }

    /// Get the current buffer dimensions (width, height)
    pub fn size(&self) -> (i32, i32) {
        (self.width, self.height)
    }

    /// Set the current buffer dimensions
    pub fn set_size(&mut self, width: i32, height: i32) {
        if width != self.width || height != self.height {
            self.width = width;
            self.height = height;
            self.relayout();
            self.shape_until_scroll();
        }
    }

    /// Get the current scroll location
    pub fn scroll(&self) -> i32 {
        self.scroll
    }

    /// Set the current scroll location
    pub fn set_scroll(&mut self, scroll: i32) {
        if scroll != self.scroll {
            self.scroll = scroll;
            self.redraw = true;
        }
    }

    /// Get the number of lines that can be viewed in the buffer
    pub fn visible_lines(&self) -> i32 {
        self.height / self.metrics.line_height
    }

    /// Set text of buffer, using provided attributes for each line by default
    pub fn set_text(&mut self, text: &str, attrs: Attrs<'a>) {
        self.lines.clear();
        for line in text.lines() {
            self.lines.push(BufferLine::new(line.to_string(), AttrsList::new(attrs)));
        }
        // Make sure there is always one line
        if self.lines.is_empty() {
            self.lines.push(BufferLine::new(String::new(), AttrsList::new(attrs)));
        }

        self.scroll = 0;

        self.shape_until_scroll();
    }
Examples found in repository?
src/buffer.rs (line 255)
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
    pub fn shape_until_cursor(&mut self, cursor: Cursor) {
        #[cfg(feature = "std")]
        let instant = std::time::Instant::now();

        let mut reshaped = 0;
        let mut layout_i = 0;
        for (line_i, line) in self.lines.iter_mut().enumerate() {
            if line_i > cursor.line {
                break;
            }

            if line.shape_opt().is_none() {
                reshaped += 1;
            }
            let layout = line.layout(
                self.font_system,
                self.metrics.font_size,
                self.width
            );
            if line_i == cursor.line {
                let layout_cursor = self.layout_cursor(&cursor);
                layout_i += layout_cursor.layout as i32;
                break;
            } else {
                layout_i += layout.len() as i32;
            }
        }

        if reshaped > 0 {
            #[cfg(feature = "std")]
            log::debug!("shape_until_cursor {}: {:?}", reshaped, instant.elapsed());
            self.redraw = true;
        }

        let lines = self.visible_lines();
        if layout_i < self.scroll {
            self.scroll = layout_i;
        } else if layout_i >= self.scroll + lines {
            self.scroll = layout_i - (lines - 1);
        }

        self.shape_until_scroll();
    }
More examples
Hide additional examples
src/edit/editor.rs (line 270)
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
    fn action(&mut self, action: Action) {
        let old_cursor = self.cursor;

        match action {
            Action::Previous => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index > 0 {
                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().grapheme_indices(true) {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;
                    self.buffer.set_redraw(true);
                } else if self.cursor.line > 0 {
                    self.cursor.line -= 1;
                    self.cursor.index = self.buffer.lines[self.cursor.line].text().len();
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Next => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index < line.text().len() {
                    for (i, c) in line.text().grapheme_indices(true) {
                        if i == self.cursor.index {
                            self.cursor.index += c.len();
                            self.buffer.set_redraw(true);
                            break;
                        }
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    self.cursor.line += 1;
                    self.cursor.index = 0;
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Left => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Next);
                    } else {
                        self.action(Action::Previous);
                    }
                }
            },
            Action::Right => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Previous);
                    } else {
                        self.action(Action::Next);
                    }
                }
            },
            Action::Up => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout > 0 {
                    cursor.layout -= 1;
                } else if cursor.line > 0 {
                    cursor.line -= 1;
                    cursor.layout = usize::max_value();
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Down => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                let layout_len = self.buffer.line_layout(cursor.line).expect("layout not found").len();

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout + 1 < layout_len {
                    cursor.layout += 1;
                } else if cursor.line + 1 < self.buffer.lines.len() {
                    cursor.line += 1;
                    cursor.layout = 0;
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Home => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = 0;
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            },
            Action::End => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = usize::max_value();
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            }
            Action::PageUp => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll -= self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::PageDown => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll += self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::Escape => {
                if self.select_opt.take().is_some() {
                    self.buffer.set_redraw(true);
                }
            },
            Action::Insert(character) => {
                if character.is_control()
                && !['\t', '\u{92}'].contains(&character)
                {
                    // Filter out special chars (except for tab), use Action instead
                    log::debug!("Refusing to insert control character {:?}", character);
                } else {
                    self.delete_selection();

                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Collect text after insertion as a line
                    let after = line.split_off(self.cursor.index);

                    // Append the inserted text
                    line.append(BufferLine::new(
                        character.to_string(),
                        AttrsList::new(line.attrs_list().defaults() /*TODO: provide attrs?*/)
                    ));

                    // Append the text after insertion
                    line.append(after);

                    self.cursor.index += character.len_utf8();
                }
            },
            Action::Enter => {
                self.delete_selection();

                let new_line = self.buffer.lines[self.cursor.line].split_off(self.cursor.index);

                self.cursor.line += 1;
                self.cursor.index = 0;

                self.buffer.lines.insert(self.cursor.line, new_line);
            },
            Action::Backspace => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index > 0 {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Get text line after cursor
                    let after = line.split_off(self.cursor.index);

                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().char_indices() {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;

                    // Remove character
                    line.split_off(self.cursor.index);

                    // Add text after cursor
                    line.append(after);
                } else if self.cursor.line > 0 {
                    let mut line_index = self.cursor.line;
                    let old_line = self.buffer.lines.remove(line_index);
                    line_index -= 1;

                    let line = &mut self.buffer.lines[line_index];

                    self.cursor.line = line_index;
                    self.cursor.index = line.text().len();

                    line.append(old_line);
                }
            },
            Action::Delete => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index < self.buffer.lines[self.cursor.line].text().len() {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    let range_opt = line
                        .text()
                        .grapheme_indices(true)
                        .take_while(|(i, _)| *i <= self.cursor.index)
                        .last()
                        .map(|(i, c)| {
                            i..(i + c.len())
                        });

                    if let Some(range) = range_opt {
                        self.cursor.index = range.start;

                        // Get text after deleted EGC
                        let after = line.split_off(range.end);

                        // Delete EGC
                        line.split_off(range.start);

                        // Add text after deleted EGC
                        line.append(after);
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    let old_line = self.buffer.lines.remove(self.cursor.line + 1);
                    self.buffer.lines[self.cursor.line].append(old_line);
                }
            },
            Action::Click { x, y } => {
                self.select_opt = None;

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Drag { x, y } => {
                if self.select_opt.is_none() {
                    self.select_opt = Some(self.cursor);
                    self.buffer.set_redraw(true);
                }

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Scroll { lines } => {
                let mut scroll = self.buffer.scroll();
                scroll += lines;
                self.buffer.set_scroll(scroll);
            }
        }

        if old_cursor != self.cursor {
            self.cursor_moved = true;

            /*TODO
            if let Some(glyph) = run.glyphs.get(new_cursor_glyph) {
                let font_opt = self.buffer.font_system().get_font(glyph.cache_key.font_id);
                let text_glyph = &run.text[glyph.start..glyph.end];
                log::debug!(
                    "{}, {}: '{}' ('{}'): '{}' ({:?})",
                    self.cursor.line,
                    self.cursor.index,
                    font_opt.as_ref().map_or("?", |font| font.info.family.as_str()),
                    font_opt.as_ref().map_or("?", |font| font.info.post_script_name.as_str()),
                    text_glyph,
                    text_glyph
                );
            }
            */
        }
    }

Get FontSystem used by this Buffer

Shape the provided line index and return the result

Lay out the provided line index and return the result

Examples found in repository?
src/edit/editor.rs (line 34)
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
    fn set_layout_cursor(&mut self, cursor: LayoutCursor) {
        let layout = self.buffer.line_layout(cursor.line).expect("layout not found");

        let layout_line = match layout.get(cursor.layout) {
            Some(some) => some,
            None => match layout.last() {
                Some(some) => some,
                None => todo!("layout cursor in line with no layouts"),
            }
        };

        let new_index = match layout_line.glyphs.get(cursor.glyph) {
            Some(glyph) => glyph.start,
            None => match layout_line.glyphs.last() {
                Some(glyph) => glyph.end,
                //TODO: is this correct?
                None => 0,
            }
        };

        if self.cursor.line != cursor.line || self.cursor.index != new_index {
            self.cursor.line = cursor.line;
            self.cursor.index = new_index;
            self.buffer.set_redraw(true);
        }
    }
}

impl<'a> Edit<'a> for Editor<'a> {
    fn buffer(&self) -> &Buffer<'a> {
        &self.buffer
    }

    fn buffer_mut(&mut self) -> &mut Buffer<'a> {
        &mut self.buffer
    }

    fn cursor(&self) -> Cursor {
        self.cursor
    }

    fn select_opt(&self) -> Option<Cursor> {
        self.select_opt
    }

    fn set_select_opt(&mut self, select_opt: Option<Cursor>) {
        if self.select_opt != select_opt {
            self.select_opt = select_opt;
            self.buffer.set_redraw(true);
        }
    }

    fn shape_as_needed(&mut self) {
        if self.cursor_moved {
            self.buffer.shape_until_cursor(self.cursor);
            self.cursor_moved = false;
        } else {
            self.buffer.shape_until_scroll();
        }
    }

    fn copy_selection(&mut self) -> Option<String> {
        let select = self.select_opt?;

        let (start, end) = match select.line.cmp(&self.cursor.line) {
            cmp::Ordering::Greater => (self.cursor, select),
            cmp::Ordering::Less => (select, self.cursor),
            cmp::Ordering::Equal => {
                /* select.line == self.cursor.line */
                if select.index < self.cursor.index {
                    (select, self.cursor)
                } else {
                    /* select.index >= self.cursor.index */
                    (self.cursor, select)
                }
            }
        };

        let mut selection = String::new();
        // Take the selection from the first line
        {
            // Add selected part of line to string
            if start.line == end.line {
                selection.push_str(&self.buffer.lines[start.line].text()[start.index..end.index]);
            } else {
                selection.push_str(&self.buffer.lines[start.line].text()[start.index..]);
                selection.push('\n');
            }
        }

        // Take the selection from all interior lines (if they exist)
        for line_i in start.line + 1..end.line {
            selection.push_str(self.buffer.lines[line_i].text());
            selection.push('\n');
        }

        // Take the selection from the last line
        if end.line > start.line {
            // Add selected part of line to string
            selection.push_str(&self.buffer.lines[end.line].text()[..end.index]);
        }

        Some(selection)
    }

    fn delete_selection(&mut self) -> bool {
        let select = match self.select_opt.take() {
            Some(some) => some,
            None => return false,
        };

        let (start, end) = match select.line.cmp(&self.cursor.line) {
            cmp::Ordering::Greater => (self.cursor, select),
            cmp::Ordering::Less => (select, self.cursor),
            cmp::Ordering::Equal => {
                /* select.line == self.cursor.line */
                if select.index < self.cursor.index {
                    (select, self.cursor)
                } else {
                    /* select.index >= self.cursor.index */
                    (self.cursor, select)
                }
            }
        };

        // Reset cursor to start of selection
        self.cursor = start;

        // Delete the selection from the last line
        let end_line_opt = if end.line > start.line {
            // Get part of line after selection
            let after = self.buffer.lines[end.line].split_off(end.index);

            // Remove end line
            self.buffer.lines.remove(end.line);

            Some(after)
        } else {
            None
        };

        // Delete interior lines (in reverse for safety)
        for line_i in (start.line + 1..end.line).rev() {
            self.buffer.lines.remove(line_i);
        }

        // Delete the selection from the first line
        {
            // Get part after selection if start line is also end line
            let after_opt = if start.line == end.line {
                Some(self.buffer.lines[start.line].split_off(end.index))
            } else {
                None
            };

            // Delete selected part of line
            self.buffer.lines[start.line].split_off(start.index);

            // Re-add part of line after selection
            if let Some(after) = after_opt {
                self.buffer.lines[start.line].append(after);
            }

            // Re-add valid parts of end line
            if let Some(end_line) = end_line_opt {
                self.buffer.lines[start.line].append(end_line);
            }
        }

        true
    }

    fn action(&mut self, action: Action) {
        let old_cursor = self.cursor;

        match action {
            Action::Previous => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index > 0 {
                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().grapheme_indices(true) {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;
                    self.buffer.set_redraw(true);
                } else if self.cursor.line > 0 {
                    self.cursor.line -= 1;
                    self.cursor.index = self.buffer.lines[self.cursor.line].text().len();
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Next => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index < line.text().len() {
                    for (i, c) in line.text().grapheme_indices(true) {
                        if i == self.cursor.index {
                            self.cursor.index += c.len();
                            self.buffer.set_redraw(true);
                            break;
                        }
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    self.cursor.line += 1;
                    self.cursor.index = 0;
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Left => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Next);
                    } else {
                        self.action(Action::Previous);
                    }
                }
            },
            Action::Right => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Previous);
                    } else {
                        self.action(Action::Next);
                    }
                }
            },
            Action::Up => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout > 0 {
                    cursor.layout -= 1;
                } else if cursor.line > 0 {
                    cursor.line -= 1;
                    cursor.layout = usize::max_value();
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Down => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                let layout_len = self.buffer.line_layout(cursor.line).expect("layout not found").len();

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout + 1 < layout_len {
                    cursor.layout += 1;
                } else if cursor.line + 1 < self.buffer.lines.len() {
                    cursor.line += 1;
                    cursor.layout = 0;
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Home => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = 0;
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            },
            Action::End => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = usize::max_value();
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            }
            Action::PageUp => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll -= self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::PageDown => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll += self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::Escape => {
                if self.select_opt.take().is_some() {
                    self.buffer.set_redraw(true);
                }
            },
            Action::Insert(character) => {
                if character.is_control()
                && !['\t', '\u{92}'].contains(&character)
                {
                    // Filter out special chars (except for tab), use Action instead
                    log::debug!("Refusing to insert control character {:?}", character);
                } else {
                    self.delete_selection();

                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Collect text after insertion as a line
                    let after = line.split_off(self.cursor.index);

                    // Append the inserted text
                    line.append(BufferLine::new(
                        character.to_string(),
                        AttrsList::new(line.attrs_list().defaults() /*TODO: provide attrs?*/)
                    ));

                    // Append the text after insertion
                    line.append(after);

                    self.cursor.index += character.len_utf8();
                }
            },
            Action::Enter => {
                self.delete_selection();

                let new_line = self.buffer.lines[self.cursor.line].split_off(self.cursor.index);

                self.cursor.line += 1;
                self.cursor.index = 0;

                self.buffer.lines.insert(self.cursor.line, new_line);
            },
            Action::Backspace => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index > 0 {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Get text line after cursor
                    let after = line.split_off(self.cursor.index);

                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().char_indices() {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;

                    // Remove character
                    line.split_off(self.cursor.index);

                    // Add text after cursor
                    line.append(after);
                } else if self.cursor.line > 0 {
                    let mut line_index = self.cursor.line;
                    let old_line = self.buffer.lines.remove(line_index);
                    line_index -= 1;

                    let line = &mut self.buffer.lines[line_index];

                    self.cursor.line = line_index;
                    self.cursor.index = line.text().len();

                    line.append(old_line);
                }
            },
            Action::Delete => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index < self.buffer.lines[self.cursor.line].text().len() {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    let range_opt = line
                        .text()
                        .grapheme_indices(true)
                        .take_while(|(i, _)| *i <= self.cursor.index)
                        .last()
                        .map(|(i, c)| {
                            i..(i + c.len())
                        });

                    if let Some(range) = range_opt {
                        self.cursor.index = range.start;

                        // Get text after deleted EGC
                        let after = line.split_off(range.end);

                        // Delete EGC
                        line.split_off(range.start);

                        // Add text after deleted EGC
                        line.append(after);
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    let old_line = self.buffer.lines.remove(self.cursor.line + 1);
                    self.buffer.lines[self.cursor.line].append(old_line);
                }
            },
            Action::Click { x, y } => {
                self.select_opt = None;

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Drag { x, y } => {
                if self.select_opt.is_none() {
                    self.select_opt = Some(self.cursor);
                    self.buffer.set_redraw(true);
                }

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Scroll { lines } => {
                let mut scroll = self.buffer.scroll();
                scroll += lines;
                self.buffer.set_scroll(scroll);
            }
        }

        if old_cursor != self.cursor {
            self.cursor_moved = true;

            /*TODO
            if let Some(glyph) = run.glyphs.get(new_cursor_glyph) {
                let font_opt = self.buffer.font_system().get_font(glyph.cache_key.font_id);
                let text_glyph = &run.text[glyph.start..glyph.end];
                log::debug!(
                    "{}, {}: '{}' ('{}'): '{}' ({:?})",
                    self.cursor.line,
                    self.cursor.index,
                    font_opt.as_ref().map_or("?", |font| font.info.family.as_str()),
                    font_opt.as_ref().map_or("?", |font| font.info.post_script_name.as_str()),
                    text_glyph,
                    text_glyph
                );
            }
            */
        }
    }

Get the current Metrics

Examples found in repository?
src/edit/editor.rs (line 508)
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
    fn draw<F>(&self, cache: &mut crate::SwashCache, color: Color, mut f: F)
        where F: FnMut(i32, i32, u32, u32, Color)
    {
        let font_size = self.buffer.metrics().font_size;
        let line_height = self.buffer.metrics().line_height;

        for run in self.buffer.layout_runs() {
            let line_i = run.line_i;
            let line_y = run.line_y;

            let cursor_glyph_opt = |cursor: &Cursor| -> Option<(usize, f32)> {
                if cursor.line == line_i {
                    for (glyph_i, glyph) in run.glyphs.iter().enumerate() {
                        if cursor.index == glyph.start {
                            return Some((glyph_i, 0.0));
                        } else if cursor.index > glyph.start && cursor.index < glyph.end {
                            // Guess x offset based on characters
                            let mut before = 0;
                            let mut total = 0;

                            let cluster = &run.text[glyph.start..glyph.end];
                            for (i, _) in cluster.grapheme_indices(true) {
                                if glyph.start + i < cursor.index {
                                    before += 1;
                                }
                                total += 1;
                            }

                            let offset = glyph.w * (before as f32) / (total as f32);
                            return Some((glyph_i, offset));
                        }
                    }
                    match run.glyphs.last() {
                        Some(glyph) => {
                            if cursor.index == glyph.end {
                                return Some((run.glyphs.len(), 0.0));
                            }
                        },
                        None => {
                            return Some((0, 0.0));
                        }
                    }
                }
                None
            };

            // Highlight selection (TODO: HIGHLIGHT COLOR!)
            if let Some(select) = self.select_opt {
                let (start, end) = match select.line.cmp(&self.cursor.line) {
                    cmp::Ordering::Greater => (self.cursor, select),
                    cmp::Ordering::Less => (select, self.cursor),
                    cmp::Ordering::Equal => {
                        /* select.line == self.cursor.line */
                        if select.index < self.cursor.index {
                            (select, self.cursor)
                        } else {
                            /* select.index >= self.cursor.index */
                            (self.cursor, select)
                        }
                    }
                };

                if line_i >= start.line && line_i <= end.line {
                    let mut range_opt = None;
                    for glyph in run.glyphs.iter() {
                        // Guess x offset based on characters
                        let cluster = &run.text[glyph.start..glyph.end];
                        let total = cluster.grapheme_indices(true).count();
                        let mut c_x = glyph.x;
                        let c_w = glyph.w / total as f32;
                        for (i, c) in cluster.grapheme_indices(true) {
                            let c_start = glyph.start + i;
                            let c_end = glyph.start + i + c.len();
                            if (start.line != line_i || c_end > start.index)
                            && (end.line != line_i || c_start < end.index) {
                                range_opt = match range_opt.take() {
                                    Some((min, max)) => Some((
                                        cmp::min(min, c_x as i32),
                                        cmp::max(max, (c_x + c_w) as i32),
                                    )),
                                    None => Some((
                                        c_x as i32,
                                        (c_x + c_w) as i32,
                                    ))
                                };
                            } else if let Some((min, max)) = range_opt.take() {
                                f(
                                    min,
                                    line_y - font_size,
                                    cmp::max(0, max - min) as u32,
                                    line_height as u32,
                                    Color::rgba(color.r(), color.g(), color.b(), 0x33)
                                );
                            }
                            c_x += c_w;
                        }
                    }

                    if run.glyphs.is_empty() && end.line > line_i{
                        // Highlight all of internal empty lines
                        range_opt = Some((0, self.buffer.size().0));
                    }

                    if let Some((mut min, mut max)) = range_opt.take() {
                        if end.line > line_i {
                            // Draw to end of line
                            if run.rtl {
                                min = 0;
                            } else {
                                max = self.buffer.size().0;
                            }
                        }
                        f(
                            min,
                            line_y - font_size,
                            cmp::max(0, max - min) as u32,
                            line_height as u32,
                            Color::rgba(color.r(), color.g(), color.b(), 0x33)
                        );
                    }
                }
            }

            // Draw cursor
            if let Some((cursor_glyph, cursor_glyph_offset)) = cursor_glyph_opt(&self.cursor) {
                let x = match run.glyphs.get(cursor_glyph) {
                    Some(glyph) => {
                        // Start of detected glyph
                        if glyph.level.is_rtl() {
                            (glyph.x + glyph.w - cursor_glyph_offset) as i32
                        } else {
                            (glyph.x + cursor_glyph_offset) as i32
                        }
                    },
                    None => match run.glyphs.last() {
                        Some(glyph) => {
                            // End of last glyph
                            if glyph.level.is_rtl() {
                                glyph.x as i32
                            } else {
                                (glyph.x + glyph.w) as i32
                            }
                        },
                        None => {
                            // Start of empty line
                            0
                        }
                    }
                };

                f(
                    x,
                    line_y - font_size,
                    1,
                    line_height as u32,
                    color,
                );
            }

            for glyph in run.glyphs.iter() {
                let (cache_key, x_int, y_int) = (glyph.cache_key, glyph.x_int, glyph.y_int);

                let glyph_color = match glyph.color_opt {
                    Some(some) => some,
                    None => color,
                };

                cache.with_pixels(cache_key, glyph_color, |x, y, color| {
                    f(x_int + x, line_y + y_int + y, 1, 1, color);
                });
            }
        }
    }

Set the current Metrics

Get the current buffer dimensions (width, height)

Examples found in repository?
src/edit/editor.rs (line 605)
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
    fn draw<F>(&self, cache: &mut crate::SwashCache, color: Color, mut f: F)
        where F: FnMut(i32, i32, u32, u32, Color)
    {
        let font_size = self.buffer.metrics().font_size;
        let line_height = self.buffer.metrics().line_height;

        for run in self.buffer.layout_runs() {
            let line_i = run.line_i;
            let line_y = run.line_y;

            let cursor_glyph_opt = |cursor: &Cursor| -> Option<(usize, f32)> {
                if cursor.line == line_i {
                    for (glyph_i, glyph) in run.glyphs.iter().enumerate() {
                        if cursor.index == glyph.start {
                            return Some((glyph_i, 0.0));
                        } else if cursor.index > glyph.start && cursor.index < glyph.end {
                            // Guess x offset based on characters
                            let mut before = 0;
                            let mut total = 0;

                            let cluster = &run.text[glyph.start..glyph.end];
                            for (i, _) in cluster.grapheme_indices(true) {
                                if glyph.start + i < cursor.index {
                                    before += 1;
                                }
                                total += 1;
                            }

                            let offset = glyph.w * (before as f32) / (total as f32);
                            return Some((glyph_i, offset));
                        }
                    }
                    match run.glyphs.last() {
                        Some(glyph) => {
                            if cursor.index == glyph.end {
                                return Some((run.glyphs.len(), 0.0));
                            }
                        },
                        None => {
                            return Some((0, 0.0));
                        }
                    }
                }
                None
            };

            // Highlight selection (TODO: HIGHLIGHT COLOR!)
            if let Some(select) = self.select_opt {
                let (start, end) = match select.line.cmp(&self.cursor.line) {
                    cmp::Ordering::Greater => (self.cursor, select),
                    cmp::Ordering::Less => (select, self.cursor),
                    cmp::Ordering::Equal => {
                        /* select.line == self.cursor.line */
                        if select.index < self.cursor.index {
                            (select, self.cursor)
                        } else {
                            /* select.index >= self.cursor.index */
                            (self.cursor, select)
                        }
                    }
                };

                if line_i >= start.line && line_i <= end.line {
                    let mut range_opt = None;
                    for glyph in run.glyphs.iter() {
                        // Guess x offset based on characters
                        let cluster = &run.text[glyph.start..glyph.end];
                        let total = cluster.grapheme_indices(true).count();
                        let mut c_x = glyph.x;
                        let c_w = glyph.w / total as f32;
                        for (i, c) in cluster.grapheme_indices(true) {
                            let c_start = glyph.start + i;
                            let c_end = glyph.start + i + c.len();
                            if (start.line != line_i || c_end > start.index)
                            && (end.line != line_i || c_start < end.index) {
                                range_opt = match range_opt.take() {
                                    Some((min, max)) => Some((
                                        cmp::min(min, c_x as i32),
                                        cmp::max(max, (c_x + c_w) as i32),
                                    )),
                                    None => Some((
                                        c_x as i32,
                                        (c_x + c_w) as i32,
                                    ))
                                };
                            } else if let Some((min, max)) = range_opt.take() {
                                f(
                                    min,
                                    line_y - font_size,
                                    cmp::max(0, max - min) as u32,
                                    line_height as u32,
                                    Color::rgba(color.r(), color.g(), color.b(), 0x33)
                                );
                            }
                            c_x += c_w;
                        }
                    }

                    if run.glyphs.is_empty() && end.line > line_i{
                        // Highlight all of internal empty lines
                        range_opt = Some((0, self.buffer.size().0));
                    }

                    if let Some((mut min, mut max)) = range_opt.take() {
                        if end.line > line_i {
                            // Draw to end of line
                            if run.rtl {
                                min = 0;
                            } else {
                                max = self.buffer.size().0;
                            }
                        }
                        f(
                            min,
                            line_y - font_size,
                            cmp::max(0, max - min) as u32,
                            line_height as u32,
                            Color::rgba(color.r(), color.g(), color.b(), 0x33)
                        );
                    }
                }
            }

            // Draw cursor
            if let Some((cursor_glyph, cursor_glyph_offset)) = cursor_glyph_opt(&self.cursor) {
                let x = match run.glyphs.get(cursor_glyph) {
                    Some(glyph) => {
                        // Start of detected glyph
                        if glyph.level.is_rtl() {
                            (glyph.x + glyph.w - cursor_glyph_offset) as i32
                        } else {
                            (glyph.x + cursor_glyph_offset) as i32
                        }
                    },
                    None => match run.glyphs.last() {
                        Some(glyph) => {
                            // End of last glyph
                            if glyph.level.is_rtl() {
                                glyph.x as i32
                            } else {
                                (glyph.x + glyph.w) as i32
                            }
                        },
                        None => {
                            // Start of empty line
                            0
                        }
                    }
                };

                f(
                    x,
                    line_y - font_size,
                    1,
                    line_height as u32,
                    color,
                );
            }

            for glyph in run.glyphs.iter() {
                let (cache_key, x_int, y_int) = (glyph.cache_key, glyph.x_int, glyph.y_int);

                let glyph_color = match glyph.color_opt {
                    Some(some) => some,
                    None => color,
                };

                cache.with_pixels(cache_key, glyph_color, |x, y, color| {
                    f(x_int + x, line_y + y_int + y, 1, 1, color);
                });
            }
        }
    }

Set the current buffer dimensions

Get the current scroll location

Examples found in repository?
src/edit/editor.rs (line 330)
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
    fn action(&mut self, action: Action) {
        let old_cursor = self.cursor;

        match action {
            Action::Previous => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index > 0 {
                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().grapheme_indices(true) {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;
                    self.buffer.set_redraw(true);
                } else if self.cursor.line > 0 {
                    self.cursor.line -= 1;
                    self.cursor.index = self.buffer.lines[self.cursor.line].text().len();
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Next => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index < line.text().len() {
                    for (i, c) in line.text().grapheme_indices(true) {
                        if i == self.cursor.index {
                            self.cursor.index += c.len();
                            self.buffer.set_redraw(true);
                            break;
                        }
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    self.cursor.line += 1;
                    self.cursor.index = 0;
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Left => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Next);
                    } else {
                        self.action(Action::Previous);
                    }
                }
            },
            Action::Right => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Previous);
                    } else {
                        self.action(Action::Next);
                    }
                }
            },
            Action::Up => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout > 0 {
                    cursor.layout -= 1;
                } else if cursor.line > 0 {
                    cursor.line -= 1;
                    cursor.layout = usize::max_value();
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Down => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                let layout_len = self.buffer.line_layout(cursor.line).expect("layout not found").len();

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout + 1 < layout_len {
                    cursor.layout += 1;
                } else if cursor.line + 1 < self.buffer.lines.len() {
                    cursor.line += 1;
                    cursor.layout = 0;
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Home => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = 0;
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            },
            Action::End => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = usize::max_value();
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            }
            Action::PageUp => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll -= self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::PageDown => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll += self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::Escape => {
                if self.select_opt.take().is_some() {
                    self.buffer.set_redraw(true);
                }
            },
            Action::Insert(character) => {
                if character.is_control()
                && !['\t', '\u{92}'].contains(&character)
                {
                    // Filter out special chars (except for tab), use Action instead
                    log::debug!("Refusing to insert control character {:?}", character);
                } else {
                    self.delete_selection();

                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Collect text after insertion as a line
                    let after = line.split_off(self.cursor.index);

                    // Append the inserted text
                    line.append(BufferLine::new(
                        character.to_string(),
                        AttrsList::new(line.attrs_list().defaults() /*TODO: provide attrs?*/)
                    ));

                    // Append the text after insertion
                    line.append(after);

                    self.cursor.index += character.len_utf8();
                }
            },
            Action::Enter => {
                self.delete_selection();

                let new_line = self.buffer.lines[self.cursor.line].split_off(self.cursor.index);

                self.cursor.line += 1;
                self.cursor.index = 0;

                self.buffer.lines.insert(self.cursor.line, new_line);
            },
            Action::Backspace => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index > 0 {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Get text line after cursor
                    let after = line.split_off(self.cursor.index);

                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().char_indices() {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;

                    // Remove character
                    line.split_off(self.cursor.index);

                    // Add text after cursor
                    line.append(after);
                } else if self.cursor.line > 0 {
                    let mut line_index = self.cursor.line;
                    let old_line = self.buffer.lines.remove(line_index);
                    line_index -= 1;

                    let line = &mut self.buffer.lines[line_index];

                    self.cursor.line = line_index;
                    self.cursor.index = line.text().len();

                    line.append(old_line);
                }
            },
            Action::Delete => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index < self.buffer.lines[self.cursor.line].text().len() {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    let range_opt = line
                        .text()
                        .grapheme_indices(true)
                        .take_while(|(i, _)| *i <= self.cursor.index)
                        .last()
                        .map(|(i, c)| {
                            i..(i + c.len())
                        });

                    if let Some(range) = range_opt {
                        self.cursor.index = range.start;

                        // Get text after deleted EGC
                        let after = line.split_off(range.end);

                        // Delete EGC
                        line.split_off(range.start);

                        // Add text after deleted EGC
                        line.append(after);
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    let old_line = self.buffer.lines.remove(self.cursor.line + 1);
                    self.buffer.lines[self.cursor.line].append(old_line);
                }
            },
            Action::Click { x, y } => {
                self.select_opt = None;

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Drag { x, y } => {
                if self.select_opt.is_none() {
                    self.select_opt = Some(self.cursor);
                    self.buffer.set_redraw(true);
                }

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Scroll { lines } => {
                let mut scroll = self.buffer.scroll();
                scroll += lines;
                self.buffer.set_scroll(scroll);
            }
        }

        if old_cursor != self.cursor {
            self.cursor_moved = true;

            /*TODO
            if let Some(glyph) = run.glyphs.get(new_cursor_glyph) {
                let font_opt = self.buffer.font_system().get_font(glyph.cache_key.font_id);
                let text_glyph = &run.text[glyph.start..glyph.end];
                log::debug!(
                    "{}, {}: '{}' ('{}'): '{}' ({:?})",
                    self.cursor.line,
                    self.cursor.index,
                    font_opt.as_ref().map_or("?", |font| font.info.family.as_str()),
                    font_opt.as_ref().map_or("?", |font| font.info.post_script_name.as_str()),
                    text_glyph,
                    text_glyph
                );
            }
            */
        }
    }

Set the current scroll location

Examples found in repository?
src/edit/editor.rs (line 332)
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
    fn action(&mut self, action: Action) {
        let old_cursor = self.cursor;

        match action {
            Action::Previous => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index > 0 {
                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().grapheme_indices(true) {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;
                    self.buffer.set_redraw(true);
                } else if self.cursor.line > 0 {
                    self.cursor.line -= 1;
                    self.cursor.index = self.buffer.lines[self.cursor.line].text().len();
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Next => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index < line.text().len() {
                    for (i, c) in line.text().grapheme_indices(true) {
                        if i == self.cursor.index {
                            self.cursor.index += c.len();
                            self.buffer.set_redraw(true);
                            break;
                        }
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    self.cursor.line += 1;
                    self.cursor.index = 0;
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Left => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Next);
                    } else {
                        self.action(Action::Previous);
                    }
                }
            },
            Action::Right => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Previous);
                    } else {
                        self.action(Action::Next);
                    }
                }
            },
            Action::Up => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout > 0 {
                    cursor.layout -= 1;
                } else if cursor.line > 0 {
                    cursor.line -= 1;
                    cursor.layout = usize::max_value();
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Down => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                let layout_len = self.buffer.line_layout(cursor.line).expect("layout not found").len();

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout + 1 < layout_len {
                    cursor.layout += 1;
                } else if cursor.line + 1 < self.buffer.lines.len() {
                    cursor.line += 1;
                    cursor.layout = 0;
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Home => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = 0;
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            },
            Action::End => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = usize::max_value();
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            }
            Action::PageUp => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll -= self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::PageDown => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll += self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::Escape => {
                if self.select_opt.take().is_some() {
                    self.buffer.set_redraw(true);
                }
            },
            Action::Insert(character) => {
                if character.is_control()
                && !['\t', '\u{92}'].contains(&character)
                {
                    // Filter out special chars (except for tab), use Action instead
                    log::debug!("Refusing to insert control character {:?}", character);
                } else {
                    self.delete_selection();

                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Collect text after insertion as a line
                    let after = line.split_off(self.cursor.index);

                    // Append the inserted text
                    line.append(BufferLine::new(
                        character.to_string(),
                        AttrsList::new(line.attrs_list().defaults() /*TODO: provide attrs?*/)
                    ));

                    // Append the text after insertion
                    line.append(after);

                    self.cursor.index += character.len_utf8();
                }
            },
            Action::Enter => {
                self.delete_selection();

                let new_line = self.buffer.lines[self.cursor.line].split_off(self.cursor.index);

                self.cursor.line += 1;
                self.cursor.index = 0;

                self.buffer.lines.insert(self.cursor.line, new_line);
            },
            Action::Backspace => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index > 0 {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Get text line after cursor
                    let after = line.split_off(self.cursor.index);

                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().char_indices() {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;

                    // Remove character
                    line.split_off(self.cursor.index);

                    // Add text after cursor
                    line.append(after);
                } else if self.cursor.line > 0 {
                    let mut line_index = self.cursor.line;
                    let old_line = self.buffer.lines.remove(line_index);
                    line_index -= 1;

                    let line = &mut self.buffer.lines[line_index];

                    self.cursor.line = line_index;
                    self.cursor.index = line.text().len();

                    line.append(old_line);
                }
            },
            Action::Delete => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index < self.buffer.lines[self.cursor.line].text().len() {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    let range_opt = line
                        .text()
                        .grapheme_indices(true)
                        .take_while(|(i, _)| *i <= self.cursor.index)
                        .last()
                        .map(|(i, c)| {
                            i..(i + c.len())
                        });

                    if let Some(range) = range_opt {
                        self.cursor.index = range.start;

                        // Get text after deleted EGC
                        let after = line.split_off(range.end);

                        // Delete EGC
                        line.split_off(range.start);

                        // Add text after deleted EGC
                        line.append(after);
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    let old_line = self.buffer.lines.remove(self.cursor.line + 1);
                    self.buffer.lines[self.cursor.line].append(old_line);
                }
            },
            Action::Click { x, y } => {
                self.select_opt = None;

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Drag { x, y } => {
                if self.select_opt.is_none() {
                    self.select_opt = Some(self.cursor);
                    self.buffer.set_redraw(true);
                }

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Scroll { lines } => {
                let mut scroll = self.buffer.scroll();
                scroll += lines;
                self.buffer.set_scroll(scroll);
            }
        }

        if old_cursor != self.cursor {
            self.cursor_moved = true;

            /*TODO
            if let Some(glyph) = run.glyphs.get(new_cursor_glyph) {
                let font_opt = self.buffer.font_system().get_font(glyph.cache_key.font_id);
                let text_glyph = &run.text[glyph.start..glyph.end];
                log::debug!(
                    "{}, {}: '{}' ('{}'): '{}' ({:?})",
                    self.cursor.line,
                    self.cursor.index,
                    font_opt.as_ref().map_or("?", |font| font.info.family.as_str()),
                    font_opt.as_ref().map_or("?", |font| font.info.post_script_name.as_str()),
                    text_glyph,
                    text_glyph
                );
            }
            */
        }
    }

Get the number of lines that can be viewed in the buffer

Examples found in repository?
src/buffer.rs (line 269)
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
    pub fn shape_until_cursor(&mut self, cursor: Cursor) {
        #[cfg(feature = "std")]
        let instant = std::time::Instant::now();

        let mut reshaped = 0;
        let mut layout_i = 0;
        for (line_i, line) in self.lines.iter_mut().enumerate() {
            if line_i > cursor.line {
                break;
            }

            if line.shape_opt().is_none() {
                reshaped += 1;
            }
            let layout = line.layout(
                self.font_system,
                self.metrics.font_size,
                self.width
            );
            if line_i == cursor.line {
                let layout_cursor = self.layout_cursor(&cursor);
                layout_i += layout_cursor.layout as i32;
                break;
            } else {
                layout_i += layout.len() as i32;
            }
        }

        if reshaped > 0 {
            #[cfg(feature = "std")]
            log::debug!("shape_until_cursor {}: {:?}", reshaped, instant.elapsed());
            self.redraw = true;
        }

        let lines = self.visible_lines();
        if layout_i < self.scroll {
            self.scroll = layout_i;
        } else if layout_i >= self.scroll + lines {
            self.scroll = layout_i - (lines - 1);
        }

        self.shape_until_scroll();
    }

    /// Shape lines until scroll
    pub fn shape_until_scroll(&mut self) {
        let lines = self.visible_lines();

        let scroll_end = self.scroll + lines;
        let total_layout = self.shape_until(scroll_end);

        self.scroll = cmp::max(
            0,
            cmp::min(
                total_layout - (lines - 1),
                self.scroll,
            ),
        );
    }
More examples
Hide additional examples
src/edit/editor.rs (line 331)
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
    fn action(&mut self, action: Action) {
        let old_cursor = self.cursor;

        match action {
            Action::Previous => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index > 0 {
                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().grapheme_indices(true) {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;
                    self.buffer.set_redraw(true);
                } else if self.cursor.line > 0 {
                    self.cursor.line -= 1;
                    self.cursor.index = self.buffer.lines[self.cursor.line].text().len();
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Next => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index < line.text().len() {
                    for (i, c) in line.text().grapheme_indices(true) {
                        if i == self.cursor.index {
                            self.cursor.index += c.len();
                            self.buffer.set_redraw(true);
                            break;
                        }
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    self.cursor.line += 1;
                    self.cursor.index = 0;
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Left => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Next);
                    } else {
                        self.action(Action::Previous);
                    }
                }
            },
            Action::Right => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Previous);
                    } else {
                        self.action(Action::Next);
                    }
                }
            },
            Action::Up => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout > 0 {
                    cursor.layout -= 1;
                } else if cursor.line > 0 {
                    cursor.line -= 1;
                    cursor.layout = usize::max_value();
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Down => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                let layout_len = self.buffer.line_layout(cursor.line).expect("layout not found").len();

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout + 1 < layout_len {
                    cursor.layout += 1;
                } else if cursor.line + 1 < self.buffer.lines.len() {
                    cursor.line += 1;
                    cursor.layout = 0;
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Home => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = 0;
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            },
            Action::End => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = usize::max_value();
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            }
            Action::PageUp => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll -= self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::PageDown => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll += self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::Escape => {
                if self.select_opt.take().is_some() {
                    self.buffer.set_redraw(true);
                }
            },
            Action::Insert(character) => {
                if character.is_control()
                && !['\t', '\u{92}'].contains(&character)
                {
                    // Filter out special chars (except for tab), use Action instead
                    log::debug!("Refusing to insert control character {:?}", character);
                } else {
                    self.delete_selection();

                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Collect text after insertion as a line
                    let after = line.split_off(self.cursor.index);

                    // Append the inserted text
                    line.append(BufferLine::new(
                        character.to_string(),
                        AttrsList::new(line.attrs_list().defaults() /*TODO: provide attrs?*/)
                    ));

                    // Append the text after insertion
                    line.append(after);

                    self.cursor.index += character.len_utf8();
                }
            },
            Action::Enter => {
                self.delete_selection();

                let new_line = self.buffer.lines[self.cursor.line].split_off(self.cursor.index);

                self.cursor.line += 1;
                self.cursor.index = 0;

                self.buffer.lines.insert(self.cursor.line, new_line);
            },
            Action::Backspace => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index > 0 {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Get text line after cursor
                    let after = line.split_off(self.cursor.index);

                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().char_indices() {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;

                    // Remove character
                    line.split_off(self.cursor.index);

                    // Add text after cursor
                    line.append(after);
                } else if self.cursor.line > 0 {
                    let mut line_index = self.cursor.line;
                    let old_line = self.buffer.lines.remove(line_index);
                    line_index -= 1;

                    let line = &mut self.buffer.lines[line_index];

                    self.cursor.line = line_index;
                    self.cursor.index = line.text().len();

                    line.append(old_line);
                }
            },
            Action::Delete => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index < self.buffer.lines[self.cursor.line].text().len() {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    let range_opt = line
                        .text()
                        .grapheme_indices(true)
                        .take_while(|(i, _)| *i <= self.cursor.index)
                        .last()
                        .map(|(i, c)| {
                            i..(i + c.len())
                        });

                    if let Some(range) = range_opt {
                        self.cursor.index = range.start;

                        // Get text after deleted EGC
                        let after = line.split_off(range.end);

                        // Delete EGC
                        line.split_off(range.start);

                        // Add text after deleted EGC
                        line.append(after);
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    let old_line = self.buffer.lines.remove(self.cursor.line + 1);
                    self.buffer.lines[self.cursor.line].append(old_line);
                }
            },
            Action::Click { x, y } => {
                self.select_opt = None;

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Drag { x, y } => {
                if self.select_opt.is_none() {
                    self.select_opt = Some(self.cursor);
                    self.buffer.set_redraw(true);
                }

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Scroll { lines } => {
                let mut scroll = self.buffer.scroll();
                scroll += lines;
                self.buffer.set_scroll(scroll);
            }
        }

        if old_cursor != self.cursor {
            self.cursor_moved = true;

            /*TODO
            if let Some(glyph) = run.glyphs.get(new_cursor_glyph) {
                let font_opt = self.buffer.font_system().get_font(glyph.cache_key.font_id);
                let text_glyph = &run.text[glyph.start..glyph.end];
                log::debug!(
                    "{}, {}: '{}' ('{}'): '{}' ({:?})",
                    self.cursor.line,
                    self.cursor.index,
                    font_opt.as_ref().map_or("?", |font| font.info.family.as_str()),
                    font_opt.as_ref().map_or("?", |font| font.info.post_script_name.as_str()),
                    text_glyph,
                    text_glyph
                );
            }
            */
        }
    }

Set text of buffer, using provided attributes for each line by default

Examples found in repository?
src/buffer.rs (line 177)
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    pub fn new(
        font_system: &'a FontSystem,
        metrics: Metrics,
    ) -> Self {
        let mut buffer = Self {
            font_system,
            lines: Vec::new(),
            metrics,
            width: 0,
            height: 0,
            scroll: 0,
            redraw: false,
        };
        buffer.set_text("", Attrs::new());
        buffer
    }

True if a redraw is needed

Set redraw needed flag

Examples found in repository?
src/edit/editor.rs (line 56)
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
    fn set_layout_cursor(&mut self, cursor: LayoutCursor) {
        let layout = self.buffer.line_layout(cursor.line).expect("layout not found");

        let layout_line = match layout.get(cursor.layout) {
            Some(some) => some,
            None => match layout.last() {
                Some(some) => some,
                None => todo!("layout cursor in line with no layouts"),
            }
        };

        let new_index = match layout_line.glyphs.get(cursor.glyph) {
            Some(glyph) => glyph.start,
            None => match layout_line.glyphs.last() {
                Some(glyph) => glyph.end,
                //TODO: is this correct?
                None => 0,
            }
        };

        if self.cursor.line != cursor.line || self.cursor.index != new_index {
            self.cursor.line = cursor.line;
            self.cursor.index = new_index;
            self.buffer.set_redraw(true);
        }
    }
}

impl<'a> Edit<'a> for Editor<'a> {
    fn buffer(&self) -> &Buffer<'a> {
        &self.buffer
    }

    fn buffer_mut(&mut self) -> &mut Buffer<'a> {
        &mut self.buffer
    }

    fn cursor(&self) -> Cursor {
        self.cursor
    }

    fn select_opt(&self) -> Option<Cursor> {
        self.select_opt
    }

    fn set_select_opt(&mut self, select_opt: Option<Cursor>) {
        if self.select_opt != select_opt {
            self.select_opt = select_opt;
            self.buffer.set_redraw(true);
        }
    }

    fn shape_as_needed(&mut self) {
        if self.cursor_moved {
            self.buffer.shape_until_cursor(self.cursor);
            self.cursor_moved = false;
        } else {
            self.buffer.shape_until_scroll();
        }
    }

    fn copy_selection(&mut self) -> Option<String> {
        let select = self.select_opt?;

        let (start, end) = match select.line.cmp(&self.cursor.line) {
            cmp::Ordering::Greater => (self.cursor, select),
            cmp::Ordering::Less => (select, self.cursor),
            cmp::Ordering::Equal => {
                /* select.line == self.cursor.line */
                if select.index < self.cursor.index {
                    (select, self.cursor)
                } else {
                    /* select.index >= self.cursor.index */
                    (self.cursor, select)
                }
            }
        };

        let mut selection = String::new();
        // Take the selection from the first line
        {
            // Add selected part of line to string
            if start.line == end.line {
                selection.push_str(&self.buffer.lines[start.line].text()[start.index..end.index]);
            } else {
                selection.push_str(&self.buffer.lines[start.line].text()[start.index..]);
                selection.push('\n');
            }
        }

        // Take the selection from all interior lines (if they exist)
        for line_i in start.line + 1..end.line {
            selection.push_str(self.buffer.lines[line_i].text());
            selection.push('\n');
        }

        // Take the selection from the last line
        if end.line > start.line {
            // Add selected part of line to string
            selection.push_str(&self.buffer.lines[end.line].text()[..end.index]);
        }

        Some(selection)
    }

    fn delete_selection(&mut self) -> bool {
        let select = match self.select_opt.take() {
            Some(some) => some,
            None => return false,
        };

        let (start, end) = match select.line.cmp(&self.cursor.line) {
            cmp::Ordering::Greater => (self.cursor, select),
            cmp::Ordering::Less => (select, self.cursor),
            cmp::Ordering::Equal => {
                /* select.line == self.cursor.line */
                if select.index < self.cursor.index {
                    (select, self.cursor)
                } else {
                    /* select.index >= self.cursor.index */
                    (self.cursor, select)
                }
            }
        };

        // Reset cursor to start of selection
        self.cursor = start;

        // Delete the selection from the last line
        let end_line_opt = if end.line > start.line {
            // Get part of line after selection
            let after = self.buffer.lines[end.line].split_off(end.index);

            // Remove end line
            self.buffer.lines.remove(end.line);

            Some(after)
        } else {
            None
        };

        // Delete interior lines (in reverse for safety)
        for line_i in (start.line + 1..end.line).rev() {
            self.buffer.lines.remove(line_i);
        }

        // Delete the selection from the first line
        {
            // Get part after selection if start line is also end line
            let after_opt = if start.line == end.line {
                Some(self.buffer.lines[start.line].split_off(end.index))
            } else {
                None
            };

            // Delete selected part of line
            self.buffer.lines[start.line].split_off(start.index);

            // Re-add part of line after selection
            if let Some(after) = after_opt {
                self.buffer.lines[start.line].append(after);
            }

            // Re-add valid parts of end line
            if let Some(end_line) = end_line_opt {
                self.buffer.lines[start.line].append(end_line);
            }
        }

        true
    }

    fn action(&mut self, action: Action) {
        let old_cursor = self.cursor;

        match action {
            Action::Previous => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index > 0 {
                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().grapheme_indices(true) {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;
                    self.buffer.set_redraw(true);
                } else if self.cursor.line > 0 {
                    self.cursor.line -= 1;
                    self.cursor.index = self.buffer.lines[self.cursor.line].text().len();
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Next => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index < line.text().len() {
                    for (i, c) in line.text().grapheme_indices(true) {
                        if i == self.cursor.index {
                            self.cursor.index += c.len();
                            self.buffer.set_redraw(true);
                            break;
                        }
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    self.cursor.line += 1;
                    self.cursor.index = 0;
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Left => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Next);
                    } else {
                        self.action(Action::Previous);
                    }
                }
            },
            Action::Right => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Previous);
                    } else {
                        self.action(Action::Next);
                    }
                }
            },
            Action::Up => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout > 0 {
                    cursor.layout -= 1;
                } else if cursor.line > 0 {
                    cursor.line -= 1;
                    cursor.layout = usize::max_value();
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Down => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                let layout_len = self.buffer.line_layout(cursor.line).expect("layout not found").len();

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout + 1 < layout_len {
                    cursor.layout += 1;
                } else if cursor.line + 1 < self.buffer.lines.len() {
                    cursor.line += 1;
                    cursor.layout = 0;
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Home => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = 0;
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            },
            Action::End => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = usize::max_value();
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            }
            Action::PageUp => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll -= self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::PageDown => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll += self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::Escape => {
                if self.select_opt.take().is_some() {
                    self.buffer.set_redraw(true);
                }
            },
            Action::Insert(character) => {
                if character.is_control()
                && !['\t', '\u{92}'].contains(&character)
                {
                    // Filter out special chars (except for tab), use Action instead
                    log::debug!("Refusing to insert control character {:?}", character);
                } else {
                    self.delete_selection();

                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Collect text after insertion as a line
                    let after = line.split_off(self.cursor.index);

                    // Append the inserted text
                    line.append(BufferLine::new(
                        character.to_string(),
                        AttrsList::new(line.attrs_list().defaults() /*TODO: provide attrs?*/)
                    ));

                    // Append the text after insertion
                    line.append(after);

                    self.cursor.index += character.len_utf8();
                }
            },
            Action::Enter => {
                self.delete_selection();

                let new_line = self.buffer.lines[self.cursor.line].split_off(self.cursor.index);

                self.cursor.line += 1;
                self.cursor.index = 0;

                self.buffer.lines.insert(self.cursor.line, new_line);
            },
            Action::Backspace => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index > 0 {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Get text line after cursor
                    let after = line.split_off(self.cursor.index);

                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().char_indices() {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;

                    // Remove character
                    line.split_off(self.cursor.index);

                    // Add text after cursor
                    line.append(after);
                } else if self.cursor.line > 0 {
                    let mut line_index = self.cursor.line;
                    let old_line = self.buffer.lines.remove(line_index);
                    line_index -= 1;

                    let line = &mut self.buffer.lines[line_index];

                    self.cursor.line = line_index;
                    self.cursor.index = line.text().len();

                    line.append(old_line);
                }
            },
            Action::Delete => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index < self.buffer.lines[self.cursor.line].text().len() {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    let range_opt = line
                        .text()
                        .grapheme_indices(true)
                        .take_while(|(i, _)| *i <= self.cursor.index)
                        .last()
                        .map(|(i, c)| {
                            i..(i + c.len())
                        });

                    if let Some(range) = range_opt {
                        self.cursor.index = range.start;

                        // Get text after deleted EGC
                        let after = line.split_off(range.end);

                        // Delete EGC
                        line.split_off(range.start);

                        // Add text after deleted EGC
                        line.append(after);
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    let old_line = self.buffer.lines.remove(self.cursor.line + 1);
                    self.buffer.lines[self.cursor.line].append(old_line);
                }
            },
            Action::Click { x, y } => {
                self.select_opt = None;

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Drag { x, y } => {
                if self.select_opt.is_none() {
                    self.select_opt = Some(self.cursor);
                    self.buffer.set_redraw(true);
                }

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Scroll { lines } => {
                let mut scroll = self.buffer.scroll();
                scroll += lines;
                self.buffer.set_scroll(scroll);
            }
        }

        if old_cursor != self.cursor {
            self.cursor_moved = true;

            /*TODO
            if let Some(glyph) = run.glyphs.get(new_cursor_glyph) {
                let font_opt = self.buffer.font_system().get_font(glyph.cache_key.font_id);
                let text_glyph = &run.text[glyph.start..glyph.end];
                log::debug!(
                    "{}, {}: '{}' ('{}'): '{}' ({:?})",
                    self.cursor.line,
                    self.cursor.index,
                    font_opt.as_ref().map_or("?", |font| font.info.family.as_str()),
                    font_opt.as_ref().map_or("?", |font| font.info.post_script_name.as_str()),
                    text_glyph,
                    text_glyph
                );
            }
            */
        }
    }

Get the visible layout runs for rendering and other tasks

Examples found in repository?
src/buffer.rs (line 444)
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
    pub fn hit(&self, x: i32, y: i32) -> Option<Cursor> {
        #[cfg(feature = "std")]
        let instant = std::time::Instant::now();

        let font_size = self.metrics.font_size;
        let line_height = self.metrics.line_height;

        let mut new_cursor_opt = None;

        let mut runs = self.layout_runs().peekable();
        let mut first_run = true;
        while let Some(run) = runs.next() {
            let line_y = run.line_y;

            if first_run && y < line_y - font_size {
                first_run = false;
                let new_cursor = Cursor::new(run.line_i, 0);
                new_cursor_opt = Some(new_cursor);
            } else if y >= line_y - font_size
                    && y < line_y - font_size + line_height
            {
                let mut new_cursor_glyph = run.glyphs.len();
                let mut new_cursor_char = 0;

                let mut first_glyph = true;

                'hit: for (glyph_i, glyph) in run.glyphs.iter().enumerate() {
                    if first_glyph {
                        first_glyph = false;
                        if (run.rtl && x > glyph.x as i32) || (!run.rtl && x < 0) {
                            new_cursor_glyph = 0;
                            new_cursor_char = 0;
                        }
                    }
                    if x >= glyph.x as i32
                    && x <= (glyph.x + glyph.w) as i32
                    {
                        new_cursor_glyph = glyph_i;

                        let cluster = &run.text[glyph.start..glyph.end];
                        let total = cluster.grapheme_indices(true).count();
                        let mut egc_x = glyph.x;
                        let egc_w = glyph.w / (total as f32);
                        for (egc_i, egc) in cluster.grapheme_indices(true) {
                            if x >= egc_x as i32
                            && x <= (egc_x + egc_w) as i32
                            {
                                new_cursor_char = egc_i;

                                let right_half = x >= (egc_x + egc_w / 2.0) as i32;
                                if right_half != glyph.level.is_rtl() {
                                    // If clicking on last half of glyph, move cursor past glyph
                                    new_cursor_char += egc.len();
                                }
                                break 'hit;
                            }
                            egc_x += egc_w;
                        }

                        let right_half = x >= (glyph.x + glyph.w / 2.0) as i32;
                        if right_half != glyph.level.is_rtl() {
                            // If clicking on last half of glyph, move cursor past glyph
                            new_cursor_char = cluster.len();
                        }
                        break 'hit;
                    }
                }

                let mut new_cursor = Cursor::new(run.line_i, 0);

                match run.glyphs.get(new_cursor_glyph) {
                    Some(glyph) => {
                        // Position at glyph
                        new_cursor.index = glyph.start + new_cursor_char;
                    },
                    None => if let Some(glyph) = run.glyphs.last() {
                        // Position at end of line
                        new_cursor.index = glyph.end;
                    },
                }

                new_cursor_opt = Some(new_cursor);

                break;
            } else if runs.peek().is_none() && y > run.line_y {
                let mut new_cursor = Cursor::new(run.line_i, 0);
                if let Some(glyph) = run.glyphs.last() {
                    new_cursor.index = glyph.end;
                }
                new_cursor_opt = Some(new_cursor);
            }
        }

        #[cfg(feature = "std")]
        log::trace!("click({}, {}): {:?}", x, y, instant.elapsed());

        new_cursor_opt
    }

    /// Draw the buffer
    #[cfg(feature = "swash")]
    pub fn draw<F>(&self, cache: &mut crate::SwashCache, color: Color, mut f: F)
        where F: FnMut(i32, i32, u32, u32, Color)
    {
        for run in self.layout_runs() {
            for glyph in run.glyphs.iter() {
                let (cache_key, x_int, y_int) = (glyph.cache_key, glyph.x_int, glyph.y_int);

                let glyph_color = match glyph.color_opt {
                    Some(some) => some,
                    None => color,
                };

                cache.with_pixels(cache_key, glyph_color, |x, y, color| {
                    f(x_int + x, run.line_y + y_int + y, 1, 1, color);
                });
            }
        }
    }
More examples
Hide additional examples
src/edit/editor.rs (line 511)
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
    fn draw<F>(&self, cache: &mut crate::SwashCache, color: Color, mut f: F)
        where F: FnMut(i32, i32, u32, u32, Color)
    {
        let font_size = self.buffer.metrics().font_size;
        let line_height = self.buffer.metrics().line_height;

        for run in self.buffer.layout_runs() {
            let line_i = run.line_i;
            let line_y = run.line_y;

            let cursor_glyph_opt = |cursor: &Cursor| -> Option<(usize, f32)> {
                if cursor.line == line_i {
                    for (glyph_i, glyph) in run.glyphs.iter().enumerate() {
                        if cursor.index == glyph.start {
                            return Some((glyph_i, 0.0));
                        } else if cursor.index > glyph.start && cursor.index < glyph.end {
                            // Guess x offset based on characters
                            let mut before = 0;
                            let mut total = 0;

                            let cluster = &run.text[glyph.start..glyph.end];
                            for (i, _) in cluster.grapheme_indices(true) {
                                if glyph.start + i < cursor.index {
                                    before += 1;
                                }
                                total += 1;
                            }

                            let offset = glyph.w * (before as f32) / (total as f32);
                            return Some((glyph_i, offset));
                        }
                    }
                    match run.glyphs.last() {
                        Some(glyph) => {
                            if cursor.index == glyph.end {
                                return Some((run.glyphs.len(), 0.0));
                            }
                        },
                        None => {
                            return Some((0, 0.0));
                        }
                    }
                }
                None
            };

            // Highlight selection (TODO: HIGHLIGHT COLOR!)
            if let Some(select) = self.select_opt {
                let (start, end) = match select.line.cmp(&self.cursor.line) {
                    cmp::Ordering::Greater => (self.cursor, select),
                    cmp::Ordering::Less => (select, self.cursor),
                    cmp::Ordering::Equal => {
                        /* select.line == self.cursor.line */
                        if select.index < self.cursor.index {
                            (select, self.cursor)
                        } else {
                            /* select.index >= self.cursor.index */
                            (self.cursor, select)
                        }
                    }
                };

                if line_i >= start.line && line_i <= end.line {
                    let mut range_opt = None;
                    for glyph in run.glyphs.iter() {
                        // Guess x offset based on characters
                        let cluster = &run.text[glyph.start..glyph.end];
                        let total = cluster.grapheme_indices(true).count();
                        let mut c_x = glyph.x;
                        let c_w = glyph.w / total as f32;
                        for (i, c) in cluster.grapheme_indices(true) {
                            let c_start = glyph.start + i;
                            let c_end = glyph.start + i + c.len();
                            if (start.line != line_i || c_end > start.index)
                            && (end.line != line_i || c_start < end.index) {
                                range_opt = match range_opt.take() {
                                    Some((min, max)) => Some((
                                        cmp::min(min, c_x as i32),
                                        cmp::max(max, (c_x + c_w) as i32),
                                    )),
                                    None => Some((
                                        c_x as i32,
                                        (c_x + c_w) as i32,
                                    ))
                                };
                            } else if let Some((min, max)) = range_opt.take() {
                                f(
                                    min,
                                    line_y - font_size,
                                    cmp::max(0, max - min) as u32,
                                    line_height as u32,
                                    Color::rgba(color.r(), color.g(), color.b(), 0x33)
                                );
                            }
                            c_x += c_w;
                        }
                    }

                    if run.glyphs.is_empty() && end.line > line_i{
                        // Highlight all of internal empty lines
                        range_opt = Some((0, self.buffer.size().0));
                    }

                    if let Some((mut min, mut max)) = range_opt.take() {
                        if end.line > line_i {
                            // Draw to end of line
                            if run.rtl {
                                min = 0;
                            } else {
                                max = self.buffer.size().0;
                            }
                        }
                        f(
                            min,
                            line_y - font_size,
                            cmp::max(0, max - min) as u32,
                            line_height as u32,
                            Color::rgba(color.r(), color.g(), color.b(), 0x33)
                        );
                    }
                }
            }

            // Draw cursor
            if let Some((cursor_glyph, cursor_glyph_offset)) = cursor_glyph_opt(&self.cursor) {
                let x = match run.glyphs.get(cursor_glyph) {
                    Some(glyph) => {
                        // Start of detected glyph
                        if glyph.level.is_rtl() {
                            (glyph.x + glyph.w - cursor_glyph_offset) as i32
                        } else {
                            (glyph.x + cursor_glyph_offset) as i32
                        }
                    },
                    None => match run.glyphs.last() {
                        Some(glyph) => {
                            // End of last glyph
                            if glyph.level.is_rtl() {
                                glyph.x as i32
                            } else {
                                (glyph.x + glyph.w) as i32
                            }
                        },
                        None => {
                            // Start of empty line
                            0
                        }
                    }
                };

                f(
                    x,
                    line_y - font_size,
                    1,
                    line_height as u32,
                    color,
                );
            }

            for glyph in run.glyphs.iter() {
                let (cache_key, x_int, y_int) = (glyph.cache_key, glyph.x_int, glyph.y_int);

                let glyph_color = match glyph.color_opt {
                    Some(some) => some,
                    None => color,
                };

                cache.with_pixels(cache_key, glyph_color, |x, y, color| {
                    f(x_int + x, line_y + y_int + y, 1, 1, color);
                });
            }
        }
    }

Convert x, y position to Cursor (hit detection)

Examples found in repository?
src/edit/editor.rs (line 455)
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
    fn action(&mut self, action: Action) {
        let old_cursor = self.cursor;

        match action {
            Action::Previous => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index > 0 {
                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().grapheme_indices(true) {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;
                    self.buffer.set_redraw(true);
                } else if self.cursor.line > 0 {
                    self.cursor.line -= 1;
                    self.cursor.index = self.buffer.lines[self.cursor.line].text().len();
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Next => {
                let line = &mut self.buffer.lines[self.cursor.line];
                if self.cursor.index < line.text().len() {
                    for (i, c) in line.text().grapheme_indices(true) {
                        if i == self.cursor.index {
                            self.cursor.index += c.len();
                            self.buffer.set_redraw(true);
                            break;
                        }
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    self.cursor.line += 1;
                    self.cursor.index = 0;
                    self.buffer.set_redraw(true);
                }
                self.cursor_x_opt = None;
            },
            Action::Left => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Next);
                    } else {
                        self.action(Action::Previous);
                    }
                }
            },
            Action::Right => {
                let rtl_opt = self.buffer.lines[self.cursor.line].shape_opt().as_ref().map(|shape| shape.rtl);
                if let Some(rtl) = rtl_opt {
                    if rtl {
                        self.action(Action::Previous);
                    } else {
                        self.action(Action::Next);
                    }
                }
            },
            Action::Up => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout > 0 {
                    cursor.layout -= 1;
                } else if cursor.line > 0 {
                    cursor.line -= 1;
                    cursor.layout = usize::max_value();
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Down => {
                //TODO: make this preserve X as best as possible!
                let mut cursor = self.buffer.layout_cursor(&self.cursor);

                let layout_len = self.buffer.line_layout(cursor.line).expect("layout not found").len();

                if self.cursor_x_opt.is_none() {
                    self.cursor_x_opt = Some(
                        cursor.glyph as i32 //TODO: glyph x position
                    );
                }

                if cursor.layout + 1 < layout_len {
                    cursor.layout += 1;
                } else if cursor.line + 1 < self.buffer.lines.len() {
                    cursor.line += 1;
                    cursor.layout = 0;
                }

                if let Some(cursor_x) = self.cursor_x_opt {
                    cursor.glyph = cursor_x as usize; //TODO: glyph x position
                }

                self.set_layout_cursor(cursor);
            },
            Action::Home => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = 0;
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            },
            Action::End => {
                let mut cursor = self.buffer.layout_cursor(&self.cursor);
                cursor.glyph = usize::max_value();
                self.set_layout_cursor(cursor);
                self.cursor_x_opt = None;
            }
            Action::PageUp => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll -= self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::PageDown => {
                //TODO: move cursor
                let mut scroll = self.buffer.scroll();
                scroll += self.buffer.visible_lines();
                self.buffer.set_scroll(scroll);
            },
            Action::Escape => {
                if self.select_opt.take().is_some() {
                    self.buffer.set_redraw(true);
                }
            },
            Action::Insert(character) => {
                if character.is_control()
                && !['\t', '\u{92}'].contains(&character)
                {
                    // Filter out special chars (except for tab), use Action instead
                    log::debug!("Refusing to insert control character {:?}", character);
                } else {
                    self.delete_selection();

                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Collect text after insertion as a line
                    let after = line.split_off(self.cursor.index);

                    // Append the inserted text
                    line.append(BufferLine::new(
                        character.to_string(),
                        AttrsList::new(line.attrs_list().defaults() /*TODO: provide attrs?*/)
                    ));

                    // Append the text after insertion
                    line.append(after);

                    self.cursor.index += character.len_utf8();
                }
            },
            Action::Enter => {
                self.delete_selection();

                let new_line = self.buffer.lines[self.cursor.line].split_off(self.cursor.index);

                self.cursor.line += 1;
                self.cursor.index = 0;

                self.buffer.lines.insert(self.cursor.line, new_line);
            },
            Action::Backspace => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index > 0 {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    // Get text line after cursor
                    let after = line.split_off(self.cursor.index);

                    // Find previous character index
                    let mut prev_index = 0;
                    for (i, _) in line.text().char_indices() {
                        if i < self.cursor.index {
                            prev_index = i;
                        } else {
                            break;
                        }
                    }

                    self.cursor.index = prev_index;

                    // Remove character
                    line.split_off(self.cursor.index);

                    // Add text after cursor
                    line.append(after);
                } else if self.cursor.line > 0 {
                    let mut line_index = self.cursor.line;
                    let old_line = self.buffer.lines.remove(line_index);
                    line_index -= 1;

                    let line = &mut self.buffer.lines[line_index];

                    self.cursor.line = line_index;
                    self.cursor.index = line.text().len();

                    line.append(old_line);
                }
            },
            Action::Delete => {
                if self.delete_selection() {
                    // Deleted selection
                } else if self.cursor.index < self.buffer.lines[self.cursor.line].text().len() {
                    let line = &mut self.buffer.lines[self.cursor.line];

                    let range_opt = line
                        .text()
                        .grapheme_indices(true)
                        .take_while(|(i, _)| *i <= self.cursor.index)
                        .last()
                        .map(|(i, c)| {
                            i..(i + c.len())
                        });

                    if let Some(range) = range_opt {
                        self.cursor.index = range.start;

                        // Get text after deleted EGC
                        let after = line.split_off(range.end);

                        // Delete EGC
                        line.split_off(range.start);

                        // Add text after deleted EGC
                        line.append(after);
                    }
                } else if self.cursor.line + 1 < self.buffer.lines.len() {
                    let old_line = self.buffer.lines.remove(self.cursor.line + 1);
                    self.buffer.lines[self.cursor.line].append(old_line);
                }
            },
            Action::Click { x, y } => {
                self.select_opt = None;

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Drag { x, y } => {
                if self.select_opt.is_none() {
                    self.select_opt = Some(self.cursor);
                    self.buffer.set_redraw(true);
                }

                if let Some(new_cursor) = self.buffer.hit(x, y) {
                    if new_cursor != self.cursor {
                        self.cursor = new_cursor;
                        self.buffer.set_redraw(true);
                    }
                }
            },
            Action::Scroll { lines } => {
                let mut scroll = self.buffer.scroll();
                scroll += lines;
                self.buffer.set_scroll(scroll);
            }
        }

        if old_cursor != self.cursor {
            self.cursor_moved = true;

            /*TODO
            if let Some(glyph) = run.glyphs.get(new_cursor_glyph) {
                let font_opt = self.buffer.font_system().get_font(glyph.cache_key.font_id);
                let text_glyph = &run.text[glyph.start..glyph.end];
                log::debug!(
                    "{}, {}: '{}' ('{}'): '{}' ({:?})",
                    self.cursor.line,
                    self.cursor.index,
                    font_opt.as_ref().map_or("?", |font| font.info.family.as_str()),
                    font_opt.as_ref().map_or("?", |font| font.info.post_script_name.as_str()),
                    text_glyph,
                    text_glyph
                );
            }
            */
        }
    }

Draw the buffer

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.