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
//! The primary widget of Duat, used to display files.
//!
//! The [`FileWidget`] is Duat's way of display text files. It is
//! an [`ActionableWidget`] with [`Text`] containing a
//! [`ropey::Rope`] and a [`any_rope::Rope`] as its backing, unlike
//! most other widgets, that just use [`String`]s and [`Vec`]s.
//!
//! Most extensible features of Duat have the primary purpose of
//! serving the [`FileWidget`], such as multiple [`Cursor`]s, a
//! [`History`] system, [`PrintInfo`], etc.
//!
//! [`FileWidget`]s can have attached extensions called
//! [`Observer`]s, that can read the [`Text`] within, and are also
//! notified of any [`Change`][crate::history::Change]s made to the
//! file.
//!
//! The [`FileWidget`] also provides a list of printed lines
//! through the [`printed_lines()`][FileWidget::printed_lines()`]
//! method. This method is notably used by the
//! [`LineNumbers`][crate::widgets::LineNumbers] widget, that shows
//! the numbers of the currently printed lines.
use std::{fs, io::ErrorKind, path::PathBuf, sync::Arc};

use self::read::{Reader, RevSearcher, Searcher};
use crate::{
    data::RwData,
    history::History,
    input::{Cursors, InputMethod, KeyMap},
    palette,
    text::{IterCfg, Point, PrintCfg, Text},
    ui::{Area, PushSpecs, Ui},
    widgets::{ActiveWidget, PassiveWidget, Widget, WidgetCfg},
    Context,
};

mod read;

pub struct FileCfg<U>
where
    U: Ui,
{
    text_op: TextOp,
    builder: Arc<dyn Fn(File) -> Widget<U> + Send + Sync + 'static>,
    cfg: PrintCfg,
    specs: PushSpecs,
}

impl<U> FileCfg<U>
where
    U: Ui,
{
    pub(crate) fn new() -> Self {
        FileCfg {
            text_op: TextOp::NewBuffer,
            builder: Arc::new(|file| Widget::active(file, RwData::new(KeyMap::new()))),
            cfg: PrintCfg::default_for_files(),
            // Kinda arbitrary.
            specs: PushSpecs::above(),
        }
    }

    pub(crate) fn build(self) -> (Widget<U>, Box<dyn Fn() -> bool>) {
        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::Set(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::Set(path))
                    } else {
                        (Text::new(), Path::new_unset())
                    }
                }
                Err(_) => (Text::new(), Path::new_unset()),
            },
        };

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

            let marker = Marker::new();
            let form1 = palette::set_form("form1lmao", Form::new().red());
            let form2 = palette::set_form("form2lmao", Form::new().on_blue());
            for i in (0..text.len_bytes()).step_by(8) {
                text.insert_tag(i, Tag::PushForm(form1), marker);
                text.insert_tag(i + 4, Tag::PopForm(form1), marker);
            }

            text
        };

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

        ((self.builder)(file), Box::new(|| false))
    }

    pub(crate) fn open_path(self, path: PathBuf) -> Self {
        Self {
            text_op: TextOp::OpenPath(path),
            ..self
        }
    }

    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
        }
    }

    pub(crate) fn set_print_cfg(&mut self, cfg: PrintCfg) {
        self.cfg = cfg;
    }

    pub(crate) fn set_input(&mut self, input: impl InputMethod<U, Widget = File> + Clone) {
        self.builder = Arc::new(move |file| Widget::active(file, RwData::new(input.clone())));
    }

    pub(crate) fn mut_print_cfg(&mut self) -> &mut PrintCfg {
        &mut self.cfg
    }
}

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

    fn build(self, _context: Context<U>, _: bool) -> (Widget<U>, impl Fn() -> bool, PushSpecs) {
        let specs = self.specs;
        let (widget, checker) = self.build();
        (widget, checker, specs)
    }
}

impl<U> Default for FileCfg<U>
where
    U: Ui,
{
    fn default() -> Self {
        Self::new()
    }
}

impl<U> Clone for FileCfg<U>
where
    U: Ui,
{
    fn clone(&self) -> Self {
        Self {
            text_op: TextOp::NewBuffer,
            builder: self.builder.clone(),
            cfg: self.cfg.clone(),
            specs: self.specs,
        }
    }
}

