pushrod/root_widget.rs
1// Pushrod
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! # RootWidget
16//!
17//! The top-level `Widget` (ID `0`) that the `Engine` creates for every window. It fills the
18//! window with its color (white by default) and is the parent of every other `Widget`.
19//!
20//! It lives in the core so the engine doesn't depend on any widget library. Change the window
21//! background with `ui.get_mut::<RootWidget>(ROOT_WIDGET_ID).unwrap().set_color(..)`, or
22//! [`Engine::set_background`](crate::engine::Engine::set_background).
23
24use crate::color::Color;
25use crate::geometry::{Point, Size};
26use crate::paint::{self, Painter};
27use crate::widget::{Widget, WidgetCore};
28
29/// The window's root `Widget`: a flat fill of its color.
30///
31/// The `Engine` creates one as `Widget` `0` for every window. It is the parent of every other
32/// `Widget`.
33pub struct RootWidget {
34 core: WidgetCore,
35}
36
37impl Widget for RootWidget {
38 /// Returns the root `Widget`'s shared state.
39 ///
40 /// # Returns
41 ///
42 /// The `WidgetCore`.
43 fn core(&self) -> &WidgetCore {
44 &self.core
45 }
46
47 /// Returns the root `Widget`'s shared state for modification.
48 ///
49 /// # Returns
50 ///
51 /// The `WidgetCore`.
52 fn core_mut(&mut self) -> &mut WidgetCore {
53 &mut self.core
54 }
55
56 /// Fills the window with the root `Widget`'s color.
57 ///
58 /// # Arguments
59 ///
60 /// * `p` - The painter, targeting the root `Widget`.
61 fn paint(&self, p: &mut dyn Painter) {
62 paint::fill(p, self.get_color());
63 }
64}
65
66impl RootWidget {
67 /// Creates a root `Widget` covering a window, filled with white.
68 ///
69 /// # Arguments
70 ///
71 /// * `size` - The size of the window in pixels.
72 ///
73 /// # Returns
74 ///
75 /// The new `RootWidget`.
76 pub fn new(size: Size) -> Self {
77 let mut root = Self {
78 core: WidgetCore::new(Point::new(0, 0), size),
79 };
80 root.set_color(Color::RGBA(255, 255, 255, 255));
81 root
82 }
83}