Skip to main content

graphix_package_gui/widgets/
mod.rs

1use anyhow::{bail, Context, Result};
2use arcstr::ArcStr;
3use graphix_compiler::expr::ExprId;
4use graphix_rt::{CallableId, GXExt, GXHandle};
5use netidx::{protocol::valarray::ValArray, publisher::Value};
6use smallvec::SmallVec;
7use std::{future::Future, pin::Pin};
8
9use crate::types::{HAlignV, LengthV, PaddingV, VAlignV};
10
11/// Compile an optional callable ref during widget construction.
12macro_rules! compile_callable {
13    ($gx:expr, $ref:ident, $label:expr) => {
14        match $ref.last.as_ref() {
15            Some(v) => Some($gx.compile_callable(v.clone()).await.context($label)?),
16            None => None,
17        }
18    };
19}
20
21/// Recompile a callable ref inside `handle_update`.
22macro_rules! update_callable {
23    ($self:ident, $rt:ident, $id:ident, $v:ident, $field:ident, $callable:ident, $label:expr) => {
24        if $id == $self.$field.id {
25            $self.$field.last = Some($v.clone());
26            $self.$callable = Some(
27                $rt.block_on($self.gx.compile_callable($v.clone())).context($label)?,
28            );
29        }
30    };
31}
32
33/// Compile a child widget ref during widget construction.
34macro_rules! compile_child {
35    ($gx:expr, $ref:ident, $label:expr) => {
36        match $ref.last.as_ref() {
37            None => Box::new(super::EmptyW) as GuiW<X>,
38            Some(v) => compile($gx.clone(), v.clone()).await.context($label)?,
39        }
40    };
41}
42
43/// Recompile a child widget ref inside `handle_update`.
44/// Sets `$changed = true` when the child is recompiled or updated.
45macro_rules! update_child {
46    ($self:ident, $rt:ident, $id:ident, $v:ident, $changed:ident, $ref:ident, $child:ident, $label:expr) => {
47        if $id == $self.$ref.id {
48            $self.$ref.last = Some($v.clone());
49            $self.$child =
50                $rt.block_on(compile($self.gx.clone(), $v.clone())).context($label)?;
51            $changed = true;
52        }
53        $changed |= $self.$child.handle_update($rt, $id, $v)?;
54    };
55}
56
57pub mod button;
58pub mod canvas;
59pub mod chart;
60pub mod combo_box;
61pub mod container;
62pub mod context_menu;
63pub mod context_menu_widget;
64pub mod grid;
65pub mod iced_keyboard_area;
66pub mod image;
67pub mod keyboard_area;
68pub mod markdown;
69pub mod menu_bar;
70pub mod menu_bar_widget;
71pub mod mouse_area;
72pub mod pick_list;
73pub mod progress_bar;
74pub mod qr_code;
75pub mod radio;
76pub mod rule;
77pub mod scrollable;
78pub mod slider;
79pub mod space;
80pub mod stack;
81pub mod table;
82pub mod text;
83pub mod text_editor;
84pub mod text_input;
85pub mod toggle;
86pub mod tooltip;
87
88/// Concrete iced renderer type used throughout the GUI package.
89/// Must match iced_widget's default Renderer parameter.
90pub type Renderer = iced_renderer::Renderer;
91
92/// Concrete iced Element type with our Message/Theme/Renderer.
93pub type IcedElement<'a> =
94    iced_core::Element<'a, Message, crate::theme::GraphixTheme, Renderer>;
95
96/// Message type for iced widget interactions.
97#[derive(Debug, Clone)]
98pub enum Message {
99    Nop,
100    Call(CallableId, ValArray),
101    EditorAction(ExprId, iced_widget::text_editor::Action),
102}
103
104/// Trait for GUI widgets. Unlike TUI widgets, GUI widgets are not
105/// async — handle_update is synchronous, and the view method builds
106/// an iced Element tree.
107pub trait GuiWidget<X: GXExt>: Send + 'static {
108    /// Process a value update from graphix. Widgets that own child
109    /// refs use `rt` to `block_on` recompilation of their subtree.
110    /// Returns `true` if the widget changed and the window should redraw.
111    fn handle_update(
112        &mut self,
113        rt: &tokio::runtime::Handle,
114        id: ExprId,
115        v: &Value,
116    ) -> Result<bool>;
117
118    /// Build the iced Element tree for rendering.
119    fn view(&self) -> IcedElement<'_>;
120
121    /// Route a text editor action to the widget that owns the given
122    /// content ref. Returns `Some((callable_id, value))` if the action
123    /// was an edit and the result should be called back to graphix.
124    fn editor_action(
125        &mut self,
126        id: ExprId,
127        action: &iced_widget::text_editor::Action,
128    ) -> Option<(CallableId, Value)> {
129        let _ = (id, action);
130        None
131    }
132}
133
134pub type GuiW<X> = Box<dyn GuiWidget<X>>;
135
136/// Future type for widget compilation (avoids infinite-size async fn).
137pub type CompileFut<X> = Pin<Box<dyn Future<Output = Result<GuiW<X>>> + Send + 'static>>;
138
139/// Empty widget placeholder.
140pub struct EmptyW;
141
142impl<X: GXExt> GuiWidget<X> for EmptyW {
143    fn handle_update(
144        &mut self,
145        _rt: &tokio::runtime::Handle,
146        _id: ExprId,
147        _v: &Value,
148    ) -> Result<bool> {
149        Ok(false)
150    }
151
152    fn view(&self) -> IcedElement<'_> {
153        iced_widget::Space::new().into()
154    }
155}
156
157/// Generate a flex layout widget (Row or Column). All parameters use
158/// call-site tokens to satisfy macro hygiene for local variable names.
159macro_rules! flex_widget {
160    ($name:ident, $label:literal,
161     $spacing:ident, $padding:ident, $width:ident, $height:ident,
162     $align_ty:ty, $align:ident, $Widget:ident, $align_set:ident,
163     [$($f:ident),+]) => {
164        pub(crate) struct $name<X: GXExt> {
165            gx: GXHandle<X>,
166            $spacing: graphix_rt::TRef<X, f64>,
167            $padding: graphix_rt::TRef<X, PaddingV>,
168            $width: graphix_rt::TRef<X, LengthV>,
169            $height: graphix_rt::TRef<X, LengthV>,
170            $align: graphix_rt::TRef<X, $align_ty>,
171            children_ref: graphix_rt::Ref<X>,
172            children: Vec<GuiW<X>>,
173        }
174
175        impl<X: GXExt> $name<X> {
176            pub(crate) async fn compile(gx: GXHandle<X>, source: Value) -> Result<GuiW<X>> {
177                let [(_, children), $((_, $f)),+] =
178                    source.cast_to::<[(ArcStr, u64); 6]>()
179                        .context(concat!($label, " flds"))?;
180                let (children_ref, $($f),+) = tokio::try_join!(
181                    gx.compile_ref(children),
182                    $(gx.compile_ref($f)),+
183                )?;
184                let compiled_children = match children_ref.last.as_ref() {
185                    None => vec![],
186                    Some(v) => compile_children(gx.clone(), v.clone()).await
187                        .context(concat!($label, " children"))?,
188                };
189                Ok(Box::new(Self {
190                    gx: gx.clone(),
191                    $spacing: graphix_rt::TRef::new($spacing)
192                        .context(concat!($label, " tref spacing"))?,
193                    $padding: graphix_rt::TRef::new($padding)
194                        .context(concat!($label, " tref padding"))?,
195                    $width: graphix_rt::TRef::new($width)
196                        .context(concat!($label, " tref width"))?,
197                    $height: graphix_rt::TRef::new($height)
198                        .context(concat!($label, " tref height"))?,
199                    $align: graphix_rt::TRef::new($align)
200                        .context(concat!($label, " tref ", stringify!($align)))?,
201                    children_ref,
202                    children: compiled_children,
203                }))
204            }
205        }
206
207        impl<X: GXExt> GuiWidget<X> for $name<X> {
208            fn handle_update(
209                &mut self,
210                rt: &tokio::runtime::Handle,
211                id: ExprId,
212                v: &Value,
213            ) -> Result<bool> {
214                let mut changed = false;
215                changed |= self.$spacing.update(id, v)
216                    .context(concat!($label, " update spacing"))?.is_some();
217                changed |= self.$padding.update(id, v)
218                    .context(concat!($label, " update padding"))?.is_some();
219                changed |= self.$width.update(id, v)
220                    .context(concat!($label, " update width"))?.is_some();
221                changed |= self.$height.update(id, v)
222                    .context(concat!($label, " update height"))?.is_some();
223                changed |= self.$align.update(id, v)
224                    .context(concat!($label, " update ", stringify!($align)))?.is_some();
225                if id == self.children_ref.id {
226                    self.children_ref.last = Some(v.clone());
227                    self.children = rt.block_on(
228                        compile_children(self.gx.clone(), v.clone())
229                    ).context(concat!($label, " children recompile"))?;
230                    changed = true;
231                }
232                for child in &mut self.children {
233                    changed |= child.handle_update(rt, id, v)?;
234                }
235                Ok(changed)
236            }
237
238            fn editor_action(
239                &mut self,
240                id: ExprId,
241                action: &iced_widget::text_editor::Action,
242            ) -> Option<(CallableId, Value)> {
243                for child in &mut self.children {
244                    if let some @ Some(_) = child.editor_action(id, action) {
245                        return some;
246                    }
247                }
248                None
249            }
250
251            fn view(&self) -> IcedElement<'_> {
252                let mut w = iced_widget::$Widget::new();
253                if let Some(sp) = self.$spacing.t {
254                    w = w.spacing(sp as f32);
255                }
256                if let Some(p) = self.$padding.t.as_ref() {
257                    w = w.padding(p.0);
258                }
259                if let Some(wi) = self.$width.t.as_ref() {
260                    w = w.width(wi.0);
261                }
262                if let Some(h) = self.$height.t.as_ref() {
263                    w = w.height(h.0);
264                }
265                if let Some(a) = self.$align.t.as_ref() {
266                    w = w.$align_set(a.0);
267                }
268                for child in &self.children {
269                    w = w.push(child.view());
270                }
271                w.into()
272            }
273        }
274    };
275}
276
277flex_widget!(
278    RowW,
279    "row",
280    spacing,
281    padding,
282    width,
283    height,
284    VAlignV,
285    valign,
286    Row,
287    align_y,
288    [height, padding, spacing, valign, width]
289);
290
291flex_widget!(
292    ColumnW,
293    "column",
294    spacing,
295    padding,
296    width,
297    height,
298    HAlignV,
299    halign,
300    Column,
301    align_x,
302    [halign, height, padding, spacing, width]
303);
304
305/// Compile a widget value into a GuiW. Returns a boxed future to
306/// avoid infinite-size futures from recursive async calls.
307pub fn compile<X: GXExt>(gx: GXHandle<X>, source: Value) -> CompileFut<X> {
308    Box::pin(async move {
309        let (s, v) = source.cast_to::<(ArcStr, Value)>()?;
310        match s.as_str() {
311            "Text" => text::TextW::compile(gx, v).await,
312            "Column" => ColumnW::compile(gx, v).await,
313            "Row" => RowW::compile(gx, v).await,
314            "Container" => container::ContainerW::compile(gx, v).await,
315            "Grid" => grid::GridW::compile(gx, v).await,
316            "Button" => button::ButtonW::compile(gx, v).await,
317            "Space" => space::SpaceW::compile(gx, v).await,
318            "TextInput" => text_input::TextInputW::compile(gx, v).await,
319            "Checkbox" => toggle::CheckboxW::compile(gx, v).await,
320            "Toggler" => toggle::TogglerW::compile(gx, v).await,
321            "Slider" => slider::SliderW::compile(gx, v).await,
322            "ProgressBar" => progress_bar::ProgressBarW::compile(gx, v).await,
323            "Scrollable" => scrollable::ScrollableW::compile(gx, v).await,
324            "HorizontalRule" => rule::HorizontalRuleW::compile(gx, v).await,
325            "VerticalRule" => rule::VerticalRuleW::compile(gx, v).await,
326            "Tooltip" => tooltip::TooltipW::compile(gx, v).await,
327            "PickList" => pick_list::PickListW::compile(gx, v).await,
328            "Stack" => stack::StackW::compile(gx, v).await,
329            "Radio" => radio::RadioW::compile(gx, v).await,
330            "VerticalSlider" => slider::VerticalSliderW::compile(gx, v).await,
331            "ComboBox" => combo_box::ComboBoxW::compile(gx, v).await,
332            "TextEditor" => text_editor::TextEditorW::compile(gx, v).await,
333            "KeyboardArea" => keyboard_area::KeyboardAreaW::compile(gx, v).await,
334            "MouseArea" => mouse_area::MouseAreaW::compile(gx, v).await,
335            "Image" => image::ImageW::compile(gx, v).await,
336            "Canvas" => canvas::CanvasW::compile(gx, v).await,
337            "ContextMenu" => context_menu::ContextMenuW::compile(gx, v).await,
338            "Chart" => chart::ChartW::compile(gx, v).await,
339            "Markdown" => markdown::MarkdownW::compile(gx, v).await,
340            "MenuBar" => menu_bar::MenuBarW::compile(gx, v).await,
341            "QrCode" => qr_code::QrCodeW::compile(gx, v).await,
342            "Table" => table::TableW::compile(gx, v).await,
343            _ => bail!("invalid gui widget type `{s}({v})"),
344        }
345    })
346}
347
348/// Compile an array of widget values into a Vec of GuiW.
349pub async fn compile_children<X: GXExt>(
350    gx: GXHandle<X>,
351    v: Value,
352) -> Result<Vec<GuiW<X>>> {
353    let items = v.cast_to::<SmallVec<[Value; 8]>>()?;
354    let futs: Vec<_> = items.into_iter().map(|item| compile(gx.clone(), item)).collect();
355    futures::future::try_join_all(futs).await
356}