aboutsummaryrefslogtreecommitdiff
path: root/src/selection.rs
blob: 375072c9d87ba2ca181386eac2e80e06b0899d81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! Provides a [`Selection`] type for working with text selections in [`Paragraph`].
//!
//! [`Paragraph`]: https://docs.iced.rs/iced_graphics/text/paragraph/struct.Paragraph.html

use std::cmp::Ordering;

use iced_widget::{graphics::text::Paragraph, text_input::Value};

/// The direction of a selection.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
#[allow(missing_docs)]
pub enum Direction {
    Left,
    #[default]
    Right,
}

/// A text selection.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub struct Selection {
    /// The start of the selection.
    pub start: SelectionEnd,
    /// The end of the selection.
    pub end: SelectionEnd,
    /// The last direction of the selection.
    pub direction: Direction,
    moving_line_index: Option<usize>,
}

/// One of the ends of a [`Selection`].
///
/// Note that the index refers to [`graphemes`], not glyphs or bytes.
///
/// [`graphemes`]: https://docs.rs/unicode-segmentation/latest/unicode_segmentation/trait.UnicodeSegmentation.html#tymethod.graphemes
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[allow(missing_docs)]
pub struct SelectionEnd {
    pub line: usize,
    pub index: usize,
}

impl SelectionEnd {
    /// Creates a new [`SelectionEnd`].
    pub fn new(line: usize, index: usize) -> Self {
        Self { line, index }
    }
}

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

impl Ord for SelectionEnd {
    fn cmp(&self, other: &Self) -> Ordering {
        self.line
            .cmp(&other.line)
            .then(self.index.cmp(&other.index))
    }
}

impl Selection {
    /// Creates a new empty [`Selection`].
    pub fn new() -> Self {
        Self::default()
    }

    /// A selection is empty when the start and end are the same.
    pub fn is_empty(&self) -> bool {
        self.start == self.end
    }

    /// Returns the selected text from the given [`Paragraph`].
    ///
    /// [`Paragraph`]: https://docs.iced.rs/iced_graphics/text/paragraph/struct.Paragraph.html
    pub fn text(&self, paragraph: &Paragraph) -> String {
        let Selection { start, end, .. } = *self;

        let mut value = String::new();
        let buffer_lines = &paragraph.buffer().lines;
        let lines_total = end.line - start.line + 1;

        for (idx, line) in buffer_lines
            .iter()
            .skip(start.line)
            .enumerate()
            .take(lines_total)
        {
            let text = Value::new(line.text());
            let length = text.len();

            if idx == 0 {
                if lines_total == 1 {
                    value.push_str(
                        &text
                            .select(
                                start.index.min(length),
                                end.index.min(length),
                            )
                            .to_string(),
                    );
                } else {
                    value.push_str(
                        &text
                            .select(start.index.min(length), length)
                            .to_string(),
                    );
                    value.push_str(line.ending().as_str());
                }
            } else if idx == lines_total - 1 {
                value.push_str(&text.until(end.index.min(length)).to_string());
            } else {
                value.push_str(&text.to_string());
                value.push_str(line.ending().as_str());
            }
        }

        value
    }

    /// Returns the currently active [`SelectionEnd`].
    ///
    /// `self.end` if `self.direction` is [`Right`], `self.start` otherwise.
    ///
    /// [`Right`]: Direction::Right
    pub fn active_end(&self) -> SelectionEnd {
        if self.direction == Direction::Right {
            self.end
        } else {
            self.start
        }
    }

    /// Select a new range.
    ///
    /// `self.start` will be set to the smaller value, `self.end` to the larger.
    ///
    /// # Example
    ///
    /// ```
    /// use iced_selection::selection::{Selection, SelectionEnd};
    ///
    /// let mut selection = Selection::default();
    ///
    /// let start = SelectionEnd::new(5, 17);
    /// let end = SelectionEnd::new(2, 8);
    ///
    /// selection.select_range(start, end);
    ///
    /// assert_eq!(selection.start, end);
    /// assert_eq!(selection.end, start);
    /// ```
    pub fn select_range(&mut self, start: SelectionEnd, end: SelectionEnd) {
        self.start = start.min(end);
        self.end = end.max(start);
    }

