瀏覽代碼

rustfmt pass.

Kestrel 4 月之前
父節點
當前提交
f6581fa7c1
共有 14 個文件被更改,包括 164 次插入99 次删除
  1. 13 10
      examples/button.rs
  2. 7 5
      examples/table_layout.rs
  3. 10 8
      src/layout.rs
  4. 10 2
      src/layout/arr.rs
  5. 11 9
      src/layout/arr/line.rs
  6. 11 7
      src/layout/arr/table.rs
  7. 20 22
      src/layout/calc.rs
  8. 0 1
      src/theme.rs
  9. 6 3
      src/ui.rs
  10. 12 4
      src/widget/button.rs
  11. 2 1
      src/widget/frame.rs
  12. 10 7
      src/widget/group.rs
  13. 20 7
      src/widget/label.rs
  14. 32 13
      src/window.rs

+ 13 - 10
examples/button.rs

@@ -15,16 +15,19 @@ struct ButtonWindow {
 impl ButtonWindow {
     fn new(uih: &mut UIHandle) -> Self {
         let mut group = widget::PlainGroup::new_column(uih);
-        group.extend(vec![
-            Box::new(widget::Spacer::new(uih)) as Box<dyn Widget<Self>>,
-            Box::new({
-                let mut button = widget::Button::new(uih);
-                button.set_label("Button label");
-                button.set_hook(Box::new(|| Some(ButtonWindowMsg::Shutdown)));
-                button
-            }),
-            Box::new(widget::Spacer::new(uih)),
-        ].into_iter());
+        group.extend(
+            vec![
+                Box::new(widget::Spacer::new(uih)) as Box<dyn Widget<Self>>,
+                Box::new({
+                    let mut button = widget::Button::new(uih);
+                    button.set_label("Button label");
+                    button.set_hook(Box::new(|| Some(ButtonWindowMsg::Shutdown)));
+                    button
+                }),
+                Box::new(widget::Spacer::new(uih)),
+            ]
+            .into_iter(),
+        );
         Self { group }
     }
 }

+ 7 - 5
examples/table_layout.rs

@@ -11,10 +11,13 @@ struct TableWindow {
 impl TableWindow {
     fn new(uih: &mut UIHandle) -> Self {
         let mut group = widget::PlainGroup::new_table(uih);
-        group.extend(vec![
-            Box::new(widget::Spacer::new(uih)) as Box<dyn Widget<Self>>,
-            Box::new(widget::Spacer::new(uih)),
-        ].into_iter());
+        group.extend(
+            vec![
+                Box::new(widget::Spacer::new(uih)) as Box<dyn Widget<Self>>,
+                Box::new(widget::Spacer::new(uih)),
+            ]
+            .into_iter(),
+        );
         Self { root: group }
     }
 }
@@ -48,4 +51,3 @@ impl WindowComponent for TableWindow {
 fn main() {
     patina::ui::make_opinionated_ui(TableWindow::new).run();
 }
-

+ 10 - 8
src/layout.rs

@@ -6,7 +6,7 @@
 //! - **Layout**: given minimum sizes and net size policies from the arrangement step, computes
 //! exact pixel values for positions and sizes.
 
-use std::{ops::Deref, rc::Rc, collections::HashMap};
+use std::{collections::HashMap, ops::Deref, rc::Rc};
 
 use cache::{Layer, LayoutCacheKey, NodeState};
 use kahlo::math::{PixelBox, PixelSideOffsets};
@@ -220,7 +220,7 @@ impl LayoutNode {
     }
 
     pub fn relayout_tree(&self) {
-        let mut to_mark : Vec<LayoutCacheKey> = vec![self.cache_key];
+        let mut to_mark: Vec<LayoutCacheKey> = vec![self.cache_key];
         while let Some(next) = to_mark.pop() {
             self.cache.with_state(next, |ns| {
                 ns.needs_update = true;
@@ -238,11 +238,13 @@ impl LayoutNode {
 
     /// Checks if node needs to be rerendered, clearing the flag if so.
     pub fn render_check(&self) -> bool {
-        self.cache.with_state(self.cache_key, |ns| {
-            let ret = ns.needs_render;
-            ns.needs_render = false;
-            ret
-        }).unwrap_or(false)
+        self.cache
+            .with_state(self.cache_key, |ns| {
+                let ret = ns.needs_render;
+                ns.needs_render = false;
+                ret
+            })
+            .unwrap_or(false)
     }
 
     pub fn render_needed(&self) {
@@ -332,7 +334,7 @@ impl Clone for LayoutNode {
             halign: self.halign,
             valign: self.valign,
             margin: self.margin,
-            table_cells: self.table_cells.clone(), 
+            table_cells: self.table_cells.clone(),
         }
     }
 }

+ 10 - 2
src/layout/arr.rs

@@ -26,7 +26,11 @@ fn do_fit<'l>(
 ) -> impl Iterator<Item = i32> {
     // first pass over children: collect sum total of minimum/desired sizes and/slack weights
     let policy_sum = policies.clone().reduce(SizePolicy::add).unwrap_or_default();
-    let (sum_min, sum_desired, sum_slack) = (policy_sum.minimum as i32, policy_sum.desired as i32, policy_sum.slack_weight as i32);
+    let (sum_min, sum_desired, sum_slack) = (
+        policy_sum.minimum as i32,
+        policy_sum.desired as i32,
+        policy_sum.slack_weight as i32,
+    );
 
     if total < sum_min {
         todo!("not enough space to distribute all children")
@@ -105,7 +109,11 @@ mod tests {
 
     #[test]
     fn distribute_3_even() {
-        let policies = vec![SizePolicy::expanding(1), SizePolicy::expanding(1), SizePolicy::expanding(1)];
+        let policies = vec![
+            SizePolicy::expanding(1),
+            SizePolicy::expanding(1),
+            SizePolicy::expanding(1),
+        ];
 
         assert_eq!(
             do_fit(3, policies.clone().into_iter()).collect::<Vec<_>>(),

+ 11 - 9
src/layout/arr/line.rs

@@ -1,5 +1,8 @@
-use crate::{math::{PixelPoint, PixelBox, PixelSize}, layout::{SizePolicy, LayoutNodeAccess, cache::NodeState}};
-use super::{ArrangementCalculator, do_fit};
+use super::{do_fit, ArrangementCalculator};
+use crate::{
+    layout::{cache::NodeState, LayoutNodeAccess, SizePolicy},
+    math::{PixelBox, PixelPoint, PixelSize},
+};
 use std::ops::Add;
 
 #[derive(Clone, Debug)]
@@ -53,13 +56,12 @@ impl ArrangementCalculator for LineArrangement {
 
     fn layout_step(&self, node: LayoutNodeAccess, inside: PixelBox) {
         // do the final children layouts
-        node.cache
-            .with_state(node.cache_key, |ns| {
-                if Some(inside) != ns.area {
-                    ns.area = Some(inside);
-                    ns.needs_render = true;
-                }
-            });
+        node.cache.with_state(node.cache_key, |ns| {
+            if Some(inside) != ns.area {
+                ns.area = Some(inside);
+                ns.needs_render = true;
+            }
+        });
 
         if node.child_len() == 0 {
             return;

+ 11 - 7
src/layout/arr/table.rs

@@ -1,5 +1,8 @@
-use crate::{math::{PixelPoint, PixelBox, PixelSize}, layout::{SizePolicy, LayoutNodeAccess, cache::NodeState}};
-use super::{ArrangementCalculator, do_fit};
+use super::{do_fit, ArrangementCalculator};
+use crate::{
+    layout::{cache::NodeState, LayoutNodeAccess, SizePolicy},
+    math::{PixelBox, PixelPoint, PixelSize},
+};
 use std::ops::Add;
 
 #[derive(Clone, Debug)]
@@ -7,12 +10,14 @@ pub struct TableArrangement;
 
 impl TableArrangement {
     fn max_coord(&self, node: &LayoutNodeAccess) -> Option<(usize, usize)> {
-        let Some(tc) = &node.table_cells else { return None };
+        let Some(tc) = &node.table_cells else {
+            return None;
+        };
         let mut max_row = None;
         let mut max_col = None;
         for cell in tc.iter() {
-            max_col = max_col.max(Some(cell.0.0));
-            max_row = max_row.max(Some(cell.0.1));
+            max_col = max_col.max(Some(cell.0 .0));
+            max_row = max_row.max(Some(cell.0 .1));
         }
         max_row.zip(max_col)
     }
@@ -28,6 +33,5 @@ impl ArrangementCalculator for TableArrangement {
         todo!()
     }
 
-    fn layout_step(&self, node: LayoutNodeAccess, inside: PixelBox) {
-    }
+    fn layout_step(&self, node: LayoutNodeAccess, inside: PixelBox) {}
 }

+ 20 - 22
src/layout/calc.rs

@@ -66,8 +66,8 @@ mod test {
     use kahlo::math::{PixelBox, PixelPoint, PixelRect, PixelSize};
 
     use crate::layout::{
-        cache::LayoutCache, ChildArrangement, LayoutNode, LayoutNodeAccess, LayoutNodeContainer,
-        NodeBehaviour, SizePolicy, dump_node_tree,
+        cache::LayoutCache, dump_node_tree, ChildArrangement, LayoutNode, LayoutNodeAccess,
+        LayoutNodeContainer, NodeBehaviour, SizePolicy,
     };
 
     use super::recalculate;
@@ -205,11 +205,19 @@ mod test {
             let area = PixelBox::from_origin_and_size(PixelPoint::new(1, 1), PixelSize::new(2, h));
             root.node.set_behaviour(NodeBehaviour::Fixed { area });
             recalculate(LayoutNodeAccess::new(&root));
-            
-            let child_areas = root.children.iter().map(|c| c.node.render_area().expect("layout did not give node a size")).collect::<Vec<_>>();
+
+            let child_areas = root
+                .children
+                .iter()
+                .map(|c| {
+                    c.node
+                        .render_area()
+                        .expect("layout did not give node a size")
+                })
+                .collect::<Vec<_>>();
 
             for i in 0..child_areas.len() {
-                for j in (i+1)..child_areas.len() {
+                for j in (i + 1)..child_areas.len() {
                     if child_areas[i].intersects(&child_areas[j]) {
                         panic!("layout children given overlapping areas!");
                     }
@@ -241,27 +249,17 @@ mod test {
         };
 
         let mut root = LayoutTree {
-            children: vec![
-                make_node(vec![
-                    make_node(vec![
-                        make_node(vec![
-                            make_node(vec![]),
-                            make_node(vec![]),
-                        ])
-                    ]),
-                    make_node(vec![
-                        make_node(vec![
-                            make_node(vec![]),
-                            make_node(vec![]),
-                        ])
-                    ])
-                ])
-            ],
+            children: vec![make_node(vec![
+                make_node(vec![make_node(vec![make_node(vec![]), make_node(vec![])])]),
+                make_node(vec![make_node(vec![make_node(vec![]), make_node(vec![])])]),
+            ])],
             node: LayoutNode::new(cache.clone()),
         };
 
         root.node.child_arrangement = ChildArrangement::Column;
-        root.node.set_behaviour(NodeBehaviour::Fixed { area: PixelBox::from_size(PixelSize::new(40, 40)) });
+        root.node.set_behaviour(NodeBehaviour::Fixed {
+            area: PixelBox::from_size(PixelSize::new(40, 40)),
+        });
         let mut dump = String::new();
         dump_node_tree(LayoutNodeAccess::new(&root), &mut dump);
         println!("before recalculate:\n{dump}");

+ 0 - 1
src/theme.rs

@@ -29,7 +29,6 @@ impl Theme {
             foreground: Colour::WHITE,
 
             // other colour in palette: #F2F3D9
-
             ui_font,
             ui_font_size: 16.0,
         }

+ 6 - 3
src/ui.rs

@@ -169,7 +169,10 @@ impl<UIC: UIComponent> winit::application::ApplicationHandler<()> for UI<UIC> {
                 self.state.window_states.remove(&window_id);
             }
             winit::event::WindowEvent::RedrawRequested => {
-                wsa.redraw(&UIHandle { eloop: event_loop, state: &mut self.state });
+                wsa.redraw(&UIHandle {
+                    eloop: event_loop,
+                    state: &mut self.state,
+                });
                 self.pump_events(event_loop);
             }
             winit::event::WindowEvent::CursorMoved { position, .. } => {
@@ -190,8 +193,8 @@ impl<UIC: UIComponent> winit::application::ApplicationHandler<()> for UI<UIC> {
             winit::event::WindowEvent::Resized(newsize) => {
                 wsa.notify_resize(PixelSize::new(newsize.width as i32, newsize.height as i32));
                 wsa.request_redraw();
-            },
-            _ => { },
+            }
+            _ => {}
         }
     }
 }

+ 12 - 4
src/widget/button.rs

@@ -1,10 +1,14 @@
-use kahlo::{prelude::*, math::PixelSideOffsets};
+use kahlo::{math::PixelSideOffsets, prelude::*};
 
 use crate::{
     component::Component,
     input::MouseButton,
-    layout::{LayoutNode, LayoutNodeAccess, LayoutNodeContainer, SizePolicy, HorizontalAlignment, VerticalAlignment},
-    ui::UIHandle, window::RenderFormat,
+    layout::{
+        HorizontalAlignment, LayoutNode, LayoutNodeAccess, LayoutNodeContainer, SizePolicy,
+        VerticalAlignment,
+    },
+    ui::UIHandle,
+    window::RenderFormat,
 };
 
 use super::{Label, Widget};
@@ -112,7 +116,11 @@ impl<C: Component> Widget<C> for Button<C> {
         };
         if self.layout.render_check() {
             target.fill_region(self.layout.render_area().unwrap(), colour);
-            target.rectangle(self.layout.render_area().unwrap(), theme.border_width, theme.border);
+            target.rectangle(
+                self.layout.render_area().unwrap(),
+                theme.border_width,
+                theme.border,
+            );
         }
         self.label.render(theme, target);
     }

+ 2 - 1
src/widget/frame.rs

@@ -4,7 +4,8 @@ use crate::{
     component::Component,
     layout::{LayoutNode, LayoutNodeAccess, LayoutNodeContainer, SizePolicy},
     theme::Theme,
-    ui::UIHandle, window::RenderFormat,
+    ui::UIHandle,
+    window::RenderFormat,
 };
 
 use super::Widget;

+ 10 - 7
src/widget/group.rs

@@ -1,10 +1,11 @@
 use crate::{
     component::Component,
     input::InputState,
-    layout::{LayoutNode, LayoutNodeAccess, LayoutNodeContainer, SizePolicy, ChildArrangement},
+    layout::{ChildArrangement, LayoutNode, LayoutNodeAccess, LayoutNodeContainer, SizePolicy},
     theme::Theme,
     ui::UIHandle,
-    widget::Widget, window::RenderFormat,
+    widget::Widget,
+    window::RenderFormat,
 };
 
 pub struct PlainGroup<C: Component> {
@@ -108,7 +109,7 @@ impl<C: Component> LayoutNodeContainer for FormGroup<C> {
         match ndx {
             0 => todo!(), // Some(LayoutNodeAccess::new(LabelContainer(self))),
             1 => todo!(),
-            _ => None
+            _ => None,
         }
     }
     fn layout_child_count(&self) -> usize {
@@ -123,10 +124,12 @@ impl<C: Component> Widget<C> for FormGroup<C> {
     fn layout_node_mut(&mut self) -> &mut LayoutNode {
         todo!()
     }
-    fn poll(&mut self, uih: &mut UIHandle, input_state: Option<&InputState>) -> Vec<<C as Component>::Msg> {
+    fn poll(
+        &mut self,
+        uih: &mut UIHandle,
+        input_state: Option<&InputState>,
+    ) -> Vec<<C as Component>::Msg> {
         todo!()
     }
-    fn render(&self, theme: &Theme, target: &mut kahlo::BitmapMut<RenderFormat>) {
-        
-    }
+    fn render(&self, theme: &Theme, target: &mut kahlo::BitmapMut<RenderFormat>) {}
 }

+ 20 - 7
src/widget/label.rs

@@ -1,12 +1,16 @@
 use std::cell::RefCell;
 
-use kahlo::{math::{PixelBox, PixelSideOffsets}, prelude::*};
+use kahlo::{
+    math::{PixelBox, PixelSideOffsets},
+    prelude::*,
+};
 
 use crate::{
     component::Component,
-    layout::{LayoutNode, LayoutNodeAccess, LeafLayoutNode, SizePolicy, HorizontalAlignment},
+    layout::{HorizontalAlignment, LayoutNode, LayoutNodeAccess, LeafLayoutNode, SizePolicy},
     theme::Theme,
-    ui::UIHandle, window::RenderFormat,
+    ui::UIHandle,
+    window::RenderFormat,
 };
 
 use super::Widget;
@@ -75,7 +79,7 @@ impl<C: Component> Widget<C> for Label<C> {
 
     fn render(&self, theme: &Theme, surface: &mut kahlo::BitmapMut<RenderFormat>) {
         if !self.lnode.render_check() {
-            return
+            return;
         }
         let rcon = self.rendered.borrow();
         let Some(rendered) = rcon.as_ref() else {
@@ -86,9 +90,18 @@ impl<C: Component> Widget<C> for Label<C> {
         // perform horizontal alignment
         let alignment_slack = (render_location.width() - rendered.size().width).max(0);
         let render_location = match self.lnode.halign() {
-            HorizontalAlignment::Left => render_location.inner_box(PixelSideOffsets::new(0, alignment_slack, 0, 0)),
-            HorizontalAlignment::Centre => render_location.inner_box(PixelSideOffsets::new(0, alignment_slack / 2, 0, alignment_slack / 2)),
-            HorizontalAlignment::Right => render_location.inner_box(PixelSideOffsets::new(0, 0, 0, alignment_slack)),
+            HorizontalAlignment::Left => {
+                render_location.inner_box(PixelSideOffsets::new(0, alignment_slack, 0, 0))
+            }
+            HorizontalAlignment::Centre => render_location.inner_box(PixelSideOffsets::new(
+                0,
+                alignment_slack / 2,
+                0,
+                alignment_slack / 2,
+            )),
+            HorizontalAlignment::Right => {
+                render_location.inner_box(PixelSideOffsets::new(0, 0, 0, alignment_slack))
+            }
         };
 
         surface.fill_region_masked(

+ 32 - 13
src/window.rs

@@ -57,13 +57,14 @@ impl<WC: WindowComponent> WindowState<WC> {
         let layout = LinearAccess::new(&self.root_node, self.wc.root_widget().layout_node());
 
         let mut bitmap = self.bitmap.borrow_mut();
-        if bitmap.as_ref().map(|v| v.size()) != Some(PixelSize::new(size.width as i32, size.height as i32)) {
+        if bitmap.as_ref().map(|v| v.size())
+            != Some(PixelSize::new(size.width as i32, size.height as i32))
+        {
             bitmap.take();
         }
 
-        let bitmap = bitmap.get_or_insert_with(|| {
-            kahlo::Bitmap::new(size.width as usize, size.height as usize)
-        });
+        let bitmap = bitmap
+            .get_or_insert_with(|| kahlo::Bitmap::new(size.width as usize, size.height as usize));
 
         let mut windowbuffer = kahlo::BitmapMut::<kahlo::formats::Bgr32>::new(
             unsafe {
@@ -83,32 +84,42 @@ impl<WC: WindowComponent> WindowState<WC> {
             crate::layout::dump_node_tree(LayoutNodeAccess::new(&layout), &mut pre_render_dump);
         }
 
-        self.wc.root_widget().render(uih.theme(), &mut bitmap.as_mut());
+        self.wc
+            .root_widget()
+            .render(uih.theme(), &mut bitmap.as_mut());
         windowbuffer.copy_from(
             bitmap,
             PixelBox::from_size(bitmap.size()),
-            PixelPoint::zero()
+            PixelPoint::zero(),
         );
         let after = std::time::Instant::now();
 
         // put the render time on the screen
         // we're going to do this the very dumb way for now
-        let render_time = format!("time: {:.03}ms", (after - before).as_micros() as f32 / 1000.0);
+        let render_time = format!(
+            "time: {:.03}ms",
+            (after - before).as_micros() as f32 / 1000.0
+        );
         let line = uih.theme().make_line(render_time.as_str()).render_line();
 
         windowbuffer.fill_region_masked(
             &line,
             PixelBox::from_size(line.size()),
-            PixelPoint::new(size.width as i32 - line.size().width, size.height as i32 - line.size().height),
+            PixelPoint::new(
+                size.width as i32 - line.size().width,
+                size.height as i32 - line.size().height,
+            ),
             uih.theme().foreground,
-            kahlo::colour::BlendMode::Simple
+            kahlo::colour::BlendMode::Simple,
         );
 
         // now put the pre-render layout dump on the window
         // again, we're doing this the dumb way
         let mut offset = 0;
         for text in pre_render_dump.split("\n") {
-            if text.len() == 0 { continue }
+            if text.len() == 0 {
+                continue;
+            }
             let line = uih.theme().make_line(text).render_line();
 
             windowbuffer.fill_region_masked(
@@ -116,7 +127,7 @@ impl<WC: WindowComponent> WindowState<WC> {
                 PixelBox::from_size(line.size()),
                 PixelPoint::new(0, offset),
                 uih.theme().foreground,
-                kahlo::colour::BlendMode::Simple
+                kahlo::colour::BlendMode::Simple,
             );
 
             offset += line.height() as i32 + 1;
@@ -154,8 +165,16 @@ impl<WC: WindowComponent> WindowStateAccess for RefCell<WindowState<WC>> {
     fn notify_resize(&self, new_size: PixelSize) {
         if Some(new_size) != self.borrow().bitmap.borrow().as_ref().map(|v| v.size()) {
             self.borrow_mut().bitmap.take();
-            self.borrow_mut().wc.root_widget().layout_node().relayout_tree();
-            self.borrow_mut().wc.root_widget().layout_node().render_needed();
+            self.borrow_mut()
+                .wc
+                .root_widget()
+                .layout_node()
+                .relayout_tree();
+            self.borrow_mut()
+                .wc
+                .root_widget()
+                .layout_node()
+                .render_needed();
         }
     }
     fn push_event(&self, we: WindowEvent) {