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
//! UI spacing & layout rendering methods.
//!
//! Provided [`PixState`] methods:
//!
//! - [`PixState::same_line`]
//! - [`PixState::next_width`]
//! - [`PixState::tab_bar`]
//! - [`PixState::spacing`]
//! - [`PixState::indent`]
//! - [`PixState::separator`]
//!
//! # Example
//!
//! ```
//! # use pix_engine::prelude::*;
//! # struct App { checkbox: bool, text_field: String, selected: &'static str };
//! # impl PixEngine for App {
//! fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
//!     s.text("Text")?;
//!     s.same_line(None);
//!     s.text("Same line")?;
//!     s.same_line([20, 0]);
//!     s.text("Same line with a +20 horizontal pixel offset")?;
//!
//!     s.separator();
//!
//!     s.spacing()?;
//!     s.indent()?;
//!     s.text("Indented!")?;
//!
//!     s.next_width(200);
//!     if s.button("Button")? {
//!         // was clicked
//!     }
//!
//!     s.tab_bar(
//!         "Tab bar",
//!         &["Tab 1", "Tab 2"],
//!         &mut self.selected,
//!         |tab: &&str, s: &mut PixState| {
//!             match tab {
//!                 &"Tab 1" => {
//!                     s.text("Tab 1 Content")?;
//!                 },
//!                 &"Tab 2" => {
//!                     s.text("Tab 2 Content")?;
//!                 },
//!                 _ => (),
//!             }
//!             Ok(())
//!         }
//!     )?;
//!     Ok(())
//! }
//! # }
//! ```

use crate::{ops::clamp_size, prelude::*};

impl PixState {
    /// Reset current UI rendering position back to the previous line with item padding, and
    /// continue with horizontal layout.
    ///
    /// You can optionally change the item padding, or set a different horizontal or vertical
    /// position by passing in an `offset`.
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// # struct App { checkbox: bool, text_field: String };
    /// # impl PixEngine for App {
    /// fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    ///     s.text("Text")?;
    ///     s.same_line(None);
    ///     s.text("Same line")?;
    ///     Ok(())
    /// }
    /// # }
    /// ```
    #[inline]
    pub fn same_line<O>(&mut self, offset: O)
    where
        O: Into<Option<[i32; 2]>>,
    {
        let pos = self.ui.pcursor();
        let offset = offset.into().unwrap_or([0; 2]);
        let item_pad = self.theme.spacing.item_pad;
        self.ui
            .set_cursor([pos.x() + item_pad.x() + offset[0], pos.y() + offset[1]]);
        self.ui.line_height = self.ui.pline_height;
    }

    /// Change the default width of the next rendered element for elements that typically take up
    /// the remaining width of the window/frame they are rendered in.
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// # struct App { checkbox: bool, text_field: String };
    /// # impl PixEngine for App {
    /// fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    ///     s.next_width(200);
    ///     if s.button("Button")? {
    ///         // was clicked
    ///     }
    ///     Ok(())
    /// }
    /// # }
    /// ```
    #[inline]
    pub fn next_width(&mut self, width: u32) {
        self.ui.next_width = Some(clamp_size(width));
    }

