Skip to main content

yse_ui/widgets/
checkbox.rs

1//! Checkbox wrapper.
2
3use crate::bridge as ffi;
4use crate::bridge::Void;
5use crate::component::Component;
6use crate::widgets::{IntoWidget, widget_wrapper};
7use std::rc::Rc;
8use yse_model::{EventStream, Signal, Sink};
9
10/// A retained two-state checkbox widget.
11pub struct CheckBox {
12    pub(crate) inner: Rc<Component>,
13}
14
15impl CheckBox {
16    /// Whether the box is checked.
17    pub fn checked(&self) -> bool {
18        unsafe { ffi::checkbox_checked(self.inner.raw()) }
19    }
20
21    /// Set the checked state programmatically.
22    pub fn set_checked(&self, checked: bool) {
23        if self.inner.is_alive() {
24            unsafe { ffi::checkbox_set_checked(self.inner.raw(), checked) };
25        }
26    }
27
28    /// A stream of toggle events carrying the new checked state.
29    pub fn toggled(&self) -> EventStream<bool> {
30        if self.inner.toggled_sink.borrow().is_none() {
31            unsafe {
32                ffi::widget_set_toggled_cb(
33                    self.inner.raw(),
34                    &*self.inner as *const Component as *mut Void,
35                );
36            }
37            *self.inner.toggled_sink.borrow_mut() = Some(Rc::new(Sink::new()));
38        }
39        self.inner.toggled_sink.borrow().as_ref().unwrap().stream()
40    }
41
42    /// Register a toggle handler carrying the new checked state.
43    pub fn on_toggle<F>(&self, f: F) -> &Self
44    where
45        F: FnMut(&bool) + 'static,
46    {
47        self.inner.owner.borrow_mut().add(self.toggled().observe(f));
48        self
49    }
50
51    /// Bind the checked state to a signal.
52    pub fn bind_checked(&self, signal: &Signal<bool>) {
53        let weak = Rc::downgrade(&self.inner);
54        let subscription = signal.observe(move |checked| {
55            if let Some(this) = weak.upgrade() {
56                this.set_checkbox_checked(*checked);
57            }
58        });
59        self.inner.owner.borrow_mut().add(subscription);
60    }
61}
62
63widget_wrapper!(CheckBox);