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?
139 140 141 142 143 144 145 146 147 148 149 150 151 152
fn init(
_: Self::Init,
root: &Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let model = App {
tasks: FactoryVecDeque::new(gtk::ListBox::default(), sender.input_sender()),
};
let task_list_box = model.tasks.widget();
let widgets = view_output!();
ComponentParts { model, widgets }
}
More examples
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 }
}
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
fn init(
counter: Self::Init,
root: &Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let counters = FactoryVecDeque::new(gtk::Box::default(), sender.input_sender());
let model = App {
created_widgets: counter,
counters,
};
let counter_box = model.counters.widget();
let widgets = view_output!();
ComponentParts { model, widgets }
}
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
fn init(
counter: Self::Init,
root: &Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let counters = FactoryVecDeque::new(gtk::Grid::default(), sender.input_sender());
let model = App {
created_widgets: counter,
counters,
};
let counter_grid = model.counters.widget();
let widgets = view_output!();
ComponentParts { model, widgets }
}
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
fn init(
counter: Self::Init,
root: &Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let counters = AsyncFactoryVecDeque::new(gtk::Box::default(), sender.input_sender());
let model = App {
created_widgets: counter,
counters,
};
let counter_box = model.counters.widget();
let widgets = view_output!();
ComponentParts { model, widgets }
}
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
fn init(
_init: Self::Init,
root: &Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let factory_box = gtk::Box::default();
let model = App {
counters: FactoryVecDeque::new(factory_box.clone(), sender.input_sender()),
created_counters: 0,
entry: gtk::EntryBuffer::new(None),
};
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?
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 }
}
More examples
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 88 89 90 91 92
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 group = RelmActionGroup::<WindowActionGroup>::new();
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;
});
group.add_action(&action);
group.add_action(&action2);
let actions = group.into_action_group();
widgets
.main_window
.insert_action_group(WindowActionGroup::NAME, Some(&actions));
ComponentParts { model, widgets }
}
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 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 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
fn init(
_: Self::Init,
root: &Self::Root,
sender: ComponentSender<Self>,
) -> ComponentParts<Self> {
let open_dialog = OpenDialog::builder()
.transient_for_native(root)
.launch(OpenDialogSettings::default())
.forward(sender.input_sender(), |response| match response {
OpenDialogResponse::Accept(path) => Input::OpenResponse(path),
OpenDialogResponse::Cancel => Input::Ignore,
});
let save_dialog = SaveDialog::builder()
.transient_for_native(root)
.launch(SaveDialogSettings::default())
.forward(sender.input_sender(), |response| match response {
SaveDialogResponse::Accept(path) => Input::SaveResponse(path),
SaveDialogResponse::Cancel => Input::Ignore,
});
let model = App {
open_dialog,
save_dialog,
buffer: gtk::TextBuffer::new(None),
file_name: None,
message: None,
};
let widgets = view_output!();
sender.input(Input::ShowMessage(String::from(
"A simple text editor showing the usage of\n<b>OpenFileDialog</b> and <b>SaveFileDialog</b> components.\n\nStart by clicking <b>Open</b> on the header bar.",
)));
ComponentParts { model, widgets }
}
fn update(&mut self, message: Self::Input, sender: ComponentSender<Self>) {
match message {
Input::OpenRequest => self.open_dialog.emit(OpenDialogMsg::Open),
Input::OpenResponse(path) => match std::fs::read_to_string(&path) {
Ok(contents) => {
self.buffer.set_text(&contents);
self.file_name = Some(
path.file_name()
.expect("The path has no file name")
.to_str()
.expect("Cannot convert file name to string")
.to_string(),
);
}
Err(e) => sender.input(Input::ShowMessage(e.to_string())),
},
Input::SaveRequest => self
.save_dialog
.emit(SaveDialogMsg::SaveAs(self.file_name.clone().unwrap())),
Input::SaveResponse(path) => match std::fs::write(
&path,
self.buffer
.text(&self.buffer.start_iter(), &self.buffer.end_iter(), false),
) {
Ok(_) => {
sender.input(Input::ShowMessage(format!(
"File saved successfully at {path:?}"
)));
self.buffer.set_text("");
self.file_name = None;
}
Err(e) => sender.input(Input::ShowMessage(e.to_string())),
},
Input::ShowMessage(message) => {
self.message = Some(message);
}
Input::ResetMessage => {
self.message = None;
}
Input::Ignore => {}
}
}
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 149 150 151 152 153
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 group = RelmActionGroup::<WindowActionGroup>::new();
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);
});
group.add_action(&action);
group.add_action(&action2);
let actions = group.into_action_group();
widgets
.main_window
.insert_action_group("win", Some(&actions));
ComponentParts { model, widgets }
}
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()
});
}
}
}
sourcepub fn spawn_command<Cmd>(&self, cmd: Cmd)where
Cmd: FnOnce(Sender<C::CommandOutput>) + Send + 'static,
pub fn spawn_command<Cmd>(&self, cmd: Cmd)where Cmd: FnOnce(Sender<C::CommandOutput>) + Send + 'static,
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)where
Fut: Future<Output = C::CommandOutput> + Send + 'static,
pub fn oneshot_command<Fut>(&self, future: Fut)where Fut: Future<Output = C::CommandOutput> + Send + 'static,
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
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
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)where
Cmd: FnOnce() -> C::CommandOutput + Send + 'static,
pub fn spawn_oneshot_command<Cmd>(&self, cmd: Cmd)where Cmd: FnOnce() -> C::CommandOutput + Send + 'static,
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()
.
source§impl<C: Component> ComponentSender<C>
impl<C: Component> ComponentSender<C>
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
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 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::builders::LabelBuilder::new()
.label(&title)
.margin_top(24)
.build();
let list = gtk::builders::ListBoxBuilder::new()
.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);
}
}
}