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
//! A widget that piles multiple widgets into a single area.

use std::collections::VecDeque;
use std::sync::Arc;

use ahash::AHashMap;
use alot::{LotId, Lots};
use figures::units::UPx;
use figures::{IntoSigned, Rect, Size};
use intentional::Assert;

use crate::context::{EventContext, GraphicsContext, LayoutContext};
use crate::value::{Dynamic, DynamicRead, DynamicReader};
use crate::widget::{MakeWidget, MakeWidgetWithTag, Widget, WidgetInstance, WidgetRef, WidgetTag};
use crate::ConstraintLimit;

/// A pile of widgets that shows the top widget.
///
/// This is a lower level widget that is similar to a
/// [`Switcher`](super::switcher::Switcher) except that all widgets held in the
/// pile remain mounted in the window when not active. This allows widgets to
/// retain information stored in a [`WindowLocal`](crate::window::WindowLocal).
#[derive(Debug, Clone, Default)]
pub struct Pile {
    data: Dynamic<PileData>,
}

#[derive(Default, Debug)]
struct PileData {
    widgets: Lots<Option<WidgetInstance>>,
    visible: VecDeque<LotId>,
    focus_visible: bool,
}

impl PileData {
    fn hide_id(&mut self, to_remove: LotId) {
        let Some((index, _)) = self
            .visible
            .iter()
            .enumerate()
            .find(|(_index, id)| **id == to_remove)
        else {
            return;
        };
        self.visible.remove(index);
    }
}

impl Pile {
    /// Returns a placeholder that can be used to show/close a piled widget
    /// before it has been constructed.
    #[must_use]
    pub fn new_pending(&self) -> PendingPiledWidget {
        let mut pile = self.data.lock();
        let id = pile.widgets.push(None);
        PendingPiledWidget(Some(PiledWidget(Arc::new(PiledWidgetData {
            pile: self.clone(),
            id,
        }))))
    }

    /// Adds a new widget to the pile.
    ///
    /// If this is the first widget, it will become visible automatically.
    /// Otherwise, it will be placed at the bottom of the pile.
    ///
    /// When the last clone of the returned [`PiledWidget`] is dropped, `widget`
    /// will be removed from the pile. If it is the currently visible widget,
    /// the next widget in the pile will be made visible.
    pub fn push(&self, widget: impl MakeWidget) -> PiledWidget {
        self.new_pending().finish(widget)
    }
}

impl MakeWidgetWithTag for Pile {
    fn make_with_tag(self, tag: WidgetTag) -> WidgetInstance {
        WidgetPile {
            pile: self.data.into_reader(),
            widgets: AHashMap::new(),
            last_visible: None,
        }
        .make_with_tag(tag)
    }
}

#[derive(Debug)]
struct WidgetPile {
    pile: DynamicReader<PileData>,
    widgets: AHashMap<LotId, WidgetRef>,
    last_visible: Option<LotId>,
}

impl WidgetPile {
    fn synchronize_widgets(&mut self) {
        let pile = self.pile.read();
        for (id, widget) in pile.widgets.entries() {
            if let Some(widget) = widget.as_ref() {
                self.widgets
                    .entry(id)
                    .or_insert_with(|| WidgetRef::new(widget.clone()));
            }
        }

        self.widgets.retain(|id, _| pile.widgets.get(*id).is_some());
    }
}

impl Widget for WidgetPile {
    fn layout(
        &mut self,
        available_space: Size<ConstraintLimit>,
        context: &mut LayoutContext<'_, '_, '_, '_>,
    ) -> Size<UPx> {
        context.invalidate_when_changed(&self.pile);
        self.synchronize_widgets();
        let pile = self.pile.read();
        let visible = pile.visible.front().copied();
        let size = if let Some(id) = visible {
            let visible = self
                .widgets
                .get_mut(&id)
                .expect("visible widget")
                .mounted(context);
            let mut child_context = context.for_other(&visible);
            if pile.focus_visible && self.last_visible != Some(id) {
                child_context.focus();
            }
            let size = child_context.layout(available_space);
            drop(child_context);
            context.set_child_layout(&visible, Rect::from(size).into_signed());
            size
        } else {
            available_space.map(ConstraintLimit::min)
        };

        self.last_visible = visible;

        size
    }

    fn redraw(&mut self, context: &mut GraphicsContext<'_, '_, '_, '_>) {
        context.invalidate_when_changed(&self.pile);
        self.synchronize_widgets();
        let pile = self.pile.read();
        if let Some(visible) = pile.visible.front() {
            let visible = self
                .widgets
                .get_mut(visible)
                .expect("visible widget")
                .mounted(context);
            context.for_other(&visible).redraw();
        }
    }

    fn unmounted(&mut self, context: &mut EventContext<'_>) {
        for widget in self.widgets.values_mut() {
            widget.unmount_in(context);
        }
    }
}

/// A placeholder for a widget in a [`Pile`].
pub struct PendingPiledWidget(Option<PiledWidget>);

impl PendingPiledWidget {
    /// Place `widget` in the pile and returns a handle to the placed widget.
    #[allow(clippy::must_use_candidate)]
    pub fn finish(mut self, widget: impl MakeWidget) -> PiledWidget {
        let piled = self.0.take().assert("finished called once");
        let mut pile = piled.0.pile.data.lock();
        pile.widgets[piled.0.id] = Some(widget.make_widget());
        pile.visible.push_back(piled.0.id);
        drop(pile);

        piled
    }
}

impl std::ops::Deref for PendingPiledWidget {
    type Target = PiledWidget;

    fn deref(&self) -> &Self::Target {
        self.0.as_ref().expect("accessed after finished")
    }
}

/// A widget that has been added to a [`Pile`].
#[derive(Clone, Debug)]
pub struct PiledWidget(Arc<PiledWidgetData>);

impl PiledWidget {
    /// Shows this widget in its pile.
    ///
    /// If `focus` is true, the widget will be focused when shown.
    pub fn show(&self, focus: bool) {
        let mut pile = self.0.pile.data.lock();
        pile.hide_id(self.0.id);
        pile.visible.push_front(self.0.id);
        pile.focus_visible = focus;
    }

    /// Removes this widget from the pile.
    pub fn remove(&self) {
        let mut pile = self.0.pile.data.lock();
        if pile.visible.front() == Some(&self.0.id) {
            pile.focus_visible = false;
        }
        pile.hide_id(self.0.id);
        pile.widgets.remove(self.0.id);
    }
}

#[derive(Clone, Debug)]
struct PiledWidgetData {
    pile: Pile,
    id: LotId,
}

impl Drop for PiledWidgetData {
    fn drop(&mut self) {
        let mut pile = self.pile.data.lock();
        pile.hide_id(self.id);
        pile.widgets.remove(self.id);
    }
}