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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
mod builder;

use std::{
    fmt::Debug,
    sync::{
        atomic::{AtomicBool, Ordering},
        mpsc,
    },
};

use crossterm::event::KeyEvent;

pub use self::builder::{FileBuilder, WindowBuilder};
use crate::{
    data::RoData,
    hooks::{self, OnFileOpen},
    palette::Painter,
    text::{Item, IterCfg, Point, PrintCfg, Text},
    widgets::{File, PassiveWidget, Widget},
    Context,
};

/// A direction, where a [`Widget<U>`] will be placed in relation to
/// another.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Side {
    Above,
    Right,
    Below,
    Left,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Constraint {
    Ratio(u16, u16),
    Percent(u16),
    Length(f64),
    Min(f64),
    Max(f64),
}

/// Information on how a [`Widget<U>`] should be pushed onto another.
///
/// The side member determines what direction to push into, in
/// relation to the original widget.
///
/// The [`Constraint`] can be one of five types:
///
/// - [`Min(min)`][Constraint::Min] represents the minimum length, in
///   the side's [`Axis`], that this new widget needs.
/// - [`Max(max)`][Constraint::Max] represents the minimum length, in
///   the side's [`Axis`], that this new widget needs.
/// - [`Length(len)`][Constraint::Length] represents a length, in the
///   side's [`Axis`], that cannot be altered by any means.
/// - [`Ratio(den, div)`][Constraint::Ratio] represents a ratio
///   between the length of the child and the length of the parent.
/// - [`Percent(per)`][Constraint::Percent] represents the percent of
///   the parent that the child must take. Must go from 0 to 100
///   percent.
///
/// So if, for example, if a widget is pushed with
/// [`PushSpecs::left(Constraint::Min(3.0)`][Self::left()]
///
/// into another widget, then it will be placed on the left side of
/// that widget, and will have a minimum `width` of `3`.
///
/// If it were pushed with either [`PushSpecs::above()`] or
/// [`PushSpecs::below()`], it would instead have a minimum `height`
/// of `3`.
#[derive(Debug, Clone, Copy)]
pub struct PushSpecs {
    side: Side,
    constraint: Option<Constraint>,
}

impl PushSpecs {
    /// Returns a new instance of [`PushSpecs`].
    pub fn left() -> Self {
        Self {
            side: Side::Left,
            constraint: None,
        }
    }

    /// Returns a new instance of [`PushSpecs`].
    pub fn right() -> Self {
        Self {
            side: Side::Right,
            constraint: None,
        }
    }

    /// Returns a new instance of [`PushSpecs`].
    pub fn above() -> Self {
        Self {
            side: Side::Above,
            constraint: None,
        }
    }

    /// Returns a new instance of [`PushSpecs`].
    pub fn below() -> Self {
        Self {
            side: Side::Below,
            constraint: None,
        }
    }

    /// Returns a new instance of [`PushSpecs`].
    pub fn to_left(self) -> Self {
        Self {
            side: Side::Left,
            ..self
        }
    }

    /// Returns a new instance of [`PushSpecs`].
    pub fn to_right(self) -> Self {
        Self {
            side: Side::Right,
            ..self
        }
    }

    /// Returns a new instance of [`PushSpecs`].
    pub fn to_above(self) -> Self {
        Self {
            side: Side::Above,
            ..self
        }
    }

    /// Returns a new instance of [`PushSpecs`].
    pub fn to_below(self) -> Self {
        Self {
            side: Side::Below,
            ..self
        }
    }

    pub fn with_lenght(self, len: f64) -> Self {
        Self {
            constraint: Some(Constraint::Length(len)),
            ..self
        }
    }

    pub fn with_minimum(self, min: f64) -> Self {
        Self {
            constraint: Some(Constraint::Min(min)),
            ..self
        }
    }

    pub fn with_maximum(self, max: f64) -> Self {
        Self {
            constraint: Some(Constraint::Max(max)),
            ..self
        }
    }

