duat_core/widgets/
line_numbers.rs

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
//! Line numbers for a [`File`]
//!
//! These are pretty standard like in most text editors. Usually,
//! they'll be printed on the right of the [`File`], but there is an
//! option to print them on the right, if you need such functionality.
//!
//! You can also change other things, like the
//! relativeness/absoluteness of the numbers, as well as the alignment
//! of the numbers, with one more option to change that of the main
//! cursor's line number.
//!
//! [`File`]: super::File
use std::{fmt::Alignment, marker::PhantomData};

use crate::{
    context::{self, FileReader},
    forms::{self, Form},
    text::{Builder, Tag, Text, text},
    ui::{Area, Constraint, PushSpecs, Ui},
    widgets::{Widget, WidgetCfg},
};

pub struct LineNumbers<U: Ui> {
    reader: FileReader<U>,
    text: Text,
    cfg: LineNumbersCfg<U>,
}

impl<U: Ui> LineNumbers<U> {
    /// The minimum width that would be needed to show the last line.
    fn calculate_width(&mut self) -> f32 {
        // "+ 1" because we index from 1, not from 0.
        let len = self.reader.inspect(|file, _, _| file.text().len().line()) + 1;
        len.ilog10() as f32
    }

    fn update_text(&mut self) {
        self.text = self.reader.inspect(|file, _, cursors| {
            let printed_lines = file.printed_lines();
            let main_line = if cursors.is_empty() {
                u32::MAX
            } else {
                cursors.main().line()
            };

            let mut builder = Text::builder();
            text!(builder, { tag_from_align(self.cfg.align) });

            for (index, (line, is_wrapped)) in printed_lines.iter().enumerate() {
                if main_line == *line {
                    text!(builder, { tag_from_align(self.cfg.main_align) });
                }

                match (main_line == *line, is_wrapped) {
                    (false, false) => text!(builder, [LineNum]),
                    (true, false) => text!(builder, [MainLineNum]),
                    (false, true) => text!(builder, [WrappedLineNum]),
                    (true, true) => text!(builder, [WrappedMainLineNum]),
                }

                let is_wrapped = *is_wrapped && index > 0;
                push_text(&mut builder, *line, main_line, is_wrapped, &self.cfg);

                if main_line == *line {
                    text!(builder, { tag_from_align(self.cfg.align) });
                }
            }

            builder.finish()
        });
    }
}

impl<U: Ui> Widget<U> for LineNumbers<U> {
    type Cfg = LineNumbersCfg<U>;

    fn cfg() -> Self::Cfg {
        LineNumbersCfg::new()
    }

    fn update(&mut self, area: &U::Area) {
        let width = self.calculate_width();
        area.constrain_hor(Constraint::Length(width + 1.0)).unwrap();

        self.update_text();
    }

    fn text(&self) -> &Text {
        &self.text
    }

    fn text_mut(&mut self) -> &mut Text {
        &mut self.text
    }

    fn once() {
        forms::set_weak("LineNum", Form::grey());
        forms::set_weak("MainLineNum", Form::yellow());
        forms::set_weak("WrappedLineNum", Form::cyan().italic());
        forms::set_weak("WrappedMainLineNum", "WrappedLineNum");
    }
}

/// How to show the line numbers on screen.
#[derive(Default, Debug, Copy, Clone)]
enum Numbers {
    #[default]
    /// Line numbers relative to the beginning of the file.
    Absolute,
    /// Line numbers relative to the main cursor's line, including
    /// that line.
    Relative,
    /// Relative line numbers on every line, except the main cursor's.
    RelAbs,
}

/// Configuration options for the [`LineNumbers<U>`] widget.
#[derive(Debug, Clone, Copy)]
pub struct LineNumbersCfg<U> {
    numbers: Numbers,
    align: Alignment,
    main_align: Alignment,
    show_wraps: bool,
    specs: PushSpecs,
    ghost: PhantomData<U>,
}

impl<U> Default for LineNumbersCfg<U> {
    fn default() -> Self {
        Self::new()
    }
}

impl<U> LineNumbersCfg<U> {
    pub fn new() -> Self {
        Self {
            numbers: Numbers::Absolute,
            align: Alignment::Left,
            main_align: Alignment::Right,
            show_wraps: false,
            specs: PushSpecs::left(),
            ghost: PhantomData,
        }
    }

    pub fn absolute(self) -> Self {
        Self { numbers: Numbers::Absolute, ..self }
    }

    pub fn relative(self) -> Self {
        Self { numbers: Numbers::Relative, ..self }
    }

    pub fn rel_abs(self) -> Self {
        Self { numbers: Numbers::RelAbs, ..self }
    }

    pub fn align_left(self) -> Self {
        Self {
            main_align: Alignment::Left,
            align: Alignment::Left,
            ..self
        }
    }

    pub fn align_center(self) -> Self {
        Self {
            main_align: Alignment::Center,
            align: Alignment::Center,
            ..self
        }
    }

    pub fn align_right(self) -> Self {
        Self {
            main_align: Alignment::Right,
            align: Alignment::Right,
            ..self
        }
    }

    pub fn align_main_left(self) -> Self {
        Self { main_align: Alignment::Left, ..self }
    }

    pub fn align_main_center(self) -> Self {
        Self { main_align: Alignment::Center, ..self }
    }

    pub fn align_main_right(self) -> Self {
        Self { main_align: Alignment::Right, ..self }
    }

    pub fn show_wraps(self) -> Self {
        Self { show_wraps: true, ..self }
    }

    pub fn hide_wraps(self) -> Self {
        Self { show_wraps: false, ..self }
    }

    pub fn on_the_right(self) -> Self {
        Self { specs: self.specs.to_right(), ..self }
    }
}

impl<U: Ui> WidgetCfg<U> for LineNumbersCfg<U> {
    type Widget = LineNumbers<U>;

    fn build(self, _: bool) -> (Self::Widget, impl Fn() -> bool, PushSpecs) {
        let reader = context::cur_file().unwrap().fixed_reader();
        let specs = self.specs;

        let mut widget = LineNumbers {
            reader: reader.clone(),
            text: Text::default(),
            cfg: self,
        };
        widget.update_text();

        (widget, move || reader.has_changed(), specs)
    }
}

/// Writes the text of the line number to a given [`String`].
fn push_text<U>(
    builder: &mut Builder,
    line: u32,
    main: u32,
    is_wrapped: bool,
    cfg: &LineNumbersCfg<U>,
) {
    if is_wrapped && !cfg.show_wraps {
        text!(*builder, "\n");
    } else if main != u32::MAX {
        let num = match cfg.numbers {
            Numbers::Absolute => line + 1,
            Numbers::Relative => line.abs_diff(main),
            Numbers::RelAbs => {
                if line != main {
                    line.abs_diff(main)
                } else {
                    line + 1
                }
            }
        };

        text!(*builder, num "\n");
    } else {
        text!(*builder, { line + 1 } "\n");
    }
}

fn tag_from_align(alignment: Alignment) -> Tag {
    match alignment {
        Alignment::Left => Tag::StartAlignLeft,
        Alignment::Right => Tag::StartAlignRight,
        Alignment::Center => Tag::StartAlignCenter,
    }
}