vizia_core/text/selection.rs
1use std::ops::Range;
2
3#[derive(Debug, Clone, Copy)]
4pub struct Selection {
5 pub anchor: usize,
6 pub active: usize,
7 pub h_pos: Option<f32>,
8}
9
10impl Selection {
11 pub fn new(anchor: usize, active: usize) -> Self {
12 Selection { anchor, active, h_pos: None }
13 }
14
15 /// Construct a new selection from this selection, with the provided h_pos.
16 ///
17 /// # Note
18 ///
19 /// `h_pos` is used to track the *pixel* location of the cursor when moving
20 /// vertically; lines may have available cursor positions at different
21 /// positions, and arrowing down and then back up should always result
22 /// in a cursor at the original starting location; doing this correctly
23 /// requires tracking this state.
24 ///
25 /// You *probably* don't need to use this, unless you are implementing a new
26 /// text field, or otherwise implementing vertical cursor motion, in which
27 /// case you will want to set this during vertical motion if it is not
28 /// already set.
29 pub fn with_h_pos(mut self, h_pos: Option<f32>) -> Self {
30 self.h_pos = h_pos;
31 self
32 }
33
34 pub fn caret(caret: usize) -> Self {
35 Selection { anchor: caret, active: caret, h_pos: None }
36 }
37
38 pub fn min(&self) -> usize {
39 usize::min(self.anchor, self.active)
40 }
41
42 pub fn max(&self) -> usize {
43 usize::max(self.anchor, self.active)
44 }
45
46 pub fn range(&self) -> Range<usize> {
47 self.min()..self.max()
48 }
49
50 pub fn is_caret(&self) -> bool {
51 self.min() == self.max()
52 }
53}