keystroke_label.rs

  1use crate::{
  2    elements::*,
  3    fonts::TextStyle,
  4    geometry::{rect::RectF, vector::Vector2F},
  5    Action, Element, SizeConstraint,
  6};
  7use serde_json::json;
  8
  9use super::ContainerStyle;
 10
 11pub struct KeystrokeLabel {
 12    action: Box<dyn Action>,
 13    container_style: ContainerStyle,
 14    text_style: TextStyle,
 15    window_id: usize,
 16    view_id: usize,
 17}
 18
 19impl KeystrokeLabel {
 20    pub fn new(
 21        window_id: usize,
 22        view_id: usize,
 23        action: Box<dyn Action>,
 24        container_style: ContainerStyle,
 25        text_style: TextStyle,
 26    ) -> Self {
 27        Self {
 28            window_id,
 29            view_id,
 30            action,
 31            container_style,
 32            text_style,
 33        }
 34    }
 35}
 36
 37impl<V: View> Drawable<V> for KeystrokeLabel {
 38    type LayoutState = Element<V>;
 39    type PaintState = ();
 40
 41    fn layout(
 42        &mut self,
 43        constraint: SizeConstraint,
 44        view: &mut V,
 45        cx: &mut ViewContext<V>,
 46    ) -> (Vector2F, Element<V>) {
 47        let mut element = if let Some(keystrokes) =
 48            cx.keystrokes_for_action(self.window_id, self.view_id, self.action.as_ref())
 49        {
 50            Flex::row()
 51                .with_children(keystrokes.iter().map(|keystroke| {
 52                    Label::new(keystroke.to_string(), self.text_style.clone())
 53                        .contained()
 54                        .with_style(self.container_style)
 55                        .boxed()
 56                }))
 57                .boxed()
 58        } else {
 59            Empty::new().collapsed().boxed()
 60        };
 61
 62        let size = element.layout(constraint, view, cx);
 63        (size, element)
 64    }
 65
 66    fn paint(
 67        &mut self,
 68        scene: &mut SceneBuilder,
 69        bounds: RectF,
 70        visible_bounds: RectF,
 71        element: &mut Element<V>,
 72        view: &mut V,
 73        cx: &mut ViewContext<V>,
 74    ) {
 75        element.paint(scene, bounds.origin(), visible_bounds, view, cx);
 76    }
 77
 78    fn rect_for_text_range(
 79        &self,
 80        _: Range<usize>,
 81        _: RectF,
 82        _: RectF,
 83        _: &Self::LayoutState,
 84        _: &Self::PaintState,
 85        _: &V,
 86        _: &ViewContext<V>,
 87    ) -> Option<RectF> {
 88        None
 89    }
 90
 91    fn debug(
 92        &self,
 93        _: RectF,
 94        element: &Element<V>,
 95        _: &(),
 96        view: &V,
 97        cx: &ViewContext<V>,
 98    ) -> serde_json::Value {
 99        json!({
100            "type": "KeystrokeLabel",
101            "action": self.action.name(),
102            "child": element.debug(view, cx)
103        })
104    }
105}