1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! Logic related to the positioning of the cursor within text.

use crate::geom::{Range, Rect};
use crate::text::{self, FontSize, Point, Scalar};

/// An index representing the position of a cursor within some text.
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Index {
    /// The byte index of the line upon which the cursor is situated.
    pub line: usize,
    /// The index within all possible cursor positions for the line.
    ///
    /// For example, for the line `foo`, a `char` of `1` would indicate the cursor's position
    /// as `f|oo` where `|` is the cursor.
    pub char: usize,
}

/// Every possible cursor position within each line of text yielded by the given iterator.
///
/// Yields `(xs, y_range)`, where `y_range` is the `Range` occupied by the line across the *y*
/// axis and `xs` is every possible cursor position along the *x* axis
#[derive(Clone)]
pub struct XysPerLine<'a, I> {
    lines_with_rects: I,
    font: &'a text::Font,
    text: &'a str,
    font_size: FontSize,
}

/// Similarly to `XysPerLine`, yields every possible cursor position within each line of text
/// yielded by the given iterator.
///
/// Rather than taking an iterator type yielding lines and positioning data, this method
/// constructs its own iterator to do so internally, saving some boilerplate involved in common
/// `XysPerLine` use cases.
///
/// Yields `(xs, y_range)`, where `y_range` is the `Range` occupied by the line across the *y*
/// axis and `xs` is every possible cursor position along the *x* axis.
#[derive(Clone)]
pub struct XysPerLineFromText<'a> {
    xys_per_line: XysPerLine<
        'a,
        std::iter::Zip<
            std::iter::Cloned<std::slice::Iter<'a, text::line::Info>>,
            text::line::Rects<std::iter::Cloned<std::slice::Iter<'a, text::line::Info>>>,
        >,
    >,
}

/// Each possible cursor position along the *x* axis within a line of text.
///
/// `Xs` iterators are produced by the `XysPerLine` iterator.
pub struct Xs<'a, 'b> {
    next_x: Option<Scalar>,
    layout: text::LayoutIter<'a, 'b>,
}

impl Index {
    /// The cursor index of the beginning of the word (block of non-whitespace) before `self`.
    ///
    /// If `self` is at the beginning of the line, call previous, which returns the last
    /// index position of the previous line, or None if it's the first line
    ///
    /// If `self` points to whitespace, skip past that whitespace, then return the index of
    /// the start of the word that precedes the whitespace
    ///
    /// If `self` is in the middle or end of a word, return the index of the start of that word
    pub fn previous_word_start<I>(self, text: &str, mut line_infos: I) -> Option<Self>
    where
        I: Iterator<Item = text::line::Info>,
    {
        let Index { line, char } = self;
        if char > 0 {
            line_infos.nth(line).and_then(|line_info| {
                let line_count = line_info.char_range().count();
                let mut chars_rev = (&text[line_info.byte_range()]).chars().rev();
                if char != line_count {
                    chars_rev.nth(line_count - char - 1);
                }
                let mut new_char = 0;
                let mut hit_non_whitespace = false;
                for (i, char_) in chars_rev.enumerate() {
                    // loop until word starts, then continue until the word ends
                    if !char_.is_whitespace() {
                        hit_non_whitespace = true;
                    }
                    if char_.is_whitespace() && hit_non_whitespace {
                        new_char = char - i;
                        break;
                    }
                }
                Some(Index {
                    line: line,
                    char: new_char,
                })
            })
        } else {
            self.previous(line_infos)
        }
    }

    /// The cursor index of the end of the first word (block of non-whitespace) after `self`.
    ///
    /// If `self` is at the end of the text, this returns `None`.
    ///
    /// If `self` is at the end of a line other than the last, this returns the first index of
    /// the next line.
    ///
    /// If `self` points to whitespace, skip past that whitespace, then return the index of
    /// the end of the word after the whitespace
    ///
    /// If `self` is in the middle or start of a word, return the index of the end of that word
    pub fn next_word_end<I>(self, text: &str, mut line_infos: I) -> Option<Self>
    where
        I: Iterator<Item = text::line::Info>,
    {
        let Index { line, char } = self;
        line_infos.nth(line).and_then(|line_info| {
            let line_count = line_info.char_range().count();
            if char < line_count {
                let mut chars = (&text[line_info.byte_range()]).chars();
                let mut new_char = line_count;
                let mut hit_non_whitespace = false;
                if char != 0 {
                    chars.nth(char - 1);
                }
                for (i, char_) in chars.enumerate() {
                    // loop until word starts, then continue until the word ends
                    if !char_.is_whitespace() {
                        hit_non_whitespace = true;
                    }
                    if char_.is_whitespace() && hit_non_whitespace {
                        new_char = char + i;
                        break;
                    }
                }
                Some(Index {
                    line: line,
                    char: new_char,
                })
            } else {
                line_infos.next().map(|_| Index {
                    line: line + 1,
                    char: 0,
                })
            }
        })
    }