    pub fn with_percent(self, percent: u16) -> Self {
        Self {
            constraint: Some(Constraint::Percent(percent)),
            ..self
        }
    }

    pub fn with_ratio(self, den: u16, div: u16) -> Self {
        Self {
            constraint: Some(Constraint::Ratio(den, div)),
            ..self
        }
    }

    pub fn axis(&self) -> Axis {
        match self.side {
            Side::Above | Side::Below => Axis::Vertical,
            Side::Right | Side::Left => Axis::Horizontal,
        }
    }

    pub fn comes_earlier(&self) -> bool {
        matches!(self.side, Side::Left | Side::Above)
    }

    pub fn constraint(&self) -> Option<Constraint> {
        self.constraint
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Caret {
    pub x: usize,
    pub len: usize,
    pub wrap: bool,
}

impl Caret {
    #[inline(always)]
    pub fn new(x: usize, len: usize, wrap: bool) -> Self {
        Self { x, len, wrap }
    }
}

/// An [`Area`] that supports printing [`Text`].
///
/// These represent the entire GUI of Parsec, the only parts of the
/// screen where text may be printed.
pub trait Area: Send + Sync + Sized {
    type ConstraintChangeErr: Debug;

    /// Gets the width of the area.
    fn width(&self) -> usize;

    /// Gets the height of the area.
    fn height(&self) -> usize;

    /// Scrolls the [`Text`] (up or down) until the main cursor is
    /// within the [`ScrollOff`][crate::text::ScrollOff] range.
    fn scroll_around_point(&self, text: &Text, point: Point, cfg: &PrintCfg);

    // Returns the [`Point`]s that would printed first.
    fn top_left(&self) -> (Point, Option<Point>);

    /// Tells the [`Ui`] that this [`Area`] is the one that is
    /// currently focused.
    ///
    /// Should make [`self`] the active [`Area`] while deactivating
    /// any other active [`Area`].
    fn set_as_active(&self);

    /// Returns `true` if this is the currently active [`Area`].
    ///
    /// Only one [`Area`] should be active at any given moment.
    fn is_active(&self) -> bool;

    /// Prints the [`Text`][crate::text::Text] via an [`Iterator`].
    fn print(&self, text: &Text, cfg: &PrintCfg, painter: Painter);

    fn print_with<'a>(
        &self,
        text: &Text,
        cfg: &PrintCfg,
        painter: Painter,
        f: impl FnMut(&Caret, &Item) + 'a,
    );

    fn change_constraint(
        &self,
        constraint: Constraint,
        axis: Axis,
    ) -> Result<(), Self::ConstraintChangeErr>;

    /// Requests that the width be enough to fit a certain piece of
    /// text.
    fn request_width_to_fit(&self, text: &str) -> Result<(), Self::ConstraintChangeErr>;

    //////////////////// Queries
    /// Wether or not [`self`] has changed.
    ///
    /// This would mean anything relevant that wouldn't be determined
    /// by [`PrintInfo`], this is most likely going to be the bounding
    /// box, but it may be something else.
    fn has_changed(&self) -> bool;

    /// Wether or not [`self`] has seniority over `other`
    ///
    /// This can only happen if, by following [`self`]'s children, you
    /// would eventually reach `other`.
    fn is_senior_of(&self, other: &Self) -> bool;

    /// Returns a printing iterator.
    ///
    /// Given an [`Iterator`] with an [`Item`] of type `(usize,
    /// usize, Part)`, where:
    ///
    /// - The first `usize` is the byte index from the file's start;
    /// - The second `usize` is the current line;
    /// - The [`Part`] is either a `char` or a [`Text`] modifier;
    ///
    /// Returns an [`Iterator`] with an [`Item`] of type `((usize,
    /// usize, Option<usize>), (usize, Part))`, where:
    ///
    /// * On the first tuple:
    ///   - The first `usize` is the current horizontal position;
    ///   - The second `usize` is the length of the [`Part`]. It is
    ///     only greater than 0 if the part is a `char`;
    ///   - The [`Option<usize>`] represents a wrapping. It is
    ///     [`Some(usize)`], where the number is the current line,
    ///     only if the `char` wraps around. For example, any `char`
    ///     following a `'\n'` should return `Some(current_line)`,
    ///     since they show up in the next line;
    ///
    /// * On the second tuple:
    ///   - The `usize` is the byte index from the file's start;
    ///   - The [`Part`] is either a `char` or a [`Text`] modifier;
    ///
    /// [`Item`]: Iterator::Item
    /// [`Option<usize>`]: Option
    /// [`Some(usize)`]: Some
    fn print_iter<'a>(
        &self,
        iter: impl Iterator<Item = Item> + Clone + 'a,
        cfg: IterCfg<'a>,
    ) -> impl Iterator<Item = (Caret, Item)> + Clone + 'a
    where
        Self: Sized;