/// The widget that is used to print and edit files.
pub struct File {
    path: Path,
    text: Text,
    cfg: PrintCfg,
    history: History,
    printed_lines: Vec<(usize, bool)>,
    _readers: Vec<Box<dyn Reader>>,
}

impl File {
    pub fn write(&self) -> Result<usize, String> {
        if let Path::Set(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",
            ))
        }
    }

    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())?))
    }

    pub fn history_mut(&mut self) -> &mut History {
        &mut self.history
    }

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

/// # Querying functions
///
/// These functions serve the purpose of querying information from
/// the [`File`].
impl File {
    pub fn search(&self) -> Searcher<'_> {
        Searcher::new_at(Point::default(), self.text.iter().no_ghosts().no_conceals())
    }

    pub fn search_at(&self, point: Point) -> Searcher<'_> {
        Searcher::new_at(point, self.text.iter_at(point).no_ghosts().no_conceals())
    }

    pub fn rev_search(&self) -> RevSearcher<'_> {
        RevSearcher::new_at(
            self.text.max_point(),
            self.text.rev_iter().no_ghosts().no_conceals(),
        )
    }

    pub fn rev_search_at(&self, point: Point) -> RevSearcher<'_> {
        RevSearcher::new_at(
            point,
            self.text.rev_iter_at(point).no_ghosts().no_conceals(),
        )
    }

    /// 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::Set(path) => path.to_string_lossy().to_string(),
            Path::UnSet(id) => format!("*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::Set(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::Set(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::Set(path) => Some(path.file_name().unwrap().to_string_lossy().to_string()),
            Path::UnSet(_) => None,
        }
    }

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

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

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

    /// 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) -> &[(usize, bool)] {
        &self.printed_lines
    }
}

/// # History related functions.
///
/// These functions allow for the modification of the [`File`]'s
/// [`Text`] by navigating through a [`History`]'s changes.
/// For now, this is a linear history (i.e. modification removes all
/// future changes), but the plan is to change it to a tree at some
/// point.
impl File {
    /// Begins a new moment in history.
    ///
    /// A new moment makes it so that "undoing" or "redoing" will undo
    /// or redo all the changes in the moment. The previous moment can
    /// be undone, undoing multiple changes at once.
    pub fn add_moment(&mut self) {
        self.history.add_moment()
    }

    /// Redoes the next moment, if there is one.
    pub fn redo(&mut self, area: &impl Area, cursors: &mut Cursors) {
        self.history.redo(&mut self.text, area, &self.cfg, cursors)
    }

    /// Undoes the last moment, if there was one.
    pub fn undo(&mut self, area: &impl Area, cursors: &mut Cursors) {
        self.history.undo(&mut self.text, area, &self.cfg, cursors)
    }

    /// Returns a mutable reference to the [`Text`] and [`History`] of
    /// the [`File`].
    pub fn mut_text_and_history(&mut self) -> (&mut Text, &mut History) {
        (&mut self.text, &mut self.history)
    }
}

impl<U> PassiveWidget<U> for File
where
    U: Ui,
{
    fn build(_context: Context<U>, _: bool) -> (Widget<U>, impl Fn() -> bool, crate::ui::PushSpecs)
    where
        Self: Sized,
    {
        let (widget, checker) = FileCfg::new().build();
        (widget, checker, PushSpecs::above())
    }

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

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

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

    fn once(_context: crate::Context<U>) {}

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

        let mut last_line = area
            .rev_print_iter(self.text.rev_iter_at(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;

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

impl<U> ActiveWidget<U> for File
where
    U: Ui,
{
    fn mut_text(&mut self) -> &mut Text {
        &mut self.text
    }

    fn on_focus(&mut self, _area: &<U as Ui>::Area) {}

    fn on_unfocus(&mut self, _area: &<U as Ui>::Area) {}
}

unsafe impl Send for File {}
unsafe impl Sync for File {}

#[derive(Clone)]
enum Path {
    Set(PathBuf),
    UnSet(usize),
}

impl 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))
    }
}

enum TextOp {
    NewBuffer,
    TakeText(Text, Path),
    OpenPath(PathBuf),
}