Tooltips, minor changes

This commit is contained in:
Aleksander
2025-10-18 22:38:39 +02:00
parent 28047d218f
commit bf1d02ed00
13 changed files with 251 additions and 131 deletions

View File

@@ -15,7 +15,10 @@
height="~side_button_size" height="~side_button_size"
color="#44444400" color="#44444400"
hover_color="#333333ff" hover_color="#333333ff"
hover_border_color="#555555ff"> hover_border_color="#555555ff"
tooltip="${tooltip}"
tooltip_side="${tooltip_side}"
>
<sprite src="${src}" width="~side_sprite_size" height="~side_sprite_size" /> <sprite src="${src}" width="~side_sprite_size" height="~side_sprite_size" />
</Button> </Button>
</template> </template>
@@ -43,13 +46,13 @@
align_items="center" align_items="center"
gap="4" gap="4"
> >
<SideButton id="btn_side_home" src="dashboard/wayvr_dashboard_mono.svg" /> <SideButton id="btn_side_home" src="dashboard/wayvr_dashboard_mono.svg" tooltip="HOME_SCREEN" tooltip_side="right" />
<SideButton id="btn_side_apps" src="dashboard/apps.svg" /> <SideButton id="btn_side_apps" src="dashboard/apps.svg" tooltip="APPLICATIONS" tooltip_side="right" />
<SideButton id="btn_side_games" src="dashboard/games.svg" /> <SideButton id="btn_side_games" src="dashboard/games.svg" tooltip="GAMES" tooltip_side="right" />
<SideButton id="btn_side_monado" src="dashboard/monado.svg" /> <SideButton id="btn_side_monado" src="dashboard/monado.svg" tooltip="MONADO_RUNTIME" tooltip_side="right" />
<SideButton id="btn_side_processes" src="dashboard/window.svg" /> <SideButton id="btn_side_processes" src="dashboard/window.svg" tooltip="PROCESSES" tooltip_side="right" />
<rectangle height="2" color="#FFFFFF33" width="~side_sprite_size" /> <rectangle height="2" color="#FFFFFF33" width="~side_sprite_size" />
<SideButton id="btn_side_settings" src="dashboard/settings.svg" /> <SideButton id="btn_side_settings" src="dashboard/settings.svg" tooltip="SETTINGS" tooltip_side="right" />
</rectangle> </rectangle>
</div> </div>
<!-- REST --> <!-- REST -->

View File

@@ -14,8 +14,8 @@ use wgui::{
}; };
use crate::tab::{ use crate::tab::{
apps::TabApps, games::TabGames, home::TabHome, monado::TabMonado, processes::TabProcesses, settings::TabSettings, Tab, TabParams, TabType, apps::TabApps, games::TabGames, home::TabHome, monado::TabMonado, processes::TabProcesses,
Tab, TabParams, TabType, settings::TabSettings,
}; };
mod assets; mod assets;

View File

@@ -12,9 +12,9 @@
<label id="label_current_option" text="Click any of these buttons" size="20" weight="bold" /> <label id="label_current_option" text="Click any of these buttons" size="20" weight="bold" />
<Button id="button_popup" text="Show pop-up" width="200" height="32" color="#777777" /> <Button id="button_popup" text="Show pop-up" width="200" height="32" color="#777777" />
<div gap="4"> <div gap="4">
<Button id="button_red" text="Red button" width="150" height="32" color="#FF0000" /> <Button id="button_red" text="Red button" width="150" height="32" color="#FF0000" tooltip="I'm at the top" tooltip_side="top" />
<Button id="button_aqua" text="Aqua button" width="150" height="32" color="#00FFFF" /> <Button id="button_aqua" text="Aqua button" width="150" height="32" color="#00FFFF" tooltip="I'm at the bottom" tooltip_side="bottom" />
<Button id="button_yellow" text="Yellow button" width="150" height="32" color="#FFFF00" /> <Button id="button_yellow" text="Yellow button" width="150" height="32" color="#FFFF00" tooltip="TESTBED.HELLO_WORLD" tooltip_side="right" />
</div> </div>
<Button id="button_click_me" text="Click me" width="128" height="24" color="#FFFFFF" /> <Button id="button_click_me" text="Click me" width="128" height="24" color="#FFFFFF" />

