duat_core/widgets/
file.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
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
//! The primary widget of Duat, used to display files.
//!
//! Most extensible features of Duat have the primary purpose of
//! serving the [`File`], such as multiple [`Cursor`]s, a
//! [`History`] system, [`Area::PrintInfo`], etc.
//!
//! The [`File`] also provides a list of printed lines through the
//! [`File::printed_lines`] method. This method is notably used by the
//! [`LineNumbers`] widget, that shows the numbers of the currently
//! printed lines.
//!
//! [`LineNumbers`]: crate::widgets::LineNumbers
//! [`Cursor`]: crate::mode::Cursor
use std::{fs, io::ErrorKind, path::PathBuf};

use crate::{
    cfg::{IterCfg, PrintCfg},
    forms,
    text::Text,
    ui::{Area, PushSpecs, Ui},
    widgets::{Widget, WidgetCfg},
};

/// The configuration for a new [`File`]
#[derive(Default, Clone)]
pub struct FileCfg {
    text_op: TextOp,
    cfg: PrintCfg,
}

impl FileCfg {
    /// Returns a new instance of [`FileCfg`], opening anew buffer
    pub(crate) fn new() -> Self {
        FileCfg {
            text_op: TextOp::NewBuffer,
            cfg: PrintCfg::default_for_input(),
        }
    }

    /// Changes the path of this cfg
    pub(crate) fn open_path(self, path: PathBuf) -> Self {
        Self { text_op: TextOp::OpenPath(path), ..self }
    }

    /// Takes a previous [`File`]
    pub(crate) fn take_from_prev(self, prev: &mut File) -> Self {
        let text = std::mem::take(&mut prev.text);
        Self {
            text_op: TextOp::TakeText(text, prev.path.clone()),
            ..self
        }
    }

    /// Sets the [`PrintCfg`]
    pub(crate) fn set_print_cfg(&mut self, cfg: PrintCfg) {
        self.cfg = cfg;
    }
}

impl<U: Ui> WidgetCfg<U> for FileCfg {
    type Widget = File;

    fn build(self, _: bool) -> (Self::Widget, impl Fn() -> bool, PushSpecs) {
        let (text, path) = match self.text_op {
            TextOp::NewBuffer => (Text::new(), Path::new_unset()),
            TextOp::TakeText(text, path) => (text, path),
            // TODO: Add an option for automatic path creation.
            TextOp::OpenPath(path) => match path.canonicalize() {
                Ok(path) => (Text::from_file(&path), Path::SetExists(path)),
                Err(err) if matches!(err.kind(), ErrorKind::NotFound) => {
                    if path.parent().is_some_and(std::path::Path::exists) {
                        let parent = path.with_file_name("").canonicalize().unwrap();
                        let path = parent.with_file_name(path.file_name().unwrap());
                        (Text::new(), Path::SetAbsent(path))
                    } else {
                        (Text::new(), Path::new_unset())
                    }
                }
                Err(_) => (Text::new(), Path::new_unset()),
            },
        };

        #[cfg(feature = "wack")]
        let text = {
            let mut text = text;
            use crate::{
                forms::{self, Form},
                text::{Key, Tag},
            };

            let key = Key::new();
            let form1 = forms::set("form1lmao", Form::red());
            let form2 = forms::set("form2lmao", Form::new().undercurled().underline_blue());
            for i in (10..text.len_bytes()).step_by(10) {
                text.insert_tag(i - 8, Tag::PushForm(form1), key);
                text.insert_tag(i - 5, Tag::PopForm(form1), key);
                text.insert_tag(i - 6, Tag::PushForm(form2), key);
                text.insert_tag(i - 2, Tag::PopForm(form2), key);
            }

            text
        };

        let file = File {
            path,
            text,
            cfg: self.cfg,
            printed_lines: Vec::new(),
        };

        // The PushSpecs don't matter
        (file, Box::new(|| false), PushSpecs::above())
    }
}

/// The widget that is used to print and edit files
pub struct File {
    path: Path,
    text: Text,
    cfg: PrintCfg,
    printed_lines: Vec<(u32, bool)>,
}

impl File {
    ////////// Writing the File

    /// Writes the file to the current [`Path`], if one was set
    ///
    /// [`Path`]: std::path::Path
    pub fn write(&self) -> Result<usize, String> {
        if let Path::SetExists(path) = &self.path {
            self.text
                .write_to(std::io::BufWriter::new(
                    fs::File::create(path).map_err(|err| err.to_string())?,
                ))
                .map_err(|err| err.to_string())
        } else {
            Err(String::from(
                "The file has no associated path, and no path was given to write to",
            ))
        }
    }