    /// The cursor index that comes before `self`.
    ///
    /// If `self` is at the beginning of the text, this returns `None`.
    ///
    /// If `self` is at the beginning of a line other than the first, this returns the last
    /// index position of the previous line.
    ///
    /// If `self` is a position other than the start of a line, it will return the position
    /// that is immediately to the left.
    pub fn previous<I>(self, mut line_infos: I) -> Option<Self>
    where
        I: Iterator<Item = text::line::Info>,
    {
        let Index { line, char } = self;
        if char > 0 {
            let new_char = char - 1;
            line_infos.nth(line).and_then(|info| {
                if new_char <= info.char_range().count() {
                    Some(Index {
                        line: line,
                        char: new_char,
                    })
                } else {
                    None
                }
            })
        } else if line > 0 {
            let new_line = line - 1;
            line_infos.nth(new_line).map(|info| {
                let new_char = info.end_char() - info.start_char;
                Index {
                    line: new_line,
                    char: new_char,
                }
            })
        } else {
            None
        }
    }

    /// The cursor index that follows `self`.
    ///
    /// If `self` is at the end of the text, this returns `None`.
    ///
    /// If `self` is at the end of a line other than the last, this returns the first index of
    /// the next line.
    ///
    /// If `self` is a position other than the end of a line, it will return the position that
    /// is immediately to the right.
    pub fn next<I>(self, mut line_infos: I) -> Option<Self>
    where
        I: Iterator<Item = text::line::Info>,
    {
        let Index { line, char } = self;
        line_infos.nth(line).and_then(|info| {
            if char >= info.char_range().count() {
                line_infos.next().map(|_| Index {
                    line: line + 1,
                    char: 0,
                })
            } else {
                Some(Index {
                    line: line,
                    char: char + 1,
                })
            }
        })
    }

    /// Clamps `self` to the given lines.
    ///
    /// If `self` would lie after the end of the last line, return the index at the end of the
    /// last line.
    ///
    /// If `line_infos` is empty, returns cursor at line=0 char=0.
    pub fn clamp_to_lines<I>(self, line_infos: I) -> Self
    where
        I: Iterator<Item = text::line::Info>,
    {
        let mut last = None;
        for (i, info) in line_infos.enumerate() {
            if i == self.line {
                let num_chars = info.char_range().len();
                let char = std::cmp::min(self.char, num_chars);
                return Index {
                    line: i,
                    char: char,
                };
            }
            last = Some((i, info));
        }
        match last {
            Some((i, info)) => Index {
                line: i,
                char: info.char_range().len(),
            },
            None => Index { line: 0, char: 0 },
        }
    }
}

/// Every possible cursor position within each line of text yielded by the given iterator.
///
/// Yields `(xs, y_range)`, where `y_range` is the `Range` occupied by the line across the *y*
/// axis and `xs` is every possible cursor position along the *x* axis
pub fn xys_per_line<'a, I>(
    lines_with_rects: I,
    font: &'a text::Font,
    text: &'a str,
    font_size: FontSize,
) -> XysPerLine<'a, I> {
    XysPerLine {
        lines_with_rects: lines_with_rects,
        font: font,
        text: text,
        font_size: font_size,
    }
}

/// Similarly to `xys_per_line`, this produces an iterator yielding every possible cursor
/// position within each line of text yielded by the given iterator.
///
/// Rather than taking an iterator yielding lines and their positioning data, this method
/// constructs its own iterator to do so internally, saving some boilerplate involved in common
/// `xys_per_line` use cases.
///
/// Yields `(xs, y_range)`, where `y_range` is the `Range` occupied by the line across the *y*
/// axis and `xs` is every possible cursor position along the *x* axis.
pub fn xys_per_line_from_text<'a>(
    text: &'a str,
    line_infos: &'a [text::line::Info],
    font: &'a text::Font,
    font_size: FontSize,
    max_width: Scalar,
    x_align: text::Justify,
    line_spacing: Scalar,
) -> XysPerLineFromText<'a> {
    let line_infos = line_infos.iter().cloned();
    let line_rects = text::line::rects(
        line_infos.clone(),
        font_size,
        max_width,
        x_align,
        line_spacing,
    );
    let lines = line_infos.clone();
    let lines_with_rects = lines.zip(line_rects.clone());
    XysPerLineFromText {
        xys_per_line: text::cursor::xys_per_line(lines_with_rects, font, text, font_size),
    }
}

/// Convert the given character index into a cursor `Index`.
pub fn index_before_char<I>(line_infos: I, char_index: usize) -> Option<Index>
where
    I: Iterator<Item = text::line::Info>,
{
    for (i, line_info) in line_infos.enumerate() {
        let start_char = line_info.start_char;
        let end_char = line_info.end_char();
        if start_char <= char_index && char_index <= end_char {
            return Some(Index {
                line: i,
                char: char_index - start_char,
            });
        }
    }
    None
}