    fn print_iter_from_top<'a>(
        &self,
        text: &'a Text,
        cfg: IterCfg<'a>,
    ) -> impl Iterator<Item = (Caret, Item)> + Clone + 'a
    where
        Self: Sized;

    /// Returns a reverse printing iterator.
    ///
    /// Given an [`Iterator`] with an [`Item`] of type `(usize,
    /// usize, Part)`, where:
    ///
    /// - The first `usize` is the byte index from the file's start;
    /// - The second `usize` is the current line;
    /// - The [`Part`] is either a `char` or a [`Text`] modifier;
    ///
    /// Returns an [`Iterator`] with an [`Item`] of type `((usize,
    /// usize, Option<usize>), (usize, Part))`, where:
    ///
    /// * On the first tuple:
    ///   - The first `usize` is the current horizontal position;
    ///   - The second `usize` is the length of the [`Part`]. It is
    ///     only greater than 0 if the part is a `char`;
    ///   - The [`Option<usize>`] represents a wrapping. It is
    ///     [`Some(usize)`], where the number is the current line,
    ///     only if the `char` wraps around. For example, any `char`
    ///     following a `'\n'` should return `Some(current_line)`,
    ///     since they show up in the next line;
    ///
    /// * On the second tuple:
    ///   - The `usize` is the byte index from the file's start;
    ///   - The [`Part`] is either a `char` or a [`Text`] modifier;
    ///
    /// [`Item`]: Iterator::Item
    /// [`Option<usize>`]: Option
    /// [`Some(usize)`]: Some
    fn rev_print_iter<'a>(
        &self,
        iter: impl Iterator<Item = Item> + Clone + 'a,
        cfg: IterCfg<'a>,
    ) -> impl Iterator<Item = (Caret, Item)> + Clone + 'a;

    /// Bisects the [`Area`][Ui::Area] with the given index into
    /// two.
    ///
    /// Will return 2 indices, the first one is the index of a new
    /// area. The second is an index for a newly created parent
    ///
    /// As an example, assuming that [`self`] has an index of `0`,
    /// pushing an area to [`self`] on [`Side::Left`] would create
    /// 2 new areas:
    ///
    /// ```text
    /// ╭────────0────────╮     ╭────────0────────╮
    /// │                 │     │╭──2───╮╭───1───╮│
    /// │      self       │ --> ││      ││ self  ││
    /// │                 │     │╰──────╯╰───────╯│
    /// ╰─────────────────╯     ╰─────────────────╯
    /// ```
    ///
    /// This means that `0` is now the index of the newly created
    /// parent, `2` is the index of the new area, and `1` is the new
    /// index of the initial area. In the end, [`Window::bisect()`]
    /// should return `(2, Some(1))`.
    ///
    /// That doesn't always happen though. For example, pushing
    /// another area to the [`Side::Right`] of `1`, `2`, or `0`, in
    /// this situation, should not result in the creation of a new
    /// parent:
    ///
    /// ```text
    /// ╭────────0────────╮     ╭────────0────────╮
    /// │╭──2───╮╭───1───╮│     │╭─2─╮╭──1──╮╭─3─╮│
    /// ││      ││ self  ││     ││   ││self ││   ││
    /// │╰──────╯╰───────╯│     │╰───╯╰─────╯╰───╯│
    /// ╰─────────────────╯     ╰─────────────────╯
    /// ```
    ///
    /// And so [`Window::bisect()`] should return `(3, None)`.
    fn bisect(&self, specs: PushSpecs, cluster: bool) -> (Self, Option<Self>);
}