View File

@@ -1,26 +1,26 @@
use glam::{vec2, Vec2}; use glam::{Vec2, vec2};
use std::sync::Arc; use std::sync::Arc;
use testbed::{testbed_any::TestbedAny, Testbed}; use testbed::{Testbed, testbed_any::TestbedAny};
use timestep::Timestep; use timestep::Timestep;
use tracing_subscriber::EnvFilter;
use tracing_subscriber::filter::LevelFilter; use tracing_subscriber::filter::LevelFilter;
use tracing_subscriber::layer::SubscriberExt; use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;
use vulkan::init_window; use vulkan::init_window;
use vulkano::{ use vulkano::{
Validated, VulkanError,
command_buffer::CommandBufferUsage, command_buffer::CommandBufferUsage,
format::Format, format::Format,
image::{view::ImageView, ImageUsage}, image::{ImageUsage, view::ImageView},
swapchain::{ swapchain::{
acquire_next_image, CompositeAlpha, PresentMode, Surface, SurfaceInfo, Swapchain, CompositeAlpha, PresentMode, Surface, SurfaceInfo, Swapchain, SwapchainCreateInfo,
SwapchainCreateInfo, SwapchainPresentInfo, SwapchainPresentInfo, acquire_next_image,
}, },
sync::GpuFuture, sync::GpuFuture,
Validated, VulkanError,
}; };
use wgui::{ use wgui::{
event::{MouseButtonIndex, MouseDownEvent, MouseMotionEvent, MouseUpEvent, MouseWheelEvent}, event::{MouseButtonIndex, MouseDownEvent, MouseMotionEvent, MouseUpEvent, MouseWheelEvent},
gfx::{cmd::WGfxClearMode, WGfx}, gfx::{WGfx, cmd::WGfxClearMode},
renderer_vk::{self}, renderer_vk::{self},
}; };
use winit::{ use winit::{
@@ -32,7 +32,7 @@ use winit::{
use crate::{ use crate::{
rate_limiter::RateLimiter, rate_limiter::RateLimiter,
testbed::{ testbed::{
testbed_dashboard::TestbedDashboard, testbed_generic::TestbedGeneric, TestbedUpdateParams, TestbedUpdateParams, testbed_dashboard::TestbedDashboard, testbed_generic::TestbedGeneric,
}, },
}; };

View File

@@ -190,6 +190,12 @@ _Translated by key_
`hover_border_color`: #FFAABB | #FFAABBCC `hover_border_color`: #FFAABB | #FFAABBCC
`tooltip`: **string**
_Tooltip text on hover, translated by key_
`tooltip_side`: "top" | "bottom" | "left" | "right" (default: top)
#### Info #### Info
Child widgets are supported and can be added directly in XML. Child widgets are supported and can be added directly in XML.

View File

@@ -98,14 +98,12 @@ impl Animation {
return; // failed return; // failed
}; };
let widget_node = *state.nodes.get(self.target_widget).unwrap();
let mut widget_state = widget.state(); let mut widget_state = widget.state();
let (data, obj) = widget_state.get_data_obj_mut(); let (data, obj) = widget_state.get_data_obj_mut();
let data = &mut CallbackData { let data = &mut CallbackData {
widget_id: self.target_widget, widget_id: self.target_widget,
widget_boundary: state.get_widget_boundary(widget_node), widget_boundary: state.get_widget_boundary(self.target_widget),
obj, obj,
data, data,
pos, pos,

View File

@@ -1,19 +1,19 @@
use crate::{ use crate::{
animation::{Animation, AnimationEasing}, animation::{Animation, AnimationEasing},
components::{tooltip::ComponentTooltip, Component, ComponentBase, ComponentTrait, InitData}, components::{self, Component, ComponentBase, ComponentTrait, InitData, tooltip::ComponentTooltip},
drawing::{self, Boundary, Color}, drawing::{self, Boundary, Color},
event::{CallbackDataCommon, EventListenerCollection, EventListenerID, EventListenerKind}, event::{CallbackDataCommon, EventListenerCollection, EventListenerID, EventListenerKind},
i18n::Translation, i18n::Translation,
layout::{WidgetID, WidgetPair}, layout::{LayoutTask, WidgetID, WidgetPair},
renderer_vk::{ renderer_vk::{
text::{FontWeight, TextStyle}, text::{FontWeight, TextStyle},
util::centered_matrix, util::centered_matrix,
}, },
widget::{ widget::{
ConstructEssentials, EventResult, WidgetData,
label::{WidgetLabel, WidgetLabelParams}, label::{WidgetLabel, WidgetLabelParams},
rectangle::{WidgetRectangle, WidgetRectangleParams}, rectangle::{WidgetRectangle, WidgetRectangleParams},
util::WLength, util::WLength,
ConstructEssentials, EventResult, WidgetData,
}, },
}; };
use glam::{Mat4, Vec3}; use glam::{Mat4, Vec3};
@@ -30,6 +30,7 @@ pub struct Params {
pub round: WLength, pub round: WLength,
pub style: taffy::Style, pub style: taffy::Style,
pub text_style: TextStyle, pub text_style: TextStyle,
pub tooltip: Option<components::tooltip::TooltipInfo>,
} }
impl Default for Params { impl Default for Params {
@@ -44,6 +45,7 @@ impl Default for Params {
round: WLength::Units(4.0), round: WLength::Units(4.0),
style: Default::default(), style: Default::default(),
text_style: TextStyle::default(), text_style: TextStyle::default(),
tooltip: None,
} }
} }
} }
@@ -55,8 +57,7 @@ struct State {
hovered: bool, hovered: bool,
down: bool, down: bool,
on_click: Option<ButtonClickCallback>, on_click: Option<ButtonClickCallback>,
active_tooltip: Option<Rc<ComponentTooltip>>,
tooltip: Option<ComponentTooltip>,
} }
struct Data { struct Data {
@@ -145,6 +146,7 @@ fn register_event_mouse_enter(
data: Rc<Data>, data: Rc<Data>,
state: Rc<RefCell<State>>, state: Rc<RefCell<State>>,
listeners: &mut EventListenerCollection, listeners: &mut EventListenerCollection,
info: Option<components::tooltip::TooltipInfo>,
) -> EventListenerID { ) -> EventListenerID {
listeners.register( listeners.register(
EventListenerKind::MouseEnter, EventListenerKind::MouseEnter,
@@ -157,26 +159,20 @@ fn register_event_mouse_enter(
event_data.widget_id, event_data.widget_id,
true, true,
)); ));
let mut state = state.borrow_mut();
// todo if let Some(info) = info.clone() {
/*common.alterables.tasks.push(LayoutTask::ModifyLayoutState({ common.alterables.tasks.push(LayoutTask::ModifyLayoutState({
let parent = data.id_rect.clone(); let widget_to_watch = data.id_rect;
let state = state.clone();
Box::new(move |m| { Box::new(move |m| {
components::tooltip::construct( state.borrow_mut().active_tooltip =
&mut ConstructEssentials { Some(components::tooltip::show(m.layout, widget_to_watch, info.clone())?);
layout: m.layout, Ok(())
listeners: &listeners,
parent,
},
components::tooltip::Params {
text: Translation::from_raw_text("this is a tooltip"),
},
);
}) })
}));*/ }));
}
state.hovered = true; state.borrow_mut().hovered = true;
Ok(EventResult::Pass) Ok(EventResult::Pass)
}), }),
) )
@@ -198,7 +194,7 @@ fn register_event_mouse_leave(
false, false,
)); ));
let mut state = state.borrow_mut(); let mut state = state.borrow_mut();
state.tooltip = None; state.active_tooltip = None;
state.hovered = false; state.hovered = false;
Ok(EventResult::Pass) Ok(EventResult::Pass)
}), }),
@@ -220,7 +216,7 @@ fn register_event_mouse_press(
rect, rect,
event_data.widget_data, event_data.widget_data,
&data, &data,
common.state.get_widget_boundary(event_data.node_id), common.state.get_node_boundary(event_data.node_id),
1.0, 1.0,
true, true,
); );
@@ -251,7 +247,7 @@ fn register_event_mouse_release(
rect, rect,
event_data.widget_data, event_data.widget_data,
&data, &data,
common.state.get_widget_boundary(event_data.node_id), common.state.get_node_boundary(event_data.node_id),
1.0, 1.0,
false, false,
); );
@@ -366,14 +362,14 @@ pub fn construct(ess: &mut ConstructEssentials, params: Params) -> anyhow::Resul
down: false, down: false,
hovered: false, hovered: false,
on_click: None, on_click: None,
tooltip: None, active_tooltip: None,
})); }));
let base = ComponentBase { let base = ComponentBase {
lhandles: { lhandles: {
let mut widget = ess.layout.state.widgets.get(id_rect).unwrap().state(); let mut widget = ess.layout.state.widgets.get(id_rect).unwrap().state();
vec![ vec![
register_event_mouse_enter(data.clone(), state.clone(), &mut widget.event_listeners), register_event_mouse_enter(data.clone(), state.clone(), &mut widget.event_listeners, params.tooltip),
register_event_mouse_leave(data.clone(), state.clone(), &mut widget.event_listeners), register_event_mouse_leave(data.clone(), state.clone(), &mut widget.event_listeners),
register_event_mouse_press(data.clone(), state.clone(), &mut widget.event_listeners), register_event_mouse_press(data.clone(), state.clone(), &mut widget.event_listeners),
register_event_mouse_release(data.clone(), state.clone(), &mut widget.event_listeners), register_event_mouse_release(data.clone(), state.clone(), &mut widget.event_listeners),

View File

@@ -1,29 +1,50 @@
use glam::{Mat4, Vec3};
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
use taffy::prelude::length; use taffy::prelude::length;
use crate::{ use crate::{
components::{Component, ComponentBase, ComponentTrait, InitData}, components::{self, Component, ComponentBase, ComponentTrait, InitData},
drawing::Color, drawing::Color,
event::{EventListenerCollection, EventListenerKind},
i18n::Translation, i18n::Translation,
layout::{LayoutTasks, WidgetID, WidgetPair}, layout::{self, LayoutTask, LayoutTasks, WidgetID, WidgetPair},
renderer_vk::text::{FontWeight, TextStyle}, renderer_vk::text::{FontWeight, TextStyle},
widget::{ widget::{
ConstructEssentials,
div::WidgetDiv,
label::{WidgetLabel, WidgetLabelParams}, label::{WidgetLabel, WidgetLabelParams},
rectangle::{WidgetRectangle, WidgetRectangleParams}, rectangle::{WidgetRectangle, WidgetRectangleParams},
util::WLength, util::WLength,
ConstructEssentials, EventResult,
}, },
}; };
pub struct Params { #[derive(Clone, Default)]
pub enum TooltipSide {
Left,
Right,
Top,
#[default]
Bottom,
}
#[derive(Clone)]
pub struct TooltipInfo {
pub text: Translation, pub text: Translation,
pub side: TooltipSide,
}
pub struct Params {
pub info: TooltipInfo,
pub widget_to_watch: WidgetID,
} }
impl Default for Params { impl Default for Params {
fn default() -> Self { fn default() -> Self {
Self { Self {
info: TooltipInfo {
text: Translation::from_raw_text(""), text: Translation::from_raw_text(""),
side: TooltipSide::Bottom,
},
widget_to_watch: WidgetID::default(),
} }
} }
} }
@@ -32,13 +53,13 @@ struct State {}
#[allow(clippy::struct_field_names)] #[allow(clippy::struct_field_names)]
struct Data { struct Data {
id_container: WidgetID, // Rectangle id_root: WidgetID, // Rectangle
id_label: WidgetID, // Label, parent of container
} }
pub struct ComponentTooltip { pub struct ComponentTooltip {
base: ComponentBase, base: ComponentBase,
data: Rc<Data>, data: Rc<Data>,
#[allow(dead_code)]
state: Rc<RefCell<State>>, state: Rc<RefCell<State>>,
tasks: LayoutTasks, tasks: LayoutTasks,
} }
@@ -53,61 +74,110 @@ impl ComponentTrait for ComponentTooltip {
impl ComponentTooltip {} impl ComponentTooltip {}
fn register_event_mouse_enter(listeners: &mut EventListenerCollection) -> crate::event::EventListenerID { impl Drop for ComponentTooltip {
listeners.register( fn drop(&mut self) {
EventListenerKind::MouseEnter, self.tasks.push(LayoutTask::RemoveWidget(self.data.id_root));
Box::new(move |common, _event_data, (), ()| { }
common.alterables.trigger_haptics();
Ok(EventResult::Pass)
}),
)
}
fn register_event_mouse_leave(listeners: &mut EventListenerCollection) -> crate::event::EventListenerID {
listeners.register(
EventListenerKind::MouseEnter,
Box::new(move |common, _event_data, (), ()| {
common.alterables.trigger_haptics();
Ok(EventResult::Pass)
}),
)
} }
#[allow(clippy::too_many_lines)]
pub fn construct(ess: &mut ConstructEssentials, params: Params) -> anyhow::Result<(WidgetPair, Rc<ComponentTooltip>)> { pub fn construct(ess: &mut ConstructEssentials, params: Params) -> anyhow::Result<(WidgetPair, Rc<ComponentTooltip>)> {
let style = taffy::Style { let absolute_boundary = {
align_items: Some(taffy::AlignItems::Center), let widget_to_watch = ess
justify_content: Some(taffy::JustifyContent::Center), .layout
gap: length(4.0), .state
padding: taffy::Rect { .widgets
left: length(8.0), .get(params.widget_to_watch)
right: length(8.0), .ok_or_else(|| anyhow::anyhow!("widget_to_watch is invalid"))?;
top: length(4.0), let widget_to_watch_state = widget_to_watch.state();
bottom: length(4.0), widget_to_watch_state.data.cached_absolute_boundary
}, };
..Default::default()
let spacing = 8.0;
let transform = Mat4::from_translation(Vec3::new(-0.5, 0.0, 0.0));
let (pin_left, pin_top, pin_align_items, pin_justify_content) = match params.info.side {
TooltipSide::Left => (
absolute_boundary.left() - spacing,
absolute_boundary.top() + absolute_boundary.size.y / 2.0,
taffy::AlignItems::Center,
taffy::JustifyContent::End,
),
TooltipSide::Right => (
absolute_boundary.left() + absolute_boundary.size.x + spacing,
absolute_boundary.top() + absolute_boundary.size.y / 2.0,
taffy::AlignItems::Center,
taffy::JustifyContent::Start,
),
TooltipSide::Top => (
absolute_boundary.left() + absolute_boundary.size.x / 2.0,
absolute_boundary.top() - spacing,
taffy::AlignItems::End,
taffy::JustifyContent::Center,
),
TooltipSide::Bottom => (
absolute_boundary.left() + absolute_boundary.size.x / 2.0,
absolute_boundary.top() + absolute_boundary.size.y + spacing,
taffy::AlignItems::Baseline,
taffy::JustifyContent::Center,
),
}; };
let globals = ess.layout.state.globals.clone(); let globals = ess.layout.state.globals.clone();
let (root, _) = ess.layout.add_child( let (div, _) = ess.layout.add_child(
ess.parent, ess.parent,
WidgetRectangle::create(WidgetRectangleParams { WidgetDiv::create(),
color: Color::new(1.0, 1.0, 1.0, 0.0), taffy::Style {
border_color: Color::new(1.0, 1.0, 1.0, 0.0), align_items: Some(pin_align_items),
round: WLength::Units(5.0), justify_content: Some(pin_justify_content),
position: taffy::Position::Absolute,
margin: taffy::Rect {
left: length(pin_left),
top: length(pin_top),
bottom: length(0.0),
right: length(0.0),
},
/* important, to make it centered! */
size: taffy::Size {
width: length(0.0),
height: length(0.0),
},
..Default::default() ..Default::default()
}), },
style,
)?; )?;
let id_container = root.id; div.widget.state().data.transform = transform;
let (label, _node_label) = ess.layout.add_child( let (rect, _) = ess.layout.add_child(
id_container, div.id,
WidgetRectangle::create(WidgetRectangleParams {
color: Color::new(0.1, 0.1, 0.1, 0.8),
border_color: Color::new(0.3, 0.3, 0.3, 1.0),
border: 2.0,
round: WLength::Percent(1.0),
..Default::default()
}),
taffy::Style {
position: taffy::Position::Relative,
gap: length(4.0),
padding: taffy::Rect {
left: length(16.0),
right: length(16.0),
top: length(8.0),
bottom: length(8.0),
},
..Default::default()
},
)?;
let (_label, _) = ess.layout.add_child(
rect.id,
WidgetLabel::create( WidgetLabel::create(
&mut globals.get(), &mut globals.get(),
WidgetLabelParams { WidgetLabelParams {
content: params.text, content: params.info.text,
style: TextStyle { style: TextStyle {
weight: Some(FontWeight::Bold), weight: Some(FontWeight::Bold),
..Default::default() ..Default::default()
@@ -117,22 +187,11 @@ pub fn construct(ess: &mut ConstructEssentials, params: Params) -> anyhow::Resul
Default::default(), Default::default(),
)?; )?;
let data = Rc::new(Data { let data = Rc::new(Data { id_root: div.id });
id_container,
id_label: label.id,
});
let state = Rc::new(RefCell::new(State {})); let state = Rc::new(RefCell::new(State {}));
let base = ComponentBase { let base = ComponentBase::default();
lhandles: {
let mut widget = ess.layout.state.widgets.get(id_container).unwrap().state();
vec![
register_event_mouse_enter(&mut widget.event_listeners),
register_event_mouse_leave(&mut widget.event_listeners),
]
},
};
let tooltip = Rc::new(ComponentTooltip { let tooltip = Rc::new(ComponentTooltip {
base, base,
@@ -142,5 +201,18 @@ pub fn construct(ess: &mut ConstructEssentials, params: Params) -> anyhow::Resul
}); });
ess.layout.defer_component_init(Component(tooltip.clone())); ess.layout.defer_component_init(Component(tooltip.clone()));
Ok((root, tooltip)) Ok((div, tooltip))
}
pub fn show(
layout: &mut layout::Layout,
widget_to_watch: WidgetID,
info: TooltipInfo,
) -> anyhow::Result<Rc<ComponentTooltip>> {
let parent = layout.tree_root_widget;
let (_, tooltip) = components::tooltip::construct(
&mut ConstructEssentials { layout, parent },
components::tooltip::Params { info, widget_to_watch },
)?;
Ok(tooltip)
} }

View File

@@ -5,7 +5,7 @@ use std::{
}; };
use glam::Vec2; use glam::Vec2;
use slotmap::{new_key_type, DenseSlotMap}; use slotmap::{DenseSlotMap, new_key_type};
use crate::{ use crate::{
animation::{self, Animation}, animation::{self, Animation},
@@ -92,6 +92,7 @@ impl Event {
} }
} }
// alterables which will be dispatched in the next loop iteration phase
#[derive(Default)] #[derive(Default)]
pub struct EventAlterables { pub struct EventAlterables {
pub dirty_nodes: Vec<taffy::NodeId>, pub dirty_nodes: Vec<taffy::NodeId>,
@@ -105,6 +106,7 @@ pub struct EventAlterables {
pub trigger_haptics: bool, pub trigger_haptics: bool,
} }
// helper functions
impl EventAlterables { impl EventAlterables {
pub const fn mark_redraw(&mut self) { pub const fn mark_redraw(&mut self) {
self.needs_redraw = true; self.needs_redraw = true;

View File

@@ -5,7 +5,7 @@ use crate::assets::AssetProvider;
// a string which optionally has translation key in it // a string which optionally has translation key in it
// it will hopefully support dynamic language changing soon // it will hopefully support dynamic language changing soon
// for now it's just a simple string container // for now it's just a simple string container
#[derive(Debug, Default)] #[derive(Debug, Default, Clone)]
pub struct Translation { pub struct Translation {
pub text: Rc<str>, pub text: Rc<str>,
pub translated: bool, // if true, `text` is a translation key pub translated: bool, // if true, `text` is a translation key

View File

@@ -8,14 +8,14 @@ use std::{
use crate::{ use crate::{
animation::Animations, animation::Animations,
components::{Component, InitData}, components::{Component, InitData},
drawing::{self, push_scissor_stack, push_transform_stack, Boundary, ANSI_BOLD_CODE, ANSI_RESET_CODE}, drawing::{self, ANSI_BOLD_CODE, ANSI_RESET_CODE, Boundary, push_scissor_stack, push_transform_stack},
event::{self, CallbackDataCommon, EventAlterables}, event::{self, CallbackDataCommon, EventAlterables},
globals::WguiGlobals, globals::WguiGlobals,
widget::{self, div::WidgetDiv, EventParams, EventResult, WidgetObj, WidgetState}, widget::{self, EventParams, EventResult, WidgetObj, WidgetState, div::WidgetDiv},
}; };
use glam::{vec2, Vec2}; use glam::{Vec2, vec2};
use slotmap::{new_key_type, HopSlotMap, SecondaryMap}; use slotmap::{HopSlotMap, SecondaryMap, new_key_type};
use taffy::{NodeId, TaffyTree, TraversePartialTree}; use taffy::{NodeId, TaffyTree, TraversePartialTree};
new_key_type! { new_key_type! {
@@ -112,13 +112,13 @@ pub struct LayoutState {
pub struct ModifyLayoutStateData<'a> { pub struct ModifyLayoutStateData<'a> {
pub layout: &'a mut Layout, pub layout: &'a mut Layout,
// don't uncomment this, todo!
// pub listeners: &'a mut EventListenerCollection,
} }
pub type ModifyLayoutStateFunc = Box<dyn Fn(ModifyLayoutStateData) -> anyhow::Result<()>>;
pub enum LayoutTask { pub enum LayoutTask {
RemoveWidget(WidgetID), RemoveWidget(WidgetID),
ModifyLayoutState(Box<dyn Fn(ModifyLayoutStateData)>), ModifyLayoutState(ModifyLayoutStateFunc),
} }
#[derive(Clone)] #[derive(Clone)]
@@ -396,6 +396,8 @@ impl Layout {
// see drawing.rs draw_widget too // see drawing.rs draw_widget too
push_transform_stack(&mut alterables.transform_stack, l, scroll_shift, &widget); push_transform_stack(&mut alterables.transform_stack, l, scroll_shift, &widget);
widget.data.cached_absolute_boundary = drawing::Boundary::construct_absolute(&alterables.transform_stack);
let scissor_pushed = push_scissor_stack( let scissor_pushed = push_scissor_stack(
&mut alterables.transform_stack, &mut alterables.transform_stack,
&mut alterables.scissor_stack, &mut alterables.scissor_stack,
@@ -589,7 +591,7 @@ impl Layout {
Ok(()) Ok(())
} }
fn process_tasks(&mut self) { pub fn process_tasks(&mut self) -> anyhow::Result<()> {
let tasks = self.tasks.clone(); let tasks = self.tasks.clone();
let mut tasks = tasks.0.borrow_mut(); let mut tasks = tasks.0.borrow_mut();
while let Some(task) = tasks.pop_front() { while let Some(task) = tasks.pop_front() {
@@ -597,17 +599,21 @@ impl Layout {
LayoutTask::RemoveWidget(widget_id) => { LayoutTask::RemoveWidget(widget_id) => {
self.remove_widget(widget_id); self.remove_widget(widget_id);
} }
LayoutTask::ModifyLayoutState(_fn) => todo!(), LayoutTask::ModifyLayoutState(callback) => {
(*callback)(ModifyLayoutStateData { layout: self })?;
} }
} }
} }
Ok(())
}
pub fn process_alterables(&mut self, alterables: EventAlterables) -> anyhow::Result<()> { pub fn process_alterables(&mut self, alterables: EventAlterables) -> anyhow::Result<()> {
for task in alterables.tasks { for task in alterables.tasks {
self.tasks.push(task); self.tasks.push(task);
} }
self.process_tasks(); self.process_tasks()?;
for node in alterables.dirty_nodes { for node in alterables.dirty_nodes {
self.state.tree.mark_dirty(node)?; self.state.tree.mark_dirty(node)?;
@@ -698,7 +704,7 @@ impl Layout {
} }
impl LayoutState { impl LayoutState {
pub fn get_widget_boundary(&self, id: NodeId) -> Boundary { pub fn get_node_boundary(&self, id: NodeId) -> Boundary {
let Ok(layout) = self.tree.layout(id) else { let Ok(layout) = self.tree.layout(id) else {
return Boundary::default(); return Boundary::default();
}; };
@@ -709,11 +715,27 @@ impl LayoutState {
} }
} }
pub fn get_widget_size(&self, id: NodeId) -> Vec2 { pub fn get_node_size(&self, id: NodeId) -> Vec2 {
let Ok(layout) = self.tree.layout(id) else { let Ok(layout) = self.tree.layout(id) else {
return Vec2::ZERO; return Vec2::ZERO;
}; };
Vec2::new(layout.size.width, layout.size.height) Vec2::new(layout.size.width, layout.size.height)
} }
pub fn get_widget_boundary(&self, id: WidgetID) -> Boundary {
let Some(node_id) = self.nodes.get(id) else {
return Boundary::default();
};
self.get_node_boundary(*node_id)
}
pub fn get_widget_size(&self, id: WidgetID) -> Vec2 {
let Some(node_id) = self.nodes.get(id) else {
return Vec2::ZERO;
};
self.get_node_size(*node_id)
}
} }

View File

@@ -1,10 +1,10 @@
use crate::{ use crate::{
components::{Component, button}, components::{self, Component, button, tooltip},
drawing::Color, drawing::Color,
i18n::Translation, i18n::Translation,
layout::WidgetID, layout::WidgetID,
parser::{ parser::{
AttribPair, ParserContext, ParserFile, parse_check_f32, parse_children, process_component, AttribPair, ParserContext, ParserFile, parse_check_f32, parse_children, print_invalid_attrib, process_component,
style::{parse_color_opt, parse_round, parse_style, parse_text_style}, style::{parse_color_opt, parse_round, parse_style, parse_text_style},
}, },
widget::util::WLength, widget::util::WLength,
@@ -23,6 +23,8 @@ pub fn parse_component_button<'a>(
let mut hover_color: Option<Color> = None; let mut hover_color: Option<Color> = None;
let mut hover_border_color: Option<Color> = None; let mut hover_border_color: Option<Color> = None;
let mut round = WLength::Units(4.0); let mut round = WLength::Units(4.0);
let mut tooltip: Option<String> = None;
let mut tooltip_side: Option<tooltip::TooltipSide> = None;
let mut translation: Option<Translation> = None; let mut translation: Option<Translation> = None;
@@ -56,6 +58,19 @@ pub fn parse_component_button<'a>(
"hover_border_color" => { "hover_border_color" => {
parse_color_opt(value, &mut hover_border_color); parse_color_opt(value, &mut hover_border_color);
} }
"tooltip" => tooltip = Some(String::from(value)),
"tooltip_side" => {
tooltip_side = match value {
"left" => Some(tooltip::TooltipSide::Left),
"right" => Some(tooltip::TooltipSide::Right),
"top" => Some(tooltip::TooltipSide::Top),
"bottom" => Some(tooltip::TooltipSide::Bottom),
_ => {
print_invalid_attrib(key, value);
None
}
}
}
_ => {} _ => {}
} }
} }
@@ -72,6 +87,10 @@ pub fn parse_component_button<'a>(
style, style,
text_style, text_style,
round, round,
tooltip: tooltip.map(|t| tooltip::TooltipInfo {
side: tooltip_side.map_or(tooltip::TooltipSide::Bottom, |f| f),
text: Translation::from_translation_key(&t),
}),
}, },
)?; )?;

View File

@@ -27,6 +27,7 @@ pub struct WidgetData {
pub scrolling_cur: Vec2, // normalized, used for smooth scrolling animation pub scrolling_cur: Vec2, // normalized, used for smooth scrolling animation
pub scrolling_cur_prev: Vec2, // for motion interpolation while rendering between ticks pub scrolling_cur_prev: Vec2, // for motion interpolation while rendering between ticks
pub transform: glam::Mat4, pub transform: glam::Mat4,
pub cached_absolute_boundary: drawing::Boundary, // updated in Layout::push_event_widget
} }
impl WidgetData { impl WidgetData {
@@ -95,6 +96,7 @@ impl WidgetState {
scrolling_cur: Vec2::default(), scrolling_cur: Vec2::default(),
scrolling_cur_prev: Vec2::default(), scrolling_cur_prev: Vec2::default(),
transform: glam::Mat4::IDENTITY, transform: glam::Mat4::IDENTITY,
cached_absolute_boundary: drawing::Boundary::default(),
}, },
obj, obj,
event_listeners: EventListenerCollection::default(), event_listeners: EventListenerCollection::default(),