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
use gtk::prelude::*;
use relm4::{prelude::*, Sender};

struct Dialog {
    buffer: gtk::EntryBuffer,
}

#[derive(Debug)]
enum DialogMsg {
    Accept,
    Cancel,
}

#[relm4::component]
impl SimpleComponent for Dialog {
    type Init = ();
    type Input = DialogMsg;
    type Output = String;
    type Widgets = DialogWidgets;

    view! {
        #[root]
        dialog = gtk::MessageDialog {
            set_margin_all: 12,
            set_modal: true,
            set_text: Some("Enter a search query"),
            add_button: ("Search", gtk::ResponseType::Accept),
            present: (),

            connect_response[sender] => move |dialog, resp| {
                dialog.hide();
                sender.input(if resp == gtk::ResponseType::Accept {
                    DialogMsg::Accept
                } else {
                    DialogMsg::Cancel
                });
            }
        },
        dialog.content_area() -> gtk::Box {
            gtk::Entry {
                set_buffer: &model.buffer,
            }
        }
    }

    fn init(
        _: Self::Init,
        root: &Self::Root,
        sender: ComponentSender<Self>,
    ) -> ComponentParts<Self> {
        let model = Dialog {
            buffer: gtk::EntryBuffer::new(None),
        };
        let widgets = view_output!();

        ComponentParts { model, widgets }
    }

    fn update(&mut self, msg: Self::Input, sender: ComponentSender<Self>) {
        match msg {
            DialogMsg::Accept => {
                sender.output(self.buffer.text()).unwrap();
            }
            DialogMsg::Cancel => {
                sender.output(String::default()).unwrap();
            }
        }
    }

    fn shutdown(&mut self, _widgets: &mut Self::Widgets, _output: Sender<Self::Output>) {
        println!("Dialog shutdown");
    }
}

#[derive(Debug)]
enum AppMsg {
    StartSearch,
}

struct App {
    result: Option<String>,
    searching: bool,
}

#[relm4::component]
impl Component for App {
    type Init = ();
    type Input = AppMsg;
    type Output = ();
    type Widgets = AppWidgets;
    type CommandOutput = Option<String>;

    view! {
        main_window = gtk::ApplicationWindow {
            set_default_size: (300, 100),

            gtk::Box {
                set_orientation: gtk::Orientation::Vertical,
                set_margin_all: 12,
                set_spacing: 12,

                if let Some(result) = &model.result {
                    gtk::LinkButton {
                        set_label: "Your search result",
                        #[watch]
                        set_uri: result,
                    }
                } else {
                    gtk::Label {
                        set_label: "Click the button to start a web-search"
                    }
                },
                gtk::Button {
                    set_label: "Start search",
                    connect_clicked => AppMsg::StartSearch,
                    #[watch]
                    set_sensitive: !model.searching,
                }
            }
        }
    }

    fn init(
        _: Self::Init,
        root: &Self::Root,
        _sender: ComponentSender<Self>,
    ) -> ComponentParts<Self> {
        let model = App {
            result: None,
            searching: false,
        };
        let widgets = view_output!();

        ComponentParts { model, widgets }
    }

    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
                    }
                });
            }
        }
    }

    fn update_cmd(
        &mut self,
        message: Self::CommandOutput,
        _sender: ComponentSender<Self>,
        _root: &Self::Root,
    ) {
        self.searching = false;
        self.result = message;
    }
}

fn main() {
    let app = RelmApp::new("relm4.example.message_stream");
    app.run::<App>(());
}