/// Elements related to the [`Widget<U>`]s.
pub struct Node<U>
where
    U: Ui,
{
    widget: Widget<U>,
    checker: Box<dyn Fn() -> bool>,
    area: U::Area,
    busy_updating: AtomicBool,
}

unsafe impl<U: Ui> Send for Node<U> {}
unsafe impl<U: Ui> Sync for Node<U> {}

impl<U> Node<U>
where
    U: Ui,
{
    pub fn needs_update(&self) -> bool {
        if !self.busy_updating.load(Ordering::Acquire) {
            (self.checker)() || self.area.has_changed()
        } else {
            false
        }
    }

    pub fn update_and_print(&self) {
        self.busy_updating.store(true, Ordering::Release);

        self.widget.update_and_print(&self.area);

        self.busy_updating.store(false, Ordering::Release);
    }
}

/// A dimension on screen, can either be horizontal or vertical.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Axis {
    Horizontal,
    Vertical,
}

impl Axis {
    pub fn perp(&self) -> Self {
        match self {
            Axis::Horizontal => Axis::Vertical,
            Axis::Vertical => Axis::Horizontal,
        }
    }
}

impl From<PushSpecs> for Axis {
    fn from(value: PushSpecs) -> Self {
        if let Side::Above | Side::Below = value.side {
            Axis::Vertical
        } else {
            Axis::Horizontal
        }
    }
}

pub enum Event {
    Key(KeyEvent),
    Resize,
    FormChange,
    ReloadConfig,
    OpenFiles,
    Quit,
}

pub struct Sender(mpsc::Sender<Event>);

impl Sender {
    pub fn new(sender: mpsc::Sender<Event>) -> Self {
        Self(sender)
    }

    pub fn send_key(&self, key: KeyEvent) -> Result<(), mpsc::SendError<Event>> {
        self.0.send(Event::Key(key))
    }

    pub fn send_resize(&self) -> Result<(), mpsc::SendError<Event>> {
        self.0.send(Event::Resize)
    }

    pub fn send_reload_config(&self) -> Result<(), mpsc::SendError<Event>> {
        self.0.send(Event::ReloadConfig)
    }

    pub(crate) fn _send_form_changed(&self) -> Result<(), mpsc::SendError<Event>> {
        self.0.send(Event::FormChange)
    }
}

/// All the methods that a working gui/tui will need to implement, in
/// order to use Parsec.
pub trait Ui: Sized + 'static {
    /// This is the underlying type that will be handled dynamically.
    type StaticFns: Default + Clone + Copy + Send + Sync;
    // May be removed later.
    type ConstraintChangeErr: Debug;
    type Area: Area<ConstraintChangeErr = Self::ConstraintChangeErr> + Clone + PartialEq;

    fn new(statics: Self::StaticFns) -> Self;

    /// Initiates and returns a new "master" [`Area`].
    ///
    /// This [`Area`] must not have any parents, and must be placed on
    /// a new window, that is, a plain region with nothing in it.
    ///
    /// [`Area`]: Ui::Area
    fn new_root(&mut self) -> Self::Area;

    /// Functions to trigger when the program begins.
    fn open(&mut self);

    /// Starts the Ui.
    ///
    /// This is different from [`Ui::open`], as this is going to run
    /// on reloads as well.
    fn start(&mut self, sender: Sender, globals: Context<Self>);

    /// Ends the Ui.
    ///
    /// This is different from [`Ui::close`], as this is going to run
    /// on reloads as well.
    fn end(&mut self);

    /// Functions to trigger when the program ends.
    fn close(&mut self);

    fn finish_printing(&self);
}