    /// Updates the current selection by setting a new end point.
    ///
    /// This method adjusts the selection range based on the provided `new_end` position. The
    /// current [`Direction`] is used to determine the new values:
    ///
    /// - If the current direction is [`Right`] (i.e., the selection goes from `start` to `end`), the
    ///   range becomes `(start, new_end)`. If `new_end` is before `start`, the direction is flipped to [`Left`].
    ///
    /// - If it's [`Left`], the range becomes `(new_end, end)`. If `new_end` is after `end`, the
    ///   direction is flipped to [`Right`].
    ///
    /// # Example
    ///
    /// ```
    /// use iced_selection::selection::{Direction, Selection, SelectionEnd};
    ///
    /// let mut selection = Selection::default();
    ///
    /// let start = SelectionEnd::new(5, 17);
    /// let end = SelectionEnd::new(2, 8);
    ///
    /// selection.select_range(start, end);
    ///
    /// assert_eq!(selection.start, end);
    /// assert_eq!(selection.end, start);
    /// assert_eq!(selection.direction, Direction::Right);
    ///
    /// let new_end = SelectionEnd::new(2, 2);
    ///
    /// selection.change_selection(new_end);
    ///
    /// assert_eq!(selection.start, new_end);
    /// assert_eq!(selection.end, end);
    /// assert_eq!(selection.direction, Direction::Left);
    /// ```
    ///
    /// [`Left`]: Direction::Left
    /// [`Right`]: Direction::Right
    pub fn change_selection(&mut self, new_end: SelectionEnd) {
        let (start, end) = if self.direction == Direction::Right {
            if new_end < self.start {
                self.direction = Direction::Left;
            }

            (self.start, new_end)
        } else {
            if new_end > self.end {
                self.direction = Direction::Right;
            }

            (new_end, self.end)
        };

        self.moving_line_index = None;
        self.select_range(start, end);
    }

    /// Updates the current selection by setting a new end point, either to the start of the
    /// previous word, or to the next one's end.
    pub fn change_selection_by_word(
        &mut self,
        new_end: SelectionEnd,
        paragraph: &Paragraph,
    ) {
        let (base_word_start, base_word_end) = {
            if self.direction == Direction::Right {
                let value = Value::new(
                    paragraph.buffer().lines[self.start.line].text(),
                );

                let end = SelectionEnd::new(
                    self.start.line,
                    value.next_end_of_word(self.start.index),
                );

                (self.start, end)
            } else {
                let value =
                    Value::new(paragraph.buffer().lines[self.end.line].text());

                let start = SelectionEnd::new(
                    self.end.line,
                    value.previous_start_of_word(self.end.index),
                );

                (start, self.end)
            }
        };

        let value = Value::new(paragraph.buffer().lines[new_end.line].text());

        let (start, end) = if new_end < self.start {
            self.direction = Direction::Left;

            let start = SelectionEnd::new(
                new_end.line,
                value.previous_start_of_word(new_end.index),
            );

            (start, base_word_end)
        } else if new_end > self.end {
            self.direction = Direction::Right;

            let end = SelectionEnd::new(
                new_end.line,
                value.next_end_of_word(new_end.index),
            );

            (base_word_start, end)
        } else if self.direction == Direction::Right {
            let end = SelectionEnd::new(
                new_end.line,
                value.next_end_of_word(new_end.index),
            );

            (base_word_start, end.max(base_word_end))
        } else {
            let start = SelectionEnd::new(
                new_end.line,
                value.previous_start_of_word(new_end.index),
            );

            (start.min(base_word_start), base_word_end)
        };

        self.moving_line_index = None;
        self.select_range(start, end);
    }

