1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
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
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
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
234
235
236
237
238
239
240
// Copyright 2022 System76 <info@system76.com>
// SPDX-License-Identifier: MIT or Apache-2.0

//! A component which allows the caller to define what options ae in its list.
//!
//! On init of the view, an output is sent to the caller to request to load widgets.
//!
//! Clicking a button will open the webpage to that option.
//!
//! Clicking the clear button will clear the list box and send a command to the
//! background that waits 2 seconds before issuing a reload command back to the
//! component, which forwards the reload command back to the caller of the
//! component, which then issues to reload the widgets again.

use gtk::prelude::*;
use relm4::*;

fn main() {
    gtk::Application::builder()
        .application_id("org.relm4.SettingsListExample")
        .launch(|_app, window| {
            // Initialize a component's root widget
            let component = App::builder()
                // Attach the root widget to the given window.
                .attach_to(&window)
                // Start the component service with an initial parameter
                .launch("Settings List Demo".into())
                // Attach the returned receiver's messages to this closure.
                .connect_receiver(move |sender, message| match message {
                    Output::Clicked(id) => {
                        eprintln!("ID {id} Clicked");

                        match id {
                            0 => xdg_open("https://github.com/Relm4/Relm4".into()),
                            1 => xdg_open("https://docs.rs/relm4/".into()),
                            2 => {
                                sender.send(Input::Clear).unwrap();
                            }
                            _ => (),
                        }
                    }

                    Output::Reload => {
                        sender
                            .send(Input::AddSetting {
                                description: "Browse GitHub Repository".into(),
                                button: "GitHub".into(),
                                id: 0,
                            })
                            .unwrap();

                        sender
                            .send(Input::AddSetting {
                                description: "Browse Documentation".into(),
                                button: "Docs".into(),
                                id: 1,
                            })
                            .unwrap();

                        sender
                            .send(Input::AddSetting {
                                description: "Clear List".into(),
                                button: "Clear".into(),
                                id: 2,
                            })
                            .unwrap();
                    }
                });

            println!("parent is {:?}", component.widget().toplevel_window());
        });
}

#[derive(Default)]
pub struct App {
    pub options: Vec<(String, String, u32)>,
}

pub struct Widgets {
    pub list: gtk::ListBox,
    pub options: Vec<gtk::Box>,
    pub button_sg: gtk::SizeGroup,
}

#[derive(Debug)]
pub enum Input {
    AddSetting {
        description: String,
        button: String,
        id: u32,
    },
    Clear,
    Reload,
}

#[derive(Debug)]
pub enum Output {
    Clicked(u32),
    Reload,
}

#[derive(Debug)]
pub enum CmdOut {
    Reload,
}

impl Component for App {
    type Init = String;
    type Input = Input;
    type Output = Output;
    type CommandOutput = CmdOut;
    type Widgets = Widgets;
    type Root = gtk::Box;

    fn init_root() -> Self::Root {
        gtk::Box::builder()
            .halign(gtk::Align::Center)
            .hexpand(true)
            .orientation(gtk::Orientation::Vertical)
            .build()
    }

    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 = &gtk::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 = &gtk::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);
            }
        }
    }
}

fn xdg_open(item: String) {
    std::thread::spawn(move || {
        let _ = std::process::Command::new("xdg-open").arg(item).status();
    });
}