/// A container for a master [`Area`] in Parsec.
pub struct Window<U>
where
    U: Ui,
{
    nodes: Vec<Node<U>>,
    files_region: U::Area,
    master_area: U::Area,
}

impl<U> Window<U>
where
    U: Ui + 'static,
{
    /// Returns a new instance of [`Window<U>`].
    pub fn new(
        ui: &mut U,
        widget: Widget<U>,
        checker: impl Fn() -> bool + 'static,
    ) -> (Self, U::Area) {
        let area = ui.new_root();
        widget.update(&area);

        let main_node = Node {
            widget,
            checker: Box::new(checker),
            area: area.clone(),
            busy_updating: AtomicBool::new(false),
        };

        let window = Self {
            nodes: vec![main_node],
            files_region: area.clone(),
            master_area: area.clone(),
        };

        (window, area)
    }

    /// Pushes a [`Widget<U>`] onto an existing one.
    pub fn push(
        &mut self,
        widget: Widget<U>,
        area: &U::Area,
        checker: impl Fn() -> bool + 'static,
        specs: PushSpecs,
        cluster: bool,
    ) -> (U::Area, Option<U::Area>) {
        let (child, parent) = area.bisect(specs, cluster);

        let node = Node {
            widget,
            checker: Box::new(checker),
            area: child.clone(),
            busy_updating: AtomicBool::new(false),
        };

        if *area == self.master_area
            && let Some(new_master_node) = parent.clone()
        {
            self.master_area = new_master_node;
        }

        self.nodes.push(node);
        (child, parent)
    }

    /// Pushes a [`File`] to the file's parent.
    ///
    /// This function will push to the edge of `self.files_parent`.
    /// This is an area, usually in the center, that contains all
    /// [`File`]s, and their associated [`Widget<U>`]s,
    /// with others being at the perifery of this area.
    pub fn push_file(
        &mut self,
        widget: Widget<U>,
        checker: impl Fn() -> bool + 'static,
        specs: PushSpecs,
    ) -> (U::Area, Option<U::Area>) {
        let area = self.files_region.clone();

        let (child, parent) = self.push(widget, &area, checker, specs, false);
        if let Some(parent) = &parent {
            self.files_region = parent.clone();
        }

        (child, parent)
    }

    /// Pushes a [`Widget<U>`] to the master node of the current
    /// window.
    pub fn push_to_master<Checker>(
        &mut self,
        widget: Widget<U>,
        checker: Checker,
        specs: PushSpecs,
    ) -> (U::Area, Option<U::Area>)
    where
        Checker: Fn() -> bool + 'static,
    {
        let master_area = self.master_area.clone();
        self.push(widget, &master_area, checker, specs, false)
    }

    /// Returns an [`Iterator`] over the [`Widget<U>`]s of [`self`].
    pub fn widgets(&self) -> impl DoubleEndedIterator<Item = (&Widget<U>, &U::Area)> + Clone + '_ {
        self.nodes
            .iter()
            .map(|Node { widget, area, .. }| (widget, area))
    }

    pub fn nodes(&self) -> impl Iterator<Item = &Node<U>> {
        self.nodes.iter()
    }

    /// Returns an [`Iterator`] over the names of [`File`]s
    /// and their respective [`ActionableWidget`] indices.
    pub fn file_names(&self) -> impl Iterator<Item = (usize, String)> + Clone + '_ {
        self.nodes
            .iter()
            .enumerate()
            .filter_map(|(pos, Node { widget, .. })| {
                widget
                    .downcast::<File>()
                    .map(|file| (pos, file.read().name()))
            })
    }

    pub fn send_key(&self, key: KeyEvent, globals: Context<U>) {
        if let Some(node) = self
            .nodes()
            .find(|node| globals.current_widget.widget_ptr_eq(&node.widget))
        {
            node.widget.send_key(key, &node.area, globals);
        }
    }

    pub fn len_widgets(&self) -> usize {
        self.nodes.len()
    }

    pub(crate) fn files_region(&self) -> &U::Area {
        &self.files_region
    }
}