    /// Draw a tabbed view to the current canvas. It accepts a list of tabs to be rendered, which
    /// one is selected and a closure that is passed the current tab and [`&mut
    /// PixState`][`PixState`] which you can use to draw all the standard drawing primitives and
    /// change any drawing settings. Settings changed inside the closure will not persist. Returns
    /// `true` if a tab selection was changed.
    ///
    /// # Errors
    ///
    /// If the renderer fails to draw to the current render target, then an error is returned.
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// # struct App { selected: &'static str };
    /// # impl PixEngine for App {
    /// fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    ///     s.tab_bar(
    ///         "Tab bar",
    ///         &["Tab 1", "Tab 2"],
    ///         &mut self.selected,
    ///         |tab: &&str, s: &mut PixState| {
    ///             match tab {
    ///                 &"Tab 1" => {
    ///                     s.text("Tab 1")?;
    ///                     s.separator();
    ///                     s.text("Some Content")?;
    ///                 }
    ///                 &"Tab 2" => {
    ///                     s.next_width(200);
    ///                     if s.button("Click me")? {
    ///                         // was clicked
    ///                     }
    ///                 }
    ///                 _ => (),
    ///             }
    ///             Ok(())
    ///         }
    ///     )?;
    ///     Ok(())
    /// }
    /// # }
    /// ```
    pub fn tab_bar<S, I, F>(
        &mut self,
        label: S,
        tabs: &[I],
        selected: &mut I,
        f: F,
    ) -> PixResult<bool>
    where
        S: AsRef<str>,
        I: AsRef<str> + Copy,
        F: FnOnce(&I, &mut PixState) -> PixResult<()>,
    {
        let label = label.as_ref();

        let s = self;
        let tab_id = s.ui.get_id(&label);
        let font_size = s.theme.font_size;
        let fpad = s.theme.spacing.frame_pad;
        let ipad = s.theme.spacing.item_pad;

        let mut changed = false;
        for (i, tab) in tabs.iter().enumerate() {
            if i > 0 {
                s.same_line([-ipad.x() + 2, 0]);
            } else {
                let pos = s.cursor_pos();
                s.set_cursor_pos([pos.x() + fpad.x(), pos.y()]);
            }
            let tab_label = tab.as_ref();
            let id = s.ui.get_id(&tab_label);
            let tab_label = s.ui.get_label(tab_label);
            let pos = s.cursor_pos();
            let colors = s.theme.colors;

            // Calculate tab size
            let (width, height) = s.text_size(tab_label)?;
            let tab_rect = rect![pos, width, height].offset_size(4 * ipad);

            // Check hover/active/keyboard focus
            let hovered = s.focused() && s.ui.try_hover(id, &tab_rect);
            let focused = s.focused() && s.ui.try_focus(id);
            let disabled = s.ui.disabled;
            let active = s.ui.is_active(id);

            s.push();
            s.ui.push_cursor();

            // Render
            s.rect_mode(RectMode::Corner);
            let clip = tab_rect.offset_size([1, 0]);
            s.clip(clip)?;
            if hovered {
                s.frame_cursor(&Cursor::hand())?;
            }
            let [stroke, fg, bg] = s.widget_colors(id, ColorType::SecondaryVariant);
            if active || focused {
                s.stroke(stroke);
            } else {
                s.stroke(None);
            }
            if hovered {
                s.fill(fg.blended(colors.background, 0.04));
            } else {
                s.fill(colors.background);
            }
            if active {
                s.clip(tab_rect.offset_size([2, 0]))?;
                s.rect(tab_rect.offset([1, 1]))?;
            } else {
                s.rect(tab_rect)?;
            }

            // Tab text
            s.rect_mode(RectMode::Center);
            s.set_cursor_pos(tab_rect.center());
            s.stroke(None);
            let is_active_tab = tab_label == selected.as_ref();
            if is_active_tab {
                s.fill(colors.secondary_variant);
            } else if hovered | focused {
                s.fill(fg);
            } else {
                s.fill(colors.secondary_variant.blended(bg, 0.60));
            }
            s.text(tab_label)?;
            s.clip(None)?;

            s.ui.pop_cursor();
            s.pop();

            // Process input
            s.ui.handle_focus(id);
            s.advance_cursor(tab_rect.size());
            if !disabled && s.ui.was_clicked(id) {
                changed = true;
                *selected = *tab;
            }
        }

        let pos = s.cursor_pos();
        s.set_cursor_pos([pos.x(), pos.y() - ipad.y() - font_size as i32 / 2]);
        s.separator()?;
        s.spacing()?;

        s.push_id(tab_id);
        f(selected, s)?;
        s.pop_id();

        Ok(changed)
    }
}

impl PixState {
    /// Draw a newline worth of spacing to the current canvas.
    ///
    /// # Errors
    ///
    /// If the renderer fails to draw to the current render target, then an error is returned.
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// # struct App { checkbox: bool, text_field: String };
    /// # impl PixEngine for App {
    /// fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    ///     s.text("Some text")?;
    ///     s.spacing()?;
    ///     s.text("Some other text")?;
    ///     Ok(())
    /// }
    /// # }
    /// ```
    pub fn spacing(&mut self) -> PixResult<()> {
        let s = self;
        let width = s.ui_width()?;
        let (_, height) = s.text_size(" ")?;
        s.advance_cursor([width, height]);
        Ok(())
    }

    /// Draw an indent worth of spacing to the current canvas.
    ///
    /// # Errors
    ///
    /// If the renderer fails to draw to the current render target, then an error is returned.
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// # struct App { checkbox: bool, text_field: String };
    /// # impl PixEngine for App {
    /// fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    ///     s.indent()?;
    ///     s.text("Indented!")?;
    ///     Ok(())
    /// }
    /// # }
    /// ```
    pub fn indent(&mut self) -> PixResult<()> {
        let s = self;
        let (width, height) = s.text_size("    ")?;
        s.advance_cursor([width, height]);
        s.same_line(None);
        Ok(())
    }

    /// Draw a horizontal or vertical separator to the current canvas.
    ///
    /// # Errors
    ///
    /// If the renderer fails to draw to the current render target, then an error is returned.
    ///
    /// # Example
    ///
    /// ```
    /// # use pix_engine::prelude::*;
    /// # struct App { checkbox: bool, text_field: String };
    /// # impl PixEngine for App {
    /// fn on_update(&mut self, s: &mut PixState) -> PixResult<()> {
    ///     s.text("Some text")?;
    ///     s.separator()?;
    ///     s.text("Some other text")?;
    ///     Ok(())
    /// }
    /// # }
    /// ```
    pub fn separator(&mut self) -> PixResult<()> {
        // TODO: Add s.layout(Direction) method
        let s = self;
        let pos = s.cursor_pos();
        let colors = s.theme.colors;
        let pad = s.theme.spacing.frame_pad;
        let height = clamp_size(s.theme.font_size);
        let y = pos.y() + height / 2;

        s.push();

        s.stroke(colors.disabled());
        let width = s.ui_width()?;
        s.line(line_![pad.x(), y, width, y])?;

        s.pop();
        s.advance_cursor([width, height]);

        Ok(())
    }
}