Struct relm4::ComponentSender
source · pub struct ComponentSender<C: Component> { /* private fields */ }
Expand description
Contains senders to send and receive messages from a Component
.
Implementations§
source§impl<C: Component> ComponentSender<C>
impl<C: Component> ComponentSender<C>
sourcepub fn input_sender(&self) -> &Sender<C::Input>
pub fn input_sender(&self) -> &Sender<C::Input>
Retrieve the sender for input messages.
Useful to forward inputs from another component. If you just need to send input messages,
input()
is more concise.
Examples found in repository?
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
fn init(
_: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let model = App {
counter: 0,
worker: AsyncHandler::builder()
.detach_worker(())
.forward(sender.input_sender(), identity),
};
let widgets = view_output!();
ComponentParts { model, widgets }
}
More examples
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
fn init(
_init: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let factory_box = gtk::Box::default();
let counters = FactoryVecDeque::builder()
.launch(factory_box.clone())
.forward(sender.input_sender(), |output| output);
let model = App {
counters,
created_counters: 0,
entry: gtk::EntryBuffer::default(),
};
let widgets = view_output!();
ComponentParts { model, widgets }
}
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
fn init(
_: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let tasks =
FactoryVecDeque::builder()
.launch_default()
.forward(sender.input_sender(), |output| match output {
TaskOutput::Delete(index) => AppMsg::DeleteEntry(index),
});
let model = App { tasks };
let task_list_box = model.tasks.widget();
let widgets = view_output!();
ComponentParts { model, widgets }
}
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
fn init(
_init: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let header = Header::builder()
.launch_with_broker((), &HEADER_BROKER)
.forward(sender.input_sender(), identity);
let dialog = Dialog::builder()
.launch(root.clone().upcast())
.forward(sender.input_sender(), identity);
let model = App {
mode: AppMode::View,
header,
dialog,
};
let widgets = view_output!();
ComponentParts { model, widgets }
}
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
fn init(
_init: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
// We don't have access to the parent window from here
// but we can just use the button to set the transient window for the dialog.
// Relm4 will get the window later by calling [`WidgetExt::root()`]
// on the button once all widgets are connected.
let dialog = Dialog::builder()
.transient_for(&root)
.launch_with_broker((), &DIALOG_BROKER)
.forward(sender.input_sender(), identity);
let model = Button { dialog };
let widgets = view_output!();
ComponentParts { model, widgets }
}
fn update(&mut self, _msg: Self::Input, _sender: ComponentSender<Self>) {}
}
#[derive(Debug)]
enum AppMsg {}
struct App {
button: Controller<Button>,
}
#[relm4::component]
impl SimpleComponent for App {
type Init = ();
type Input = AppMsg;
type Output = ();
view! {
main_window = gtk::ApplicationWindow {
set_default_size: (500, 250),
set_child: Some(model.button.widget()),
}
}
fn init(
_init: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let button = Button::builder()
.launch(())
.forward(sender.input_sender(), identity);
let model = App { button };
let widgets = view_output!();
ComponentParts { model, widgets }
}
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
fn init(
counter: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let counters = FactoryVecDeque::builder()
.launch(adw::TabView::default())
.forward(sender.input_sender(), |output| match output {
CounterOutput::SendFront(index) => AppMsg::SendFront(index),
CounterOutput::MoveUp(index) => AppMsg::MoveUp(index),
CounterOutput::MoveDown(index) => AppMsg::MoveDown(index),
});
let model = App {
created_widgets: counter,
counters,
};
let tab_view = model.counters.widget();
let widgets = view_output!();
ComponentParts { model, widgets }
}
sourcepub fn output_sender(&self) -> &Sender<C::Output>
pub fn output_sender(&self) -> &Sender<C::Output>
Retrieve the sender for output messages.
Useful to forward outputs from another component. If you just need to send output messages,
output()
is more concise.
sourcepub fn command_sender(&self) -> &Sender<C::CommandOutput>
pub fn command_sender(&self) -> &Sender<C::CommandOutput>
Retrieve the sender for command output messages.
Useful to forward outputs from another component. If you just need to send output messages,
command()
is more concise.
sourcepub fn input(&self, message: C::Input)
pub fn input(&self, message: C::Input)
Emit an input to the component.
Examples found in repository?
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
fn update(&mut self, msg: Self::Input, sender: ComponentSender<Self>) {
match msg {
Msg::Activate => {
self.activated = "Active";
let toast = adw::Toast::builder()
.title("Activated")
.button_label("Cancel")
.timeout(0)
.build();
toast.connect_button_clicked(move |this| {
this.dismiss();
sender.input(Msg::Cancel);
});
self.toaster.add_toast(toast);
}
Msg::Cancel => self.activated = "Idle",
}
}
More examples
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
fn update_cmd(
&mut self,
msg: Self::CommandOutput,
sender: ComponentSender<Self>,
_root: &Self::Root,
) {
if msg {
sender.input(AppMsg::StopGame);
} else {
let mut counters_guard = self.counters.guard();
match rand::random::<u8>() % 3 {
0 => {
counters_guard.swap(1, 2);
}
1 => {
counters_guard.swap(0, 1);
}
_ => {
let widget = counters_guard.widget();
if !widget.select_next_page() {
widget.select_previous_page();
}
}
}
}
}
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
fn init(
counter: Self::Init,
window: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let model = App { counter };
let vbox = gtk::Box::builder()
.orientation(gtk::Orientation::Vertical)
.spacing(5)
.build();
let inc_button = gtk::Button::with_label("Increment");
let dec_button = gtk::Button::with_label("Decrement");
let label = gtk::Label::new(Some(&format!("Counter: {}", model.counter)));
label.set_margin_all(5);
window.set_child(Some(&vbox));
vbox.set_margin_all(5);
vbox.append(&inc_button);
vbox.append(&dec_button);
vbox.append(&label);
inc_button.connect_clicked(clone!(@strong sender => move |_| {
sender.input(Msg::Increment);
}));
dec_button.connect_clicked(clone!(@strong sender => move |_| {
sender.input(Msg::Decrement);
}));
let widgets = AppWidgets { label };
ComponentParts { model, widgets }
}
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
fn init(
_init: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let menu_model = gtk::gio::Menu::new();
menu_model.append(Some("Stateless"), Some(&ExampleAction::action_name()));
let model = Self { counter: 0 };
let widgets = view_output!();
let app = relm4::main_application();
app.set_accelerators_for_action::<ExampleAction>(&["<primary>W"]);
let action: RelmAction<ExampleAction> = RelmAction::new_stateless(move |_| {
println!("Statelesss action!");
sender.input(Msg::Increment);
});
let action2: RelmAction<ExampleU8Action> =
RelmAction::new_stateful_with_target_value(&0, |_, state, value| {
println!("Stateful action -> state: {state}, value: {value}");
*state += value;
});
let mut group = RelmActionGroup::<WindowActionGroup>::new();
group.add_action(action);
group.add_action(action2);
group.register_for_widget(&widgets.main_window);
ComponentParts { model, widgets }
}
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
fn init(
_args: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
relm4::view! {
container = gtk::Box {
set_halign: gtk::Align::Center,
set_valign: gtk::Align::Center,
set_width_request: 300,
set_spacing: 12,
set_margin_top: 4,
set_margin_bottom: 4,
set_margin_start: 12,
set_margin_end: 12,
set_orientation: gtk::Orientation::Horizontal,
gtk::Box {
set_spacing: 4,
set_hexpand: true,
set_valign: gtk::Align::Center,
set_orientation: gtk::Orientation::Vertical,
append: label = >k::Label {
set_xalign: 0.0,
set_label: "Find the answer to life:",
},
append: progress = >k::ProgressBar {
set_visible: false,
},
},
append: button = >k::Button {
set_label: "Compute",
connect_clicked => Input::Compute,
}
}
}
root.set_child(Some(&container));
ComponentParts {
model: App::default(),
widgets: Widgets {
label,
button,
progress,
},
}
}
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
fn init(
counter: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
// ============================================================
//
// You can also use menu! outside of the widget macro.
// This is the manual equivalent to the the menu! macro above.
//
// ============================================================
//
// relm4::menu! {
// main_menu: {
// custom: "my_widget",
// "Example" => ExampleAction,
// "Example2" => ExampleAction,
// "Example toggle" => ExampleU8Action(1_u8),
// section! {
// "Section example" => ExampleAction,
// "Example toggle" => ExampleU8Action(1_u8),
// },
// section! {
// "Example" => ExampleAction,
// "Example2" => ExampleAction,
// "Example Value" => ExampleU8Action(1_u8),
// }
// }
// };
let model = Self { counter };
let widgets = view_output!();
let app = relm4::main_application();
app.set_accelerators_for_action::<ExampleAction>(&["<primary>W"]);
let action: RelmAction<ExampleAction> = {
RelmAction::new_stateless(move |_| {
println!("Statelesss action!");
sender.input(Msg::Increment);
})
};
let action2: RelmAction<ExampleU8Action> =
RelmAction::new_stateful_with_target_value(&0, |_, state, _value| {
*state ^= 1;
dbg!(state);
});
let mut group = RelmActionGroup::<WindowActionGroup>::new();
group.add_action(action);
group.add_action(action2);
group.register_for_widget(&widgets.main_window);
ComponentParts { model, widgets }
}
sourcepub fn output(&self, message: C::Output) -> Result<(), C::Output>
pub fn output(&self, message: C::Output) -> Result<(), C::Output>
Examples found in repository?
More examples
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
fn init(
title: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
// Request the caller to reload its options.
sender.output(Output::Reload).unwrap();
let label = gtk::Label::builder().label(title).margin_top(24).build();
let list = gtk::ListBox::builder()
.halign(gtk::Align::Center)
.margin_bottom(24)
.margin_top(24)
.selection_mode(gtk::SelectionMode::None)
.build();
root.append(&label);
root.append(&list);
ComponentParts {
model: App::default(),
widgets: Widgets {
list,
button_sg: gtk::SizeGroup::new(gtk::SizeGroupMode::Both),
options: Default::default(),
},
}
}
fn update(&mut self, message: Self::Input, sender: ComponentSender<Self>, _root: &Self::Root) {
match message {
Input::AddSetting {
description,
button,
id,
} => {
self.options.push((description, button, id));
}
Input::Clear => {
self.options.clear();
// Perform this async operation.
sender.oneshot_command(async move {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
CmdOut::Reload
});
}
Input::Reload => {
sender.output(Output::Reload).unwrap();
}
}
}
fn update_cmd(
&mut self,
message: Self::CommandOutput,
sender: ComponentSender<Self>,
_root: &Self::Root,
) {
match message {
CmdOut::Reload => {
sender.output(Output::Reload).unwrap();
}
}
}
fn update_view(&self, widgets: &mut Self::Widgets, sender: ComponentSender<Self>) {
if self.options.is_empty() && !widgets.options.is_empty() {
widgets.list.remove_all();
} else if self.options.len() != widgets.options.len() {
if let Some((description, button_label, id)) = self.options.last() {
let id = *id;
relm4::view! {
widget = gtk::Box {
set_orientation: gtk::Orientation::Horizontal,
set_margin_start: 20,
set_margin_end: 20,
set_margin_top: 8,
set_margin_bottom: 8,
set_spacing: 24,
append = >k::Label {
set_label: description,
set_halign: gtk::Align::Start,
set_hexpand: true,
set_valign: gtk::Align::Center,
set_ellipsize: gtk::pango::EllipsizeMode::End,
},
append: button = >k::Button {
set_label: button_label,
set_size_group: &widgets.button_sg,
connect_clicked[sender] => move |_| {
sender.output(Output::Clicked(id)).unwrap();
}
}
}
}
widgets.list.append(&widget);
widgets.options.push(widget);
}
}
}
sourcepub fn command<Cmd, Fut>(&self, cmd: Cmd)where
Cmd: FnOnce(Sender<C::CommandOutput>, ShutdownReceiver) -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send,
pub fn command<Cmd, Fut>(&self, cmd: Cmd)where
Cmd: FnOnce(Sender<C::CommandOutput>, ShutdownReceiver) -> Fut + Send + 'static,
Fut: Future<Output = ()> + Send,
Spawns an asynchronous command.
You can bind the the command to the lifetime of the component
by using a ShutdownReceiver
.
Examples found in repository?
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
fn init(
_: Self::Init,
root: Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let model = App {
width: 100.0,
height: 100.0,
points: Vec::new(),
handler: DrawHandler::new(),
};
let area = model.handler.drawing_area();
let widgets = view_output!();
sender.command(|out, shutdown| {
shutdown
.register(async move {
loop {
tokio::time::sleep(Duration::from_millis(20)).await;
out.send(UpdatePointsMsg).unwrap();
}
})
.drop_on_shutdown()
});
ComponentParts { model, widgets }
}
More examples
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
fn update(&mut self, message: Self::Input, sender: ComponentSender<Self>, _root: &Self::Root) {
match message {
Input::Compute => {
self.computing = true;
sender.command(|out, shutdown| {
shutdown
// Performs this operation until a shutdown is triggered
.register(async move {
let mut progress = 0.0;
while progress < 1.0 {
out.send(CmdOut::Progress(progress)).unwrap();
progress += 0.1;
tokio::time::sleep(std::time::Duration::from_millis(333)).await;
}
out.send(CmdOut::Finished(Ok("42".into()))).unwrap();
})
// Perform task until a shutdown interrupts it
.drop_on_shutdown()
// Wrap into a `Pin<Box<Future>>` for return
.boxed()
});
}
}
}
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
fn update(&mut self, msg: Self::Input, sender: ComponentSender<Self>, _root: &Self::Root) {
match msg {
AppMsg::StartGame(index) => {
self.start_index = Some(index);
sender.command(|sender, _| async move {
for i in (1..4).rev() {
*GAME_STATE.write() = GameState::Countdown(i);
relm4::tokio::time::sleep(Duration::from_millis(1000)).await;
}
*GAME_STATE.write() = GameState::Running;
for _ in 0..20 {
relm4::tokio::time::sleep(Duration::from_millis(500)).await;
sender.send(false).unwrap();
}
relm4::tokio::time::sleep(Duration::from_millis(1000)).await;
sender.send(true).unwrap();
});
}
AppMsg::StopGame => {
*GAME_STATE.write() = GameState::Guessing;
}
AppMsg::SelectedGuess(index) => {
*GAME_STATE.write() = GameState::End(index == self.start_index.take().unwrap());
}
}
}
sourcepub fn spawn_command<Cmd>(&self, cmd: Cmd)
pub fn spawn_command<Cmd>(&self, cmd: Cmd)
Spawns a synchronous command.
This is particularly useful for CPU-intensive background jobs that need to run on a thread-pool in the background.
If you expect the component to be dropped while the command is running take care while sending messages!
sourcepub fn oneshot_command<Fut>(&self, future: Fut)
pub fn oneshot_command<Fut>(&self, future: Fut)
Spawns a future that will be dropped as soon as the factory component is shut down.
Essentially, this is a simpler version of Self::command()
.
Examples found in repository?
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
fn update(&mut self, message: Self::Input, sender: ComponentSender<Self>, _root: &Self::Root) {
match message {
Input::AddSetting {
description,
button,
id,
} => {
self.options.push((description, button, id));
}
Input::Clear => {
self.options.clear();
// Perform this async operation.
sender.oneshot_command(async move {
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
CmdOut::Reload
});
}
Input::Reload => {
sender.output(Output::Reload).unwrap();
}
}
}
More examples
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
fn update(&mut self, msg: Self::Input, sender: ComponentSender<Self>, root: &Self::Root) {
match msg {
AppMsg::StartSearch => {
self.searching = true;
let stream = Dialog::builder()
.transient_for(root)
.launch(())
.into_stream();
sender.oneshot_command(async move {
// Use the component as stream
let result = stream.recv_one().await;
if let Some(search) = result {
let response =
reqwest::get(format!("https://duckduckgo.com/lite/?q={search}"))
.await
.unwrap();
let response_text = response.text().await.unwrap();
// Extract the url of the first search result.
if let Some(url) = response_text.split("<a rel=\"nofollow\" href=\"").nth(1)
{
let url = url.split('\"').next().unwrap().replace("amp;", "");
Some(format!("https:{url}"))
} else {
None
}
} else {
None
}
});
}
}
}
sourcepub fn spawn_oneshot_command<Cmd>(&self, cmd: Cmd)
pub fn spawn_oneshot_command<Cmd>(&self, cmd: Cmd)
Spawns a synchronous command that will be dropped as soon as the factory component is shut down.
Essentially, this is a simpler version of Self::spawn_command()
.