pub struct RoWindow<'a, U>(&'a Window<U>)
where
    U: Ui;

impl<'a, U> RoWindow<'a, U>
where
    U: Ui,
{
    /// Similar to the [`Iterator::fold`] operation, folding each
    /// [`&File`][File`] by applying an operation,
    /// returning a final result.
    ///
    /// The reason why this is a `fold` operation, and doesn't just
    /// return an [`Iterator`], is because `f` will act on a
    /// reference, as to not do unnecessary cloning of the widget's
    /// inner [`RwData<W>`], and because [`Iterator`]s cannot return
    /// references to themselves.
    pub fn fold_files<B>(&self, init: B, mut f: impl FnMut(B, &File) -> B) -> B {
        self.0
            .nodes
            .iter()
            .fold(init, |accum, Node { widget, .. }| {
                if let Some(file) = widget.downcast::<File>() {
                    f(accum, &file.read())
                } else {
                    accum
                }
            })
    }

    /// Similar to the [`Iterator::fold`] operation, folding each
    /// [`&dyn Widget<U>`][Widget] by applying an
    /// operation, returning a final result.
    ///
    /// The reason why this is a `fold` operation, and doesn't just
    /// return an [`Iterator`], is because `f` will act on a
    /// reference, as to not do unnecessary cloning of the widget's
    /// inner [`RwData<W>`], and because [`Iterator`]s cannot return
    /// references to themselves.
    pub fn fold_widgets<B>(&self, init: B, mut f: impl FnMut(B, &dyn PassiveWidget<U>) -> B) -> B {
        self.0
            .nodes
            .iter()
            .fold(init, |accum, Node { widget, .. }| {
                let f = &mut f;
                widget.raw_inspect(|widget| f(accum, widget))
            })
    }
}

pub struct RoWindows<U>(RoData<Vec<Window<U>>>)
where
    U: Ui;

impl<U> RoWindows<U>
where
    U: Ui,
{
    pub fn new(windows: RoData<Vec<Window<U>>>) -> Self {
        RoWindows(windows)
    }

    pub fn inspect_nth<B>(&self, index: usize, f: impl FnOnce(RoWindow<U>) -> B) -> Option<B> {
        let windows = self.0.read();
        windows.get(index).map(|window| f(RoWindow(window)))
    }

    pub fn try_inspect_nth<B>(&self, index: usize, f: impl FnOnce(RoWindow<U>) -> B) -> Option<B> {
        self.0
            .try_read()
            .and_then(|windows| windows.get(index).map(|window| f(RoWindow(window))))
    }
}

pub(crate) fn build_file<U>(window: &mut Window<U>, mod_area: U::Area, globals: Context<U>)
where
    U: Ui,
{
    let old_file = {
        let node = window
            .nodes
            .iter()
            .find(|Node { area, .. }| *area == mod_area)
            .unwrap();

        node.widget.downcast::<File>().map(|file| {
            globals.current_file.swap((
                file,
                node.area.clone(),
                node.widget.input().unwrap().clone(),
                node.widget.related_widgets().unwrap(),
            ))
        })
    };

    let mut builder = FileBuilder::new(window, mod_area, globals);
    hooks::trigger::<OnFileOpen<U>>(&mut builder);

    if let Some(parts) = old_file {
        globals.current_file.swap(parts);
    };
}