aboutsummaryrefslogtreecommitdiff
path: root/client-native-gui/src/main.rs
blob: 69d165775d462a41fdcccee3f13d7cee160bc40b (plain)
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#![feature(box_syntax)]

use async_std::task::block_on;
use client_native_lib::{
    instance::Instance,
    peer::Peer,
    protocol::{ProvideInfo, RelayMessage},
    Config, EventHandler,
};
use eframe::egui;
use egui::{Ui, Visuals};
use std::{
    collections::HashMap,
    sync::{Arc, RwLock},
};
use tokio::task::JoinHandle;

#[tokio::main]
async fn main() {
    env_logger::builder()
        .filter_module("keks_meet", log::LevelFilter::Info)
        .filter_module("client_native_lib", log::LevelFilter::Info)
        .parse_env("LOG")
        .init();

    let options = eframe::NativeOptions::default();
    eframe::run_native(
        "keks-meet",
        options,
        Box::new(|cc| {
            cc.egui_ctx.set_visuals(Visuals {
                dark_mode: true,
                ..Default::default()
            });
            Box::new(App::new())
        }),
    );
}

enum App {
    Prejoin(String, String),
    Joining(Option<JoinHandle<Ingame>>),
    Ingame(Ingame),
}

struct Ingame {
    instance: Arc<Instance>,
    handler: Arc<Handler>,
}

struct Handler {
    peers: RwLock<HashMap<usize, GuiPeer>>,
}

struct GuiPeer {
    peer: Arc<Peer>,
    resources: HashMap<String, GuiResource>,
    username: Option<String>,
}

struct GuiResource {
    info: ProvideInfo,
    state: GuiResourceState,
}

enum GuiResourceState {
    Available,
    Connecting,
    Connected,
}

impl App {
    pub fn new() -> Self {
        Self::Prejoin("longtest".to_string(), "blub".to_string())
    }
}

impl eframe::App for App {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        egui::CentralPanel::default().show(ctx, |ui| match self {
            App::Prejoin(secret, username) => {
                ui.heading("Join a meeting");
                ui.label("Room secret:");
                ui.text_edit_singleline(secret);
                ui.label("Username:");
                ui.text_edit_singleline(username);
                if ui.button("Join").clicked() {
                    let secret = secret.clone();
                    let username = username.clone();
                    *self = Self::Joining(Some(tokio::spawn(async move {
                        Ingame::new(Config {
                            secret,
                            username,
                            signaling_uri: "wss://meet.metamuffin.org".to_string(),
                        })
                        .await
                    })))
                }
            }
            App::Joining(fut) => {
                ui.spinner();
                if fut.as_ref().map(|f| f.is_finished()).unwrap_or(false) {
                    *self = Self::Ingame(block_on(fut.take().unwrap()).unwrap());
                }
            }
            App::Ingame(x) => x.ui(ui),
        });
    }
}

impl Ingame {
    pub async fn new(config: Config) -> Self {
        let handler = Arc::new(Handler::new());
        let instance = Instance::new(config, handler.clone()).await;
        instance.spawn_ping().await;
        {
            let instance = instance.clone();
            tokio::spawn(instance.receive_loop());
        }
        Self { instance, handler }
    }

    pub fn ui(&self, ui: &mut Ui) {
        for peer in self.handler.peers.write().unwrap().values_mut() {
            ui.collapsing(peer.display_name(), |ui| {
                for resource in peer.resources.values_mut() {
                    resource.ui(ui, &peer.peer)
                }
            });
        }
    }
}
impl GuiResource {
    pub fn ui(&mut self, ui: &mut Ui, peer: &Arc<Peer>) {
        ui.label(&format!(
            "{} {} {:?}",
            self.info.id, self.info.kind, self.info.label
        ));
        match self.state {
            GuiResourceState::Available => {
                if ui.button("Enable").clicked() {
                    let id = self.info.id.clone();
                    let peer = peer.clone();
                    self.state = GuiResourceState::Connecting;
                    tokio::spawn(async move { peer.request_resource(id).await });
                }
            }
            GuiResourceState::Connecting => {
                ui.horizontal(|ui| {
                    ui.spinner();
                    ui.label("Connecting...")
                });
            }
            GuiResourceState::Connected => {
                if ui.button("Disable").clicked() {
                    let id = self.info.id.clone();
                    let peer = peer.clone();
                    self.state = GuiResourceState::Available;
                    tokio::spawn(async move { peer.request_stop_resource(id).await });
                }
            }
        }
    }
}

impl Handler {
    pub fn new() -> Self {
        Self {
            peers: Default::default(),
        }
    }
}

impl GuiPeer {
    pub fn display_name(&self) -> String {
        self.username
            .clone()
            .unwrap_or_else(|| format!("Unknown ({})", self.peer.id))
    }
}

impl EventHandler for Handler {
    fn peer_join(
        &self,
        peer: std::sync::Arc<client_native_lib::peer::Peer>,
    ) -> client_native_lib::DynFut<()> {
        self.peers.write().unwrap().insert(
            peer.id,
            GuiPeer {
                resources: HashMap::new(),
                peer: peer.clone(),
                username: None,
            },
        );
        Box::pin(async move {})
    }

    fn peer_leave(
        &self,
        peer: std::sync::Arc<client_native_lib::peer::Peer>,
    ) -> client_native_lib::DynFut<()> {
        self.peers.write().unwrap().remove(&peer.id);
        Box::pin(async move {})
    }

    fn resource_added(
        &self,
        peer: std::sync::Arc<client_native_lib::peer::Peer>,
        info: client_native_lib::protocol::ProvideInfo,
    ) -> client_native_lib::DynFut<()> {
        if let Some(gp) = self.peers.write().unwrap().get_mut(&peer.id) {
            gp.resources.insert(
                info.id.clone(),
                GuiResource {
                    info,
                    state: GuiResourceState::Available,
                },
            );
        }
        Box::pin(async move {})
    }

    fn resource_removed(
        &self,
        peer: std::sync::Arc<client_native_lib::peer::Peer>,
        id: String,
    ) -> client_native_lib::DynFut<()> {
        if let Some(gp) = self.peers.write().unwrap().get_mut(&peer.id) {
            gp.resources.remove(&id);
        }
        Box::pin(async move {})
    }

    fn resource_connected(
        &self,
        peer: std::sync::Arc<client_native_lib::peer::Peer>,
        resource: &client_native_lib::protocol::ProvideInfo,
        channel: client_native_lib::peer::TransportChannel,
    ) -> client_native_lib::DynFut<()> {
        if let Some(gp) = self.peers.write().unwrap().get_mut(&peer.id) {
            if let Some(gr) = gp.resources.get_mut(&resource.id) {
                gr.state = GuiResourceState::Connected

                // TODO
            }
        }
        Box::pin(async move {})
    }

    fn on_relay(
        &self,
        peer: Arc<Peer>,
        message: &client_native_lib::protocol::RelayMessage,
    ) -> client_native_lib::DynFut<()> {
        let mut guard = self.peers.write().unwrap();
        let p = guard.get_mut(&peer.id).unwrap();
        match message.clone() {
            RelayMessage::Identify { username } => p.username = Some(username),
            _ => (),
        };
        Box::pin(async move {})
    }
}