ref: c8f04fcd933d9ddeeec47176e59db8e48efd8abd nex-trip-gtk/src/main.rs -rw-r--r-- 4.2 KiB View raw
                                                                                
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
use futures::channel::mpsc::{Receiver, Sender};
use gio::prelude::*;
use gtk::prelude::*;
use gtk::{ApplicationWindow, Builder, Button, Label};
use serde::Deserialize;
use std::cell::RefCell;
use std::env::args;
use std::rc::Rc;

#[derive(Debug)]
enum UiEvent {
    Refresh,
}

#[derive(Debug)]
enum DataEvent {
    UpdateInfo(String),
}

#[derive(Clone)]
struct UiElements {
    info_label: Label,
}

fn build_ui(
    application: &gtk::Application,
    ui_event_sender: Sender<UiEvent>,
    data_event_receiver: Rc<RefCell<Option<Receiver<DataEvent>>>>,
) {
    let glade_src = include_str!("../assets/main-window.glade");
    let builder = Builder::new_from_string(glade_src);

    let window: ApplicationWindow = builder.get_object("main-window").expect("get main-window");
    window.set_application(Some(application));

    // info stuff
    let refresh_button: Button = builder
        .get_object("refresh-button")
        .expect("get refresh-button");
    let info_label: Label = builder.get_object("info-label").expect("get info-label");

    {
        let info_label = info_label.clone();
        refresh_button.connect_clicked(move |_| {
            ui_event_sender
                .clone()
                .try_send(UiEvent::Refresh)
                .expect("send UI event from refresh button");
            info_label.set_text("Fetching...");
        });
    }

    window.show_all();

    let ui_elements = UiElements { info_label };

    // future on main thread that has access to UI
    let future = {
        let info_label = ui_elements.info_label.clone();
        let mut data_event_receiver = data_event_receiver
            .replace(None)
            .take()
            .expect("data_event_reciver");
        async move {
            use futures::stream::StreamExt;

            while let Some(event) = data_event_receiver.next().await {
                println!("data event: {:?}", event);
                match event {
                    DataEvent::UpdateInfo(text) => info_label.set_text(&text),
                }
            }
        }
    };

    let c = glib::MainContext::default();
    c.spawn_local(future);

    // do I need to put this somewhere? It doesn't seem to do anything and doesn't cause problems
    // if I don't use it.
    //c.pop_thread_default();
}

async fn fetch_next_departure() -> String {
    let resp: Vec<Departure> =
        reqwest::get("https://svc.metrotransit.org/NexTrip/56026?format=json")
            .await
            .expect("fetch info")
            .json()
            .await
            .expect("parse body as json");
    println!("{:#?}", resp);

    resp[0].departure_text.clone()
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Departure {
    departure_text: String,
}

fn main() {
    use std::thread;

    // thread-to-thread communication
    let (ui_event_sender, mut ui_event_receiver) = futures::channel::mpsc::channel(0);
    let (mut data_event_sender, data_event_receiver) = futures::channel::mpsc::channel(0);

    // spawn data/network thread
    thread::spawn(move || {
        use tokio::runtime::Runtime;

        let rt = Runtime::new().expect("create tokio runtime");
        rt.block_on(async {
            use futures::sink::SinkExt;
            use futures::stream::StreamExt;

            while let Some(event) = ui_event_receiver.next().await {
                println!("got event: {:?}", event);
                match event {
                    UiEvent::Refresh => data_event_sender
                        .send(DataEvent::UpdateInfo(fetch_next_departure().await))
                        .await
                        .expect("send refresh result"),
                }
            }
        })
    });

    // main thread is ui thread
    let application = gtk::Application::new(Some("net.azdle.nex-trip-gtk"), Default::default())
        .expect("create application");

    // this type is a evil hack that I'm using because the closure passed to `connect_activate`
    // needs to be `Clone`.
    let data_event_receiver = Rc::new(RefCell::new(Some(data_event_receiver)));
    application.connect_activate(move |app| {
        build_ui(app, ui_event_sender.clone(), data_event_receiver.clone());
    });

    application.run(&args().collect::<Vec<_>>());
}