    /// Updates the current selection by setting a new end point, either to the end of a following
    /// line, or the beginning of a previous one.
    pub fn change_selection_by_line(
        &mut self,
        new_line: usize,
        paragraph: &Paragraph,
    ) {
        if self.active_end().line == new_line {
            return;
        }

        let old_direction = self.direction;

        if new_line < self.start.line {
            self.direction = Direction::Left;
        } else if new_line > self.end.line {
            self.direction = Direction::Right;
        }

        let (start, end) = if self.direction == Direction::Right {
            let value = Value::new(paragraph.buffer().lines[new_line].text());

            let start = if self.direction == old_direction {
                self.start
            } else {
                SelectionEnd::new(self.end.line, 0)
            };

            let end = SelectionEnd::new(new_line, value.len());

            (start, end)
        } else {
            let start = SelectionEnd::new(new_line, 0);

            let end = if self.direction == old_direction {
                self.end
            } else {
                let value = Value::new(
                    paragraph.buffer().lines[self.start.line].text(),
                );

                SelectionEnd::new(self.start.line, value.len())
            };

            (start, end)
        };

        self.moving_line_index = None;
        self.select_range(start, end);
    }

    /// Selects the word around the given grapheme position.
    pub fn select_word(
        &mut self,
        line: usize,
        index: usize,
        paragraph: &Paragraph,
    ) {
        let value = Value::new(paragraph.buffer().lines[line].text());

        let start =
            SelectionEnd::new(line, value.previous_start_of_word(index));
        let end = SelectionEnd::new(line, value.next_end_of_word(index));

        self.select_range(start, end);
    }

    /// Moves the active [`SelectionEnd`] to the left by one, wrapping to the previous line if
    /// possible and required.
    pub fn select_left(&mut self, paragraph: &Paragraph) {
        let mut active_end = self.active_end();

        if active_end.index > 0 {
            active_end.index -= 1;

            self.change_selection(active_end);
        } else if active_end.line > 0 {
            active_end.line -= 1;

            let value =
                Value::new(paragraph.buffer().lines[active_end.line].text());
            active_end.index = value.len();

            self.change_selection(active_end);
        }
    }

    /// Moves the active [`SelectionEnd`] to the right by one, wrapping to the next line if
    /// possible and required.
    pub fn select_right(&mut self, paragraph: &Paragraph) {
        let mut active_end = self.active_end();

        let lines = &paragraph.buffer().lines;
        let value = Value::new(lines[active_end.line].text());

        if active_end.index < value.len() {
            active_end.index += 1;

            self.change_selection(active_end);
        } else if active_end.line < lines.len() - 1 {
            active_end.line += 1;
            active_end.index = 0;

            self.change_selection(active_end);
        }
    }

    /// Moves the active [`SelectionEnd`] up by one, keeping track of the original grapheme index.
    pub fn select_up(&mut self, paragraph: &Paragraph) {
        let mut active_end = self.active_end();

        if active_end.line == 0 {
            active_end.index = 0;

            self.change_selection(active_end);
        } else {
            active_end.line -= 1;

            let mut moving_line_index = None;

            if let Some(index) = self.moving_line_index.take() {
                active_end.index = index;
            }

            let value =
                Value::new(paragraph.buffer().lines[active_end.line].text());
            if active_end.index > value.len() {
                moving_line_index = Some(active_end.index);
                active_end.index = value.len();
            }

            self.change_selection(active_end);
            self.moving_line_index = moving_line_index;
        }
    }

    /// Moves the active [`SelectionEnd`] down by one, keeping track of the original grapheme index.
    pub fn select_down(&mut self, paragraph: &Paragraph) {
        let mut active_end = self.active_end();

        let lines = &paragraph.buffer().lines;
        let value = Value::new(lines[active_end.line].text());

        if active_end.line == lines.len() - 1 {
            active_end.index = value.len();

            self.change_selection(active_end);
        } else {
            active_end.line += 1;

            let mut moving_line_index = None;

            if let Some(index) = self.moving_line_index.take() {
                active_end.index = index;
            }

            let value =
                Value::new(paragraph.buffer().lines[active_end.line].text());
            if active_end.index > value.len() {
                moving_line_index = Some(active_end.index);
                active_end.index = value.len();
            }

            self.change_selection(active_end);
            self.moving_line_index = moving_line_index;
        }
    }