    /// Writes the file to the given [`Path`]
    ///
    /// [`Path`]: std::path::Path
    pub fn write_to(&self, path: impl AsRef<str>) -> std::io::Result<usize> {
        self.text
            .write_to(std::io::BufWriter::new(fs::File::create(path.as_ref())?))
    }

    ////////// Path querying functions

    /// The full path of the file.
    ///
    /// If there is no set path, returns `"*scratch file*#{id}"`.
    pub fn path(&self) -> String {
        match &self.path {
            Path::SetExists(path) | Path::SetAbsent(path) => path.to_string_lossy().to_string(),
            Path::UnSet(id) => {
                let path = std::env::current_dir()
                    .unwrap()
                    .to_string_lossy()
                    .to_string();

                format!("{path}/*scratch file*#{id}")
            }
        }
    }

    /// The full path of the file.
    ///
    /// Returns [`None`] if the path has not been set yet.
    pub fn path_set(&self) -> Option<String> {
        match &self.path {
            Path::SetExists(path) | Path::SetAbsent(path) => {
                Some(path.to_string_lossy().to_string())
            }
            Path::UnSet(_) => None,
        }
    }

    /// The file's name.
    ///
    /// If there is no set path, returns `"*scratch file #{id}*"`.
    pub fn name(&self) -> String {
        match &self.path {
            Path::SetExists(path) | Path::SetAbsent(path) => {
                path.file_name().unwrap().to_string_lossy().to_string()
            }
            Path::UnSet(id) => format!("*scratch file #{id}*"),
        }
    }

    /// The file's name.
    ///
    /// Returns [`None`] if the path has not been set yet.
    pub fn name_set(&self) -> Option<String> {
        match &self.path {
            Path::SetExists(path) | Path::SetAbsent(path) => {
                Some(path.file_name().unwrap().to_string_lossy().to_string())
            }
            Path::UnSet(_) => None,
        }
    }

    /// Returns the currently printed set of lines.
    ///
    /// These are returned as a `usize`, showing the index of the line
    /// in the file, and a `bool`, which is `true` when the line is
    /// wrapped.
    pub fn printed_lines(&self) -> &[(u32, bool)] {
        &self.printed_lines
    }

    ////////// General querying functions

    /// The number of bytes in the file.
    pub fn len_bytes(&self) -> u32 {
        self.text.len().byte()
    }

    /// The number of [`char`]s in the file.
    pub fn len_chars(&self) -> u32 {
        self.text.len().char()
    }

    /// The number of lines in the file.
    pub fn len_lines(&self) -> u32 {
        self.text.len().line()
    }

    /// The [`Text`] of the [`File`]
    pub fn text(&self) -> &Text {
        &self.text
    }

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

    /// The mutable [`Text`] of the [`File`]
    pub fn print_cfg(&self) -> PrintCfg {
        self.cfg
    }

    /// Wether o not the [`File`] exists or not
    pub fn exists(&self) -> bool {
        self.path_set()
            .is_some_and(|p| std::fs::exists(PathBuf::from(&p)).is_ok_and(|e| e))
    }
}

impl<U: Ui> Widget<U> for File {
    type Cfg = FileCfg;

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

    fn update(&mut self, _area: &U::Area) {}

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

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

    fn print_cfg(&self) -> PrintCfg {
        self.cfg
    }

    fn once() {}

    fn print(&mut self, area: &<U as Ui>::Area) {
        let (start, _) = area.top_left();

        let mut last_line = area
            .rev_print_iter(self.text.iter_rev(start), IterCfg::new(self.cfg))
            .find_map(|(caret, item)| caret.wrap.then_some(item.line()));

        self.printed_lines.clear();
        let printed_lines = &mut self.printed_lines;

        let mut has_wrapped = false;

        area.print_with(
            &self.text,
            self.cfg,
            forms::painter(),
            move |caret, item| {
                has_wrapped |= caret.wrap;
                if has_wrapped && item.part.is_char() {
                    has_wrapped = false;
                    let line = item.line();
                    let wrapped = last_line.is_some_and(|ll| ll == line);
                    last_line = Some(line);
                    printed_lines.push((line, wrapped));
                }
            },
        )
    }
}

/// Represents the presence or absence of a path
#[derive(Clone)]
enum Path {
    SetExists(PathBuf),
    SetAbsent(PathBuf),
    UnSet(usize),
}

impl Path {
    /// Returns a new unset [`Path`]
    fn new_unset() -> Path {
        use std::sync::atomic::{AtomicUsize, Ordering};
        static UNSET_COUNT: AtomicUsize = AtomicUsize::new(1);

        Path::UnSet(UNSET_COUNT.fetch_add(1, Ordering::Relaxed))
    }
}

/// What to do when opening the [`File`]
#[derive(Default, Clone)]
enum TextOp {
    #[default]
    NewBuffer,
    TakeText(Text, Path),
    OpenPath(PathBuf),
}