summaryrefslogtreecommitdiff
path: root/src/ui/rooms.rs
blob: 3e4d9d008880142af8c2d04340b690b09ba0dcf3 (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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
use std::collections::{HashMap, HashSet};
use std::iter;
use std::sync::Arc;

use crossterm::style::{ContentStyle, Stylize};
use euphoxide::api::SessionType;
use euphoxide::conn::{Joined, Status};
use parking_lot::FairMutex;
use tokio::sync::mpsc;
use toss::styled::Styled;
use toss::terminal::Terminal;

use crate::config::{Config, RoomsSortOrder};
use crate::euph::EuphRoomEvent;
use crate::vault::Vault;

use super::euph::room::{EuphRoom, RoomStatus};
use super::input::{key, InputEvent, KeyBindingsList};
use super::widgets::editor::EditorState;
use super::widgets::join::{HJoin, Segment, VJoin};
use super::widgets::layer::Layer;
use super::widgets::list::{List, ListState};
use super::widgets::popup::Popup;
use super::widgets::resize::Resize;
use super::widgets::text::Text;
use super::widgets::BoxedWidget;
use super::{util, UiEvent};

enum State {
    ShowList,
    ShowRoom(String),
    Connect(EditorState),
    Delete(String, EditorState),
}

enum Order {
    Alphabet,
    Importance,
}

impl Order {
    fn from_rooms_sort_order(order: RoomsSortOrder) -> Self {
        match order {
            RoomsSortOrder::Alphabet => Self::Alphabet,
            RoomsSortOrder::Importance => Self::Importance,
        }
    }
}

pub struct Rooms {
    config: &'static Config,

    vault: Vault,
    ui_event_tx: mpsc::UnboundedSender<UiEvent>,

    state: State,

    list: ListState<String>,
    order: Order,
    euph_rooms: HashMap<String, EuphRoom>,
}

impl Rooms {
    pub fn new(
        config: &'static Config,
        vault: Vault,
        ui_event_tx: mpsc::UnboundedSender<UiEvent>,
    ) -> Self {
        let mut result = Self {
            config,
            vault,
            ui_event_tx,
            state: State::ShowList,
            list: ListState::new(),
            order: Order::from_rooms_sort_order(config.rooms_sort_order),
            euph_rooms: HashMap::new(),
        };

        if !config.offline {
            for (name, config) in &config.euph.rooms {
                if config.autojoin {
                    result.get_or_insert_room(name.clone()).connect();
                }
            }
        }

        result
    }

    fn get_or_insert_room(&mut self, name: String) -> &mut EuphRoom {
        self.euph_rooms.entry(name.clone()).or_insert_with(|| {
            EuphRoom::new(
                self.config.euph_room(&name),
                self.vault.euph().room(name),
                self.ui_event_tx.clone(),
            )
        })
    }

    /// Remove rooms that are not running any more and can't be found in the db.
    /// Insert rooms that are in the db but not yet in in the hash map.
    ///
    /// These kinds of rooms are either
    /// - failed connection attempts, or
    /// - rooms that were deleted from the db.
    async fn stabilize_rooms(&mut self) {
        let mut rooms_set = self
            .vault
            .euph()
            .rooms()
            .await
            .into_iter()
            .collect::<HashSet<_>>();

        // Prevent room that is currently being shown from being removed. This
        // could otherwise happen when connecting to a room that doesn't exist.
        if let State::ShowRoom(name) = &self.state {
            rooms_set.insert(name.clone());
        }

        self.euph_rooms
            .retain(|n, r| !r.stopped() || rooms_set.contains(n));

        for room in rooms_set {
            self.get_or_insert_room(room).retain();
        }
    }

    pub async fn widget(&mut self) -> BoxedWidget {
        match &self.state {
            State::ShowRoom(_) => {}
            _ => self.stabilize_rooms().await,
        }

        match &self.state {
            State::ShowList => self.rooms_widget().await,
            State::ShowRoom(name) => {
                self.euph_rooms
                    .get_mut(name)
                    .expect("room exists after stabilization")
                    .widget()
                    .await
            }
            State::Connect(editor) => Layer::new(vec![
                self.rooms_widget().await,
                Self::new_room_widget(editor),
            ])
            .into(),
            State::Delete(name, editor) => Layer::new(vec![
                self.rooms_widget().await,
                Self::delete_room_widget(name, editor),
            ])
            .into(),
        }
    }

    fn new_room_widget(editor: &EditorState) -> BoxedWidget {
        let room_style = ContentStyle::default().bold().blue();
        let editor = editor.widget().highlight(|s| Styled::new(s, room_style));
        Popup::new(HJoin::new(vec![
            Segment::new(Text::new(("&", room_style))),
            Segment::new(editor).priority(0),
        ]))
        .title("Connect to")
        .build()
    }

    fn delete_room_widget(name: &str, editor: &EditorState) -> BoxedWidget {
        let warn_style = ContentStyle::default().bold().red();
        let room_style = ContentStyle::default().bold().blue();
        let editor = editor.widget().highlight(|s| Styled::new(s, room_style));
        let text = Styled::new_plain("Are you sure you want to delete ")
            .then("&", room_style)
            .then(name, room_style)
            .then_plain("?\n\n")
            .then_plain("This will delete the entire room history from your vault. ")
            .then_plain("To shrink your vault afterwards, run ")
            .then("cove gc", ContentStyle::default().italic().grey())
            .then_plain(".\n\n")
            .then_plain("To confirm the deletion, ")
            .then_plain("enter the full name of the room and press enter:");
        Popup::new(VJoin::new(vec![
            // The HJoin prevents the text from filling up the entire available
            // space if the editor is wider than the text.
            Segment::new(HJoin::new(vec![Segment::new(
                Resize::new(Text::new(text).wrap(true)).max_width(54),
            )])),
            Segment::new(HJoin::new(vec![
                Segment::new(Text::new(("&", room_style))),
                Segment::new(editor).priority(0),
            ])),
        ]))
        .title(("Delete room", warn_style))
        .border(warn_style)
        .build()
    }

    fn format_pbln(joined: &Joined) -> String {
        let mut p = 0_usize;
        let mut b = 0_usize;
        let mut l = 0_usize;
        let mut n = 0_usize;

        let sessions = joined
            .listing
            .values()
            .map(|s| (s.id(), s.name()))
            .chain(iter::once((
                &joined.session.id,
                &joined.session.name as &str,
            )));
        for (user_id, name) in sessions {
            match user_id.session_type() {
                Some(SessionType::Bot) if name.is_empty() => n += 1,
                Some(SessionType::Bot) => b += 1,
                _ if name.is_empty() => l += 1,
                _ => p += 1,
            }
        }

        // There must always be either one p, b, l or n since we're including
        // ourselves.
        let mut result = vec![];
        if p > 0 {
            result.push(format!("{p}p"));
        }
        if b > 0 {
            result.push(format!("{b}b"));
        }
        if l > 0 {
            result.push(format!("{l}l"));
        }
        if n > 0 {
            result.push(format!("{n}n"));
        }
        result.join(" ")
    }

    fn format_status(status: RoomStatus) -> Option<String> {
        match status {
            RoomStatus::NoRoom | RoomStatus::Stopped => None,
            RoomStatus::Connecting => Some("connecting".to_string()),
            RoomStatus::Connected(Status::Joining(j)) if j.bounce.is_some() => {
                Some("auth required".to_string())
            }
            RoomStatus::Connected(Status::Joining(_)) => Some("joining".to_string()),
            RoomStatus::Connected(Status::Joined(joined)) => Some(Self::format_pbln(&joined)),
        }
    }

    fn format_unseen_msgs(unseen: usize) -> Option<String> {
        if unseen == 0 {
            None
        } else {
            Some(format!("{unseen}"))
        }
    }

    fn format_room_info(status: RoomStatus, unseen: usize) -> Styled {
        let unseen_style = ContentStyle::default().bold().green();

        let status = Self::format_status(status);
        let unseen = Self::format_unseen_msgs(unseen);

        match (status, unseen) {
            (None, None) => Styled::default(),
            (None, Some(u)) => Styled::new_plain(" (")
                .then(&u, unseen_style)
                .then_plain(")"),
            (Some(s), None) => Styled::new_plain(" (").then_plain(&s).then_plain(")"),
            (Some(s), Some(u)) => Styled::new_plain(" (")
                .then_plain(&s)
                .then_plain(", ")
                .then(&u, unseen_style)
                .then_plain(")"),
        }
    }

    fn sort_rooms(&self, rooms: &mut [(&String, RoomStatus, usize)]) {
        match self.order {
            Order::Alphabet => rooms.sort_unstable_by_key(|(n, _, _)| *n),
            Order::Importance => {
                rooms.sort_unstable_by_key(|(n, s, u)| (!s.connecting_or_connected(), *u == 0, *n))
            }
        }
    }

    async fn render_rows(&self, list: &mut List<String>) {
        if self.euph_rooms.is_empty() {
            list.add_unsel(Text::new((
                "Press F1 for key bindings",
                ContentStyle::default().grey().italic(),
            )))
        }

        let mut rooms = vec![];
        for (name, room) in &self.euph_rooms {
            let status = room.status().await;
            let unseen = room.unseen_msgs_count().await;
            rooms.push((name, status, unseen));
        }
        self.sort_rooms(&mut rooms);
        for (name, status, unseen) in rooms {
            let room_style = ContentStyle::default().bold().blue();
            let room_sel_style = ContentStyle::default().bold().black().on_white();

            let mut normal = Styled::new(format!("&{name}"), room_style);
            let mut selected = Styled::new(format!("&{name}"), room_sel_style);

            let info = Self::format_room_info(status, unseen);
            normal = normal.and_then(info.clone());
            selected = selected.and_then(info);

            list.add_sel(name.clone(), Text::new(normal), Text::new(selected));
        }
    }

    async fn rooms_widget(&self) -> BoxedWidget {
        let heading_style = ContentStyle::default().bold();
        let amount = self.euph_rooms.len();
        let heading =
            Text::new(Styled::new("Rooms", heading_style).then_plain(format!(" ({amount})")));

        let mut list = self.list.widget().focus(true);
        self.render_rows(&mut list).await;

        VJoin::new(vec![Segment::new(heading), Segment::new(list).priority(0)]).into()
    }

    fn room_char(c: char) -> bool {
        c.is_ascii_alphanumeric() || c == '_'
    }

    fn list_showlist_key_bindings(bindings: &mut KeyBindingsList) {
        bindings.heading("Rooms");
        util::list_list_key_bindings(bindings);
        bindings.empty();
        bindings.binding("enter", "enter selected room");
        bindings.binding("c", "connect to selected room");
        bindings.binding("C", "connect to all rooms");
        bindings.binding("d", "disconnect from selected room");
        bindings.binding("D", "disconnect from all rooms");
        bindings.binding("a", "connect to all autojoin room");
        bindings.binding("A", "disconnect from all non-autojoin rooms");
        bindings.binding("n", "connect to new room");
        bindings.binding("X", "delete room");
        bindings.empty();
        bindings.binding("s", "change sort order");
    }

    fn handle_showlist_input_event(&mut self, event: &InputEvent) -> bool {
        if util::handle_list_input_event(&mut self.list, event) {
            return true;
        }

        match event {
            key!(Enter) => {
                if let Some(name) = self.list.cursor() {
                    self.state = State::ShowRoom(name);
                }
                return true;
            }
            key!('c') => {
                if let Some(name) = self.list.cursor() {
                    if let Some(room) = self.euph_rooms.get_mut(&name) {
                        room.connect();
                    }
                }
                return true;
            }
            key!('C') => {
                for room in self.euph_rooms.values_mut() {
                    room.connect();
                }
                return true;
            }
            key!('d') => {
                if let Some(name) = self.list.cursor() {
                    if let Some(room) = self.euph_rooms.get_mut(&name) {
                        room.disconnect();
                    }
                }
                return true;
            }
            key!('D') => {
                for room in self.euph_rooms.values_mut() {
                    room.disconnect();
                }
                return true;
            }
            key!('a') => {
                for (name, options) in &self.config.euph.rooms {
                    if options.autojoin {
                        self.get_or_insert_room(name.clone()).connect();
                    }
                }
                return true;
            }
            key!('A') => {
                for (name, room) in &mut self.euph_rooms {
                    let autojoin = self
                        .config
                        .euph
                        .rooms
                        .get(name)
                        .map(|r| r.autojoin)
                        .unwrap_or(false);
                    if !autojoin {
                        room.disconnect();
                    }
                }
                return true;
            }
            key!('n') => {
                self.state = State::Connect(EditorState::new());
                return true;
            }
            key!('X') => {
                if let Some(name) = self.list.cursor() {
                    self.state = State::Delete(name, EditorState::new());
                }
                return true;
            }
            key!('s') => {
                self.order = match self.order {
                    Order::Alphabet => Order::Importance,
                    Order::Importance => Order::Alphabet,
                };
                return true;
            }
            _ => {}
        }

        false
    }

    pub async fn list_key_bindings(&self, bindings: &mut KeyBindingsList) {
        match &self.state {
            State::ShowList => Self::list_showlist_key_bindings(bindings),
            State::ShowRoom(name) => {
                // Key bindings for leaving the room are a part of the room's
                // list_key_bindings function since they may be shadowed by the
                // nick selector or message editor.
                if let Some(room) = self.euph_rooms.get(name) {
                    room.list_key_bindings(bindings).await;
                } else {
                    // There should always be a room here already but I don't
                    // really want to panic in case it is not. If I show a
                    // message like this, it'll hopefully be reported if
                    // somebody ever encounters it.
                    bindings.binding_ctd("oops, this text should never be visible")
                }
            }
            State::Connect(_) => {
                bindings.heading("Rooms");
                bindings.binding("esc", "abort");
                bindings.binding("enter", "connect to room");
                util::list_editor_key_bindings(bindings, Self::room_char);
            }
            State::Delete(_, _) => {
                bindings.heading("Rooms");
                bindings.binding("esc", "abort");
                bindings.binding("enter", "delete room");
                util::list_editor_key_bindings(bindings, Self::room_char);
            }
        }
    }

    pub async fn handle_input_event(
        &mut self,
        terminal: &mut Terminal,
        crossterm_lock: &Arc<FairMutex<()>>,
        event: &InputEvent,
    ) -> bool {
        self.stabilize_rooms().await;

        match &self.state {
            State::ShowList => {
                if self.handle_showlist_input_event(event) {
                    return true;
                }
            }
            State::ShowRoom(name) => {
                if let Some(room) = self.euph_rooms.get_mut(name) {
                    if room
                        .handle_input_event(terminal, crossterm_lock, event)
                        .await
                    {
                        return true;
                    }

                    if let key!(Esc) = event {
                        self.state = State::ShowList;
                        return true;
                    }
                }
            }
            State::Connect(ed) => match event {
                key!(Esc) => {
                    self.state = State::ShowList;
                    return true;
                }
                key!(Enter) => {
                    let name = ed.text();
                    if !name.is_empty() {
                        self.get_or_insert_room(name.clone()).connect();
                        self.state = State::ShowRoom(name);
                    }
                    return true;
                }
                _ => {
                    if util::handle_editor_input_event(ed, terminal, event, Self::room_char) {
                        return true;
                    }
                }
            },
            State::Delete(name, editor) => match event {
                key!(Esc) => {
                    self.state = State::ShowList;
                    return true;
                }
                key!(Enter) if editor.text() == *name => {
                    self.euph_rooms.remove(name);
                    self.vault.euph().delete(name.clone());
                    self.state = State::ShowList;
                    return true;
                }
                _ => {
                    if util::handle_editor_input_event(editor, terminal, event, Self::room_char) {
                        return true;
                    }
                }
            },
        }

        false
    }

    pub fn handle_euph_room_event(&mut self, name: String, event: EuphRoomEvent) -> bool {
        let room_visible = if let State::ShowRoom(n) = &self.state {
            *n == name
        } else {
            true
        };

        let room = self.get_or_insert_room(name);
        let handled = room.handle_euph_room_event(event);
        handled && room_visible
    }
}