/// Determine the *xy* location of the cursor at the given cursor `Index`.
pub fn xy_at<'a, I>(xys_per_line: I, idx: Index) -> Option<(Scalar, Range)>
where
    I: Iterator<Item = (Xs<'a, 'a>, Range)>,
{
    for (i, (xs, y)) in xys_per_line.enumerate() {
        if i == idx.line {
            for (j, x) in xs.enumerate() {
                if j == idx.char {
                    return Some((x, y));
                }
            }
        }
    }
    None
}

/// Find the closest line for the given `y` position, and return the line index, Xs iterator, and y-range of that line
///
/// Returns `None` if there are no lines
pub fn closest_line<'a, I>(y_pos: Scalar, xys_per_line: I) -> Option<(usize, Xs<'a, 'a>, Range)>
where
    I: Iterator<Item = (Xs<'a, 'a>, Range)>,
{
    let mut xys_per_line_enumerated = xys_per_line.enumerate();
    xys_per_line_enumerated
        .next()
        .and_then(|(first_line_idx, (first_line_xs, first_line_y))| {
            let mut closest_line = (first_line_idx, first_line_xs, first_line_y);
            let mut closest_diff = (y_pos - first_line_y.middle()).abs();
            for (line_idx, (line_xs, line_y)) in xys_per_line_enumerated {
                if line_y.contains(y_pos) {
                    closest_line = (line_idx, line_xs, line_y);
                    break;
                } else {
                    let diff = (y_pos - line_y.middle()).abs();
                    if diff < closest_diff {
                        closest_line = (line_idx, line_xs, line_y);
                        closest_diff = diff;
                    } else {
                        break;
                    }
                }
            }
            Some(closest_line)
        })
}

/// Find the closest cursor index to the given `xy` position, and the center `Point` of that
/// cursor.
///
/// Returns `None` if the given `text` is empty.
pub fn closest_cursor_index_and_xy<'a, I>(xy: Point, xys_per_line: I) -> Option<(Index, Point)>
where
    I: Iterator<Item = (Xs<'a, 'a>, Range)>,
{
    closest_line(xy[1], xys_per_line).and_then(
        |(closest_line_idx, closest_line_xs, closest_line_y)| {
            let (closest_char_idx, closest_x) =
                closest_cursor_index_on_line(xy[0], closest_line_xs);
            let index = Index {
                line: closest_line_idx,
                char: closest_char_idx,
            };
            let point = [closest_x, closest_line_y.middle()].into();
            Some((index, point))
        },
    )
}

/// Find the closest cursor index to the given `x` position on the given line along with the
/// `x` position of that cursor.
pub fn closest_cursor_index_on_line<'a>(x_pos: Scalar, line_xs: Xs<'a, 'a>) -> (usize, Scalar) {
    let mut xs_enumerated = line_xs.enumerate();
    // `xs` always yields at least one `x` (the start of the line).
    let (first_idx, first_x) = xs_enumerated.next().unwrap();
    let first_diff = (x_pos - first_x).abs();
    let mut closest = (first_idx, first_x);
    let mut closest_diff = first_diff;
    for (i, x) in xs_enumerated {
        let diff = (x_pos - x).abs();
        if diff < closest_diff {
            closest = (i, x);
            closest_diff = diff;
        } else {
            break;
        }
    }
    closest
}

impl<'a, I> Iterator for XysPerLine<'a, I>
where
    I: Iterator<Item = (text::line::Info, Rect)>,
{
    // The `Range` occupied by the line across the *y* axis, along with an iterator yielding
    // each possible cursor position along the *x* axis.
    type Item = (Xs<'a, 'a>, Range);
    fn next(&mut self) -> Option<Self::Item> {
        let XysPerLine {
            ref mut lines_with_rects,
            font,
            text,
            font_size,
        } = *self;
        let scale = text::pt_to_scale(font_size);
        lines_with_rects.next().map(|(line_info, line_rect)| {
            let line = &text[line_info.byte_range()];
            let (x, y) = (line_rect.left() as f32, line_rect.top() as f32);
            let point = text::rt::Point { x: x, y: y };
            let y = line_rect.y;
            let layout = font.layout(line, scale, point);
            let xs = Xs {
                next_x: Some(line_rect.x.start),
                layout: layout,
            };
            (xs, y)
        })
    }
}

impl<'a> Iterator for XysPerLineFromText<'a> {
    type Item = (Xs<'a, 'a>, Range);
    fn next(&mut self) -> Option<Self::Item> {
        self.xys_per_line.next()
    }
}

impl<'a, 'b> Iterator for Xs<'a, 'b> {
    // Each possible cursor position along the *x* axis.
    type Item = Scalar;
    fn next(&mut self) -> Option<Self::Item> {
        self.next_x.map(|x| {
            self.next_x = self.layout.next().map(|g| {
                g.pixel_bounding_box()
                    .map(|r| r.max.x as Scalar)
                    .unwrap_or_else(|| x + g.unpositioned().h_metrics().advance_width as Scalar)
            });
            x
        })
    }
}