    /// Moves the active [`SelectionEnd`] to the previous start of a word on its current line, or
    /// the previous line if it exists and `index == 0`.
    pub fn select_left_by_words(&mut self, paragraph: &Paragraph) {
        let mut active_end = self.active_end();

        if active_end.index == 1 {
            active_end.index = 0;

            self.change_selection(active_end);
        } else if active_end.index > 1 {
            let value =
                Value::new(paragraph.buffer().lines[active_end.line].text());
            active_end.index = value.previous_start_of_word(active_end.index);

            self.change_selection(active_end);
        } else if active_end.line > 0 {
            active_end.line -= 1;

            let value =
                Value::new(paragraph.buffer().lines[active_end.line].text());
            active_end.index = value.previous_start_of_word(value.len());

            self.change_selection(active_end);
        }
    }

    /// Moves the active [`SelectionEnd`] to the next end of a word on its current line, or
    /// the next line if it exists and `index == line.len()`.
    pub fn select_right_by_words(&mut self, paragraph: &Paragraph) {
        let mut active_end = self.active_end();

        let lines = &paragraph.buffer().lines;
        let value = Value::new(lines[active_end.line].text());

        if value.len() - active_end.index == 1 {
            active_end.index = value.len();

            self.change_selection(active_end);
        } else if active_end.index < value.len() {
            active_end.index = value.next_end_of_word(active_end.index);

            self.change_selection(active_end);
        } else if active_end.line < lines.len() - 1 {
            active_end.line += 1;

            let value = Value::new(lines[active_end.line].text());
            active_end.index = value.next_end_of_word(0);

            self.change_selection(active_end);
        }
    }

    /// Moves the active [`SelectionEnd`] to the beginning of its current line.
    pub fn select_line_beginning(&mut self) {
        let mut active_end = self.active_end();

        if active_end.index > 0 {
            active_end.index = 0;

            self.change_selection(active_end);
        }
    }

    /// Moves the active [`SelectionEnd`] to the end of its current line.
    pub fn select_line_end(&mut self, paragraph: &Paragraph) {
        let mut active_end = self.active_end();

        let value =
            Value::new(paragraph.buffer().lines[active_end.line].text());

        if active_end.index < value.len() {
            active_end.index = value.len();

            self.change_selection(active_end);
        }
    }

    /// Moves the active [`SelectionEnd`] to the beginning of the [`Paragraph`].
    ///
    /// [`Paragraph`]: https://docs.iced.rs/iced_graphics/text/paragraph/struct.Paragraph.html
    pub fn select_beginning(&mut self) {
        self.change_selection(SelectionEnd::new(0, 0));
    }

    /// Moves the active [`SelectionEnd`] to the end of the [`Paragraph`].
    ///
    /// [`Paragraph`]: https://docs.iced.rs/iced_graphics/text/paragraph/struct.Paragraph.html
    pub fn select_end(&mut self, paragraph: &Paragraph) {
        let lines = &paragraph.buffer().lines;
        let value = Value::new(lines[lines.len() - 1].text());

        let new_end = SelectionEnd::new(lines.len() - 1, value.len());

        self.change_selection(new_end);
    }

    /// Selects an entire line.
    pub fn select_line(&mut self, line: usize, paragraph: &Paragraph) {
        let value = Value::new(paragraph.buffer().lines[line].text());

        let start = SelectionEnd::new(line, 0);
        let end = SelectionEnd::new(line, value.len());

        self.select_range(start, end);
    }

    /// Selects the entire [`Paragraph`].
    ///
    /// [`Paragraph`]: https://docs.iced.rs/iced_graphics/text/paragraph/struct.Paragraph.html
    pub fn select_all(&mut self, paragraph: &Paragraph) {
        let line = paragraph.buffer().lines.len() - 1;
        let index = Value::new(paragraph.buffer().lines[line].text()).len();

        let end = SelectionEnd::new(line, index);

        self.select_range(SelectionEnd::new(0, 0), end);
    }
}