pp_client 3.0.2

A poker client and TUI
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
use anyhow::{Error, bail};
use chrono::{DateTime, Utc};
use mio::{Events, Interest, Poll, Waker};
use private_poker::{
    entities::{Action, Card, GameView, Suit, Usd, User, Username, Vote},
    functional,
    messages::UserState,
    net::{
        messages::{ClientMessage, ServerMessage, UserCommand},
        server::{DEFAULT_POLL_TIMEOUT, SERVER, WAKER},
        utils::{read_prefixed, write_prefixed},
    },
};
use ratatui::{
    DefaultTerminal, Frame,
    crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
    layout::{Alignment, Constraint, Flex, Layout, Margin, Position},
    style::{Style, Stylize},
    symbols::scrollbar,
    text::{Line, Span, Text},
    widgets::{
        Block, Cell, Clear, List, ListDirection, ListItem, Padding, Paragraph, Row, Scrollbar,
        ScrollbarOrientation, Table, block,
    },
};
use std::{
    collections::VecDeque,
    io,
    net::{SocketAddr, TcpStream},
    sync::mpsc::{Receiver, Sender, channel},
    thread,
    time::{Duration, Instant},
};

mod widgets;

use widgets::{ScrollableList, UserInput};

const HELP: &str = "\
all-in
        Go all-in, betting all your money on the hand.                                 
call
        Match the investment required to stay in the hand.                             
check
        Check, voting to move to the next card reveal(s).                              
fold
        Fold, forfeiting your hand.                                                    
play
        Join the playing waitlist.                                                     
raise
        Raise the investment required to stay in the hand. Entering without a value    
        defaults to the min raise amount. Entering AMOUNT will raise by AMOUNT, but    
        AMOUNT must be >= the min raise.                                               
show
        Show your hand. Only possible during the showdown.                             
spectate
        Join spectators. If you're a player, you won't spectate until the game is over.
start
        Start the game. Requires 2+ players or waitlisters.
vote kick USER
        Vote to kick a user from the game. The vote will pass when a majority is
        reached.
vote reset
        Vote to reset game money. Entering without a value defaults to voting to
        reset everyone's money. Entering USER will vote to reset that specific
        user's money.
";
const INVALID_RAISE_MESSAGE: &str = "invalid raise amount";
const MAX_LOG_RECORDS: usize = 1024;
const POLL_TIMEOUT: Duration = Duration::from_millis(100);
const UNRECOGNIZED_COMMAND_MESSAGE: &str = "unrecognized command";

fn make_board_spans(view: &GameView) -> Vec<Span<'_>> {
    (!view.board.is_empty())
        .then(|| {
            std::iter::once(" board: ".into()).chain(
                view.board
                    .iter()
                    .flat_map(|card| vec![make_card_span(card), "  ".into()]),
            )
        })
        .into_iter()
        .flatten()
        .collect()
}

fn make_card_span(card: &Card) -> Span<'_> {
    let Card(.., suit) = card;
    let repr = card.to_string();
    match suit {
        Suit::Club => repr.light_green(),
        Suit::Diamond => repr.light_blue(),
        Suit::Heart => repr.light_red(),
        Suit::Spade => repr.into(),
        Suit::Wild => repr.light_magenta(),
    }
}

fn make_user_row(username: &Username, user: &User) -> Row<'static> {
    let mut row = Row::new(vec![
        Cell::new(Text::from(user.name.to_string()).alignment(Alignment::Left)),
        Cell::new(Text::from(format!("${}", user.money)).alignment(Alignment::Right)),
    ]);

    if username == &user.name {
        row = row.bold().white();
    }

    row
}

#[derive(Clone)]
enum RecordKind {
    Ack,
    Alert,
    Error,
    Game,
    You,
}

/// A timestamped terminal message with an importance label to help
/// direct user attention.
#[derive(Clone)]
struct Record {
    datetime: DateTime<Utc>,
    kind: RecordKind,
    content: String,
}

impl Record {
    fn new(kind: RecordKind, content: String) -> Self {
        Self {
            datetime: Utc::now(),
            kind,
            content,
        }
    }
}

impl From<Record> for ListItem<'_> {
    fn from(val: Record) -> Self {
        let repr = match val.kind {
            RecordKind::Ack => "ACK".light_blue(),
            RecordKind::Alert => "ALERT".light_magenta(),
            RecordKind::Error => "ERROR".light_red(),
            RecordKind::Game => "GAME".light_yellow(),
            RecordKind::You => "YOU".light_green(),
        };

        let msg = vec![
            format!("[{} ", val.datetime.format("%H:%M:%S")).into(),
            Span::styled(format!("{repr:5}"), repr.style),
            format!("]: {}", val.content).into(),
        ];

        let content = Line::from(msg);
        ListItem::new(content)
    }
}

/// Provides turn time remaining warnings at specific intervals when it's
/// the player's turn.
struct TurnWarnings {
    t: Instant,
    idx: usize,
    warnings: [u8; 8],
}

impl TurnWarnings {
    /// Check for a new warning.
    fn check(&mut self) -> Option<u8> {
        if self.idx > 0 {
            let ceiling = self.warnings.last().expect("warnings should be immutable");
            let warning = self.warnings[self.idx - 1];
            let dt = self.t.elapsed();
            let remaining = ceiling.saturating_sub(dt.as_secs() as u8);
            if remaining <= warning {
                self.idx -= 1;
                return Some(warning);
            }
        }
        None
    }

    fn clear(&mut self) {
        self.idx = 0;
    }

    fn new() -> Self {
        Self {
            t: Instant::now(),
            idx: 0,
            warnings: [1, 2, 3, 4, 5, 10, 20, 30],
        }
    }

    fn reset(&mut self) {
        self.t = Instant::now();
        self.idx = self.warnings.len();
    }
}

/// App holds the application state.
pub struct App {
    username: Username,
    addr: SocketAddr,
    /// Whether to display the help menu window
    show_help_menu: bool,
    /// Helps scroll through the help menu window if the terminal is small
    help_handle: ScrollableList,
    /// History of recorded messages
    log_handle: ScrollableList,
    /// Current value of the input box
    user_input: UserInput,
}

impl App {
    fn handle_command(
        &mut self,
        user_input: &str,
        tx_client: &Sender<ClientMessage>,
        waker: &Waker,
    ) -> Result<(), Error> {
        let result = match user_input.trim() {
            "all-in" => Ok(UserCommand::TakeAction(Action::AllIn)),
            "call" => Ok(UserCommand::TakeAction(Action::Call)),
            "check" => Ok(UserCommand::TakeAction(Action::Check)),
            "fold" => Ok(UserCommand::TakeAction(Action::Fold)),
            "play" => Ok(UserCommand::ChangeState(UserState::Play)),
            "show" => Ok(UserCommand::ShowHand),
            "spectate" => Ok(UserCommand::ChangeState(UserState::Spectate)),
            "start" => Ok(UserCommand::StartGame),
            other => {
                let other: Vec<&str> = other.split_ascii_whitespace().collect();
                match other.first() {
                    Some(&"raise") => {
                        let result = match other.get(1) {
                            // Raise with a specific amount.
                            Some(value) => match value.parse::<Usd>() {
                                Ok(amount) => Ok(Action::Raise(Some(amount))),
                                Err(_) => Err(INVALID_RAISE_MESSAGE.to_string()),
                            },
                            None => Ok(Action::Raise(None)),
                        };
                        result.map(UserCommand::TakeAction)
                    }
                    Some(&"vote") => match (other.get(1), other.get(2)) {
                        (Some(&"kick"), Some(username)) => {
                            Ok(UserCommand::CastVote(Vote::Kick(Username::new(username))))
                        }
                        (Some(&"reset"), Some(username)) => Ok(UserCommand::CastVote(Vote::Reset(
                            Some(Username::new(username)),
                        ))),
                        (Some(&"reset"), None) => Ok(UserCommand::CastVote(Vote::Reset(None))),
                        _ => Err(UNRECOGNIZED_COMMAND_MESSAGE.to_string()),
                    },
                    _ => Err(UNRECOGNIZED_COMMAND_MESSAGE.to_string()),
                }
            }
        };
        match result {
            Ok(command) => {
                let msg = ClientMessage {
                    username: self.username.clone(),
                    command,
                };
                tx_client.send(msg)?;
                waker.wake()?;
            }
            Err(message) => {
                let record = Record::new(RecordKind::Error, message);
                self.log_handle.push(record.into());
            }
        }
        Ok(())
    }

    pub fn new(addr: SocketAddr, username: Username) -> Self {
        // Fill help menu with help text lines. Also add some whitespace as
        // a jank way to add padding on the top and bottom.
        let mut help_handle = ScrollableList::new(MAX_LOG_RECORDS);
        help_handle.push("".into());
        for line in HELP.lines() {
            help_handle.push(line.into());
        }
        help_handle.push("".into());
        help_handle.jump_to_first();
        Self {
            username,
            addr,
            show_help_menu: false,
            help_handle,
            log_handle: ScrollableList::new(MAX_LOG_RECORDS),
            user_input: UserInput::new(),
        }
    }

    pub fn run(
        mut self,
        stream: TcpStream,
        mut view: GameView,
        mut terminal: DefaultTerminal,
    ) -> Result<(), Error> {
        let (tx_client, rx_client): (Sender<ClientMessage>, Receiver<ClientMessage>) = channel();
        let (tx_server, rx_server): (Sender<ServerMessage>, Receiver<ServerMessage>) = channel();

        let mut poll = Poll::new()?;
        let waker = Waker::new(poll.registry(), WAKER)?;

        // This thread is where the actual client-server networking happens for
        // non-blocking IO. Some non-blocking IO between client threads is also
        // managed by this thread. The UI thread sends client command messages
        // to this thread; those messages are eventually written to the server.
        thread::spawn(move || -> Result<(), Error> {
            let mut events = Events::with_capacity(64);
            let mut messages_to_write: VecDeque<ClientMessage> = VecDeque::new();
            stream.set_nonblocking(true)?;
            let mut stream = mio::net::TcpStream::from_std(stream);
            poll.registry()
                .register(&mut stream, SERVER, Interest::READABLE)?;

            loop {
                if let Err(error) = poll.poll(&mut events, Some(DEFAULT_POLL_TIMEOUT)) {
                    match error.kind() {
                        io::ErrorKind::Interrupted => continue,
                        _ => bail!(error),
                    }
                }

                for event in &events {
                    match event.token() {
                        SERVER => {
                            if event.is_writable() && !messages_to_write.is_empty() {
                                while let Some(msg) = messages_to_write.pop_front() {
                                    if let Err(error) =
                                        write_prefixed::<ClientMessage, mio::net::TcpStream>(
                                            &mut stream,
                                            &msg,
                                        )
                                    {
                                        match error.kind() {
                                            // `write_prefixed` uses `write_all` under the hood, so we know
                                            // that if any of these occur, then the connection was probably
                                            // dropped at some point.
                                            io::ErrorKind::BrokenPipe
                                            | io::ErrorKind::ConnectionAborted
                                            | io::ErrorKind::ConnectionReset
                                            | io::ErrorKind::TimedOut
                                            | io::ErrorKind::UnexpectedEof => {
                                                bail!("connection dropped");
                                            }
                                            // Would block "errors" are the OS's way of saying that the
                                            // connection is not actually ready to perform this I/O operation.
                                            io::ErrorKind::WouldBlock => {
                                                // The message couldn't be sent, so we need to push it back
                                                // onto the queue so we don't accidentally forget about it.
                                                messages_to_write.push_front(msg);
                                            }
                                            // Retry writing in the case that the full message couldn't
                                            // be written. This should be infrequent.
                                            io::ErrorKind::WriteZero => {
                                                messages_to_write.push_front(msg);
                                                continue;
                                            }
                                            // Other errors we'll consider fatal.
                                            _ => bail!(error),
                                        }
                                        poll.registry().reregister(
                                            &mut stream,
                                            SERVER,
                                            Interest::READABLE,
                                        )?;
                                        break;
                                    }
                                }
                            }

                            if event.is_readable() {
                                // We can (maybe) read from the connection.
                                loop {
                                    match read_prefixed::<ServerMessage, mio::net::TcpStream>(
                                        &mut stream,
                                    ) {
                                        Ok(msg) => {
                                            tx_server.send(msg)?;
                                        }
                                        Err(error) => {
                                            match error.kind() {
                                                // `read_prefixed` uses `read_exact` under the hood, so we know
                                                // that an Eof error means the connection was dropped.
                                                io::ErrorKind::BrokenPipe
                                                | io::ErrorKind::ConnectionAborted
                                                | io::ErrorKind::ConnectionReset
                                                | io::ErrorKind::InvalidData
                                                | io::ErrorKind::TimedOut
                                                | io::ErrorKind::UnexpectedEof => {
                                                    bail!("connection dropped");
                                                }
                                                // Would block "errors" are the OS's way of saying that the
                                                // connection is not actually ready to perform this I/O operation.
                                                io::ErrorKind::WouldBlock => {}
                                                // Other errors we'll consider fatal.
                                                _ => {
                                                    bail!(error)
                                                }
                                            }
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        WAKER => {
                            while let Ok(msg) = rx_client.try_recv() {
                                messages_to_write.push_back(msg);
                                poll.registry().reregister(
                                    &mut stream,
                                    SERVER,
                                    Interest::READABLE | Interest::WRITABLE,
                                )?;
                            }
                        }
                        _ => {}
                    }
                }
            }
        });

        let mut turn_warnings = TurnWarnings::new();
        loop {
            terminal.draw(|frame| self.draw(&view, frame))?;

            if event::poll(POLL_TIMEOUT)?
                && let Event::Key(KeyEvent {
                    code,
                    modifiers,
                    kind,
                    ..
                }) = event::read()?
                && kind == KeyEventKind::Press
            {
                match modifiers {
                    KeyModifiers::CONTROL => match code {
                        KeyCode::Home => self.log_handle.jump_to_first(),
                        KeyCode::End => self.log_handle.jump_to_last(),
                        _ => {}
                    },
                    KeyModifiers::NONE => match code {
                        KeyCode::Enter => {
                            let user_input = self.user_input.submit();
                            let record = Record::new(RecordKind::You, user_input.clone());
                            self.log_handle.push(record.into());
                            self.handle_command(&user_input, &tx_client, &waker)?;
                        }
                        KeyCode::Char(to_insert) => self.user_input.input(to_insert),
                        KeyCode::Backspace => self.user_input.backspace(),
                        KeyCode::Delete => self.user_input.delete(),
                        KeyCode::Left => self.user_input.move_left(),
                        KeyCode::Right => self.user_input.move_right(),
                        KeyCode::Up => {
                            if self.show_help_menu {
                                self.help_handle.move_up();
                            } else {
                                self.log_handle.move_up();
                            }
                        }
                        KeyCode::Down => {
                            if self.show_help_menu {
                                self.help_handle.move_down();
                            } else {
                                self.log_handle.move_down();
                            }
                        }
                        KeyCode::Home => self.user_input.jump_to_first(),
                        KeyCode::End => self.user_input.jump_to_last(),
                        KeyCode::Tab => self.show_help_menu = !self.show_help_menu,
                        KeyCode::Esc => return Ok(()),
                        _ => {}
                    },
                    _ => {}
                }
            }

            if let Ok(msg) = rx_server.try_recv() {
                let result = match msg {
                    ServerMessage::Ack(msg) => {
                        if msg.username == self.username {
                            match msg.command {
                                // Our action was acknowledged, so we don't need warnings anymore.
                                UserCommand::TakeAction(_) => {
                                    turn_warnings.clear();
                                }
                                // Our action timed-out and so the server booted us; let's exit.
                                UserCommand::Disconnect => return Ok(()),
                                _ => {}
                            }
                        }
                        Some(Record::new(RecordKind::Ack, msg.to_string()))
                    }
                    ServerMessage::ClientError(error) => {
                        Some(Record::new(RecordKind::Error, error.to_string()))
                    }
                    ServerMessage::GameEvent(event) => {
                        Some(Record::new(RecordKind::Game, event.to_string()))
                    }
                    ServerMessage::GameView(new_view) => {
                        view = new_view;
                        None
                    }
                    ServerMessage::Status(msg) => Some(Record::new(RecordKind::Game, msg)),
                    ServerMessage::TurnSignal(_) => {
                        turn_warnings.reset();
                        Some(Record::new(
                            RecordKind::Alert,
                            "it's your turn!".to_string(),
                        ))
                    }
                    ServerMessage::UserError(error) => {
                        Some(Record::new(RecordKind::Error, error.to_string()))
                    }
                };
                if let Some(record) = result {
                    self.log_handle.push(record.into());
                }
            }

            // Signal how much time is left to the user at specific intervals.
            if let Some(warning) = turn_warnings.check() {
                let record = Record::new(RecordKind::Alert, format!("{warning:>2} second(s) left"));
                self.log_handle.push(record.into());
            }
        }
    }

    fn draw(&mut self, view: &GameView, frame: &mut Frame) {
        let window = Layout::vertical([
            Constraint::Min(6),
            Constraint::Length(3),
            Constraint::Length(1),
        ]);
        let [top_area, user_input_area, help_area] = window.areas(frame.area());
        let [view_area, log_area] =
            Layout::vertical([Constraint::Percentage(55), Constraint::Percentage(45)])
                .areas(top_area);
        let [lobby_area, table_area] =
            Layout::horizontal([Constraint::Percentage(40), Constraint::Percentage(60)])
                .areas(view_area);
        let [spectator_area, waitlister_area] =
            Layout::horizontal([Constraint::Percentage(50), Constraint::Percentage(50)])
                .areas(lobby_area);

        // Render spectators area.
        let mut spectators = Vec::from_iter(view.spectators.iter());
        spectators.sort_unstable();
        let spectators = Table::new(
            spectators
                .iter()
                .map(|user| make_user_row(&self.username, user)),
            [Constraint::Percentage(50), Constraint::Percentage(50)],
        )
        .block(
            Block::bordered()
                .padding(Padding::uniform(1))
                .title(" spectators  "),
        );
        frame.render_widget(spectators, spectator_area);

        // Render waitlisters area.
        let waitlisters = Table::new(
            view.waitlist
                .iter()
                .map(|user| make_user_row(&self.username, user)),
            [Constraint::Percentage(50), Constraint::Percentage(50)],
        )
        .block(
            Block::bordered()
                .padding(Padding::uniform(1))
                .title(" waitlisters  "),
        );
        frame.render_widget(waitlisters, waitlister_area);

        // Render table area.
        let table = Table::new(
            view.players.iter().enumerate().map(|(player_idx, player)| {
                // Indicator if it's the player's move.
                let move_repr = if let Some(next_action_idx) = view.play_positions.next_action_idx
                    && player_idx == next_action_idx
                {
                    "→"
                } else {
                    ""
                };

                // Indicator for what blind each player pays.
                let button_repr = match player_idx {
                    idx if idx == view.play_positions.big_blind_idx => "BB",
                    idx if idx == view.play_positions.small_blind_idx => "SB",
                    _ => "",
                };

                // Username column.
                let username_repr = player.user.name.to_string();

                // Money column.
                let money_repr = format!("${}", player.user.money);

                // State column.
                let state_repr = player.state.to_string();

                // This is the final row representation for the table entry.
                let mut row = vec![
                    Cell::new(Text::from(move_repr).alignment(Alignment::Center)),
                    Cell::new(Text::from(button_repr).alignment(Alignment::Left)),
                    Cell::new(Text::from(username_repr).alignment(Alignment::Left)),
                    Cell::new(Text::from(money_repr).alignment(Alignment::Right)),
                    Cell::new(Text::from(state_repr).alignment(Alignment::Center)),
                ];

                // Player cards styled according to suit.
                for card_idx in 0..2 {
                    let card_repr = player
                        .cards
                        .get(card_idx)
                        .map_or_else(|| "".into(), make_card_span);
                    let card_cell = Cell::new(Text::from(card_repr).alignment(Alignment::Right));
                    row.push(card_cell);
                }

                // Player's highest subhand displayed.
                let hand_repr = if player.cards.is_empty() {
                    String::new()
                } else {
                    let mut cards = view.board.clone();
                    cards.extend(player.cards.clone());
                    functional::prepare_hand(&mut cards);
                    let hand = functional::eval(&cards);
                    hand.first()
                        .map_or_else(String::new, |subhand| format!("({})", subhand.rank))
                };
                let hand_cell = Cell::new(Text::from(hand_repr).alignment(Alignment::Right));
                row.push(hand_cell);

                let mut row = Row::new(row);
                if self.username == player.user.name {
                    row = row.bold().white();
                }
                row
            }),
            [
                Constraint::Max(3),
                Constraint::Fill(1),
                Constraint::Fill(2),
                Constraint::Fill(2),
                Constraint::Fill(2),
                Constraint::Fill(1),
                Constraint::Fill(1),
                Constraint::Fill(1),
            ],
        )
        .block(
            block::Block::bordered()
                .padding(Padding::uniform(1))
                .title(
                    block::Title::from(make_board_spans(view))
                        .position(block::Position::Top)
                        .alignment(Alignment::Left),
                )
                .title(
                    block::Title::from(format!(" blinds: {}  ", view.blinds))
                        .position(block::Position::Bottom)
                        .alignment(Alignment::Right),
                )
                .title(
                    block::Title::from(format!(" pot: {}  ", view.pot))
                        .position(block::Position::Bottom)
                        .alignment(Alignment::Left),
                ),
        );
        frame.render_widget(table, table_area);

        // Render log window.
        let log_records = self.log_handle.list_items.clone();
        let log_records = List::new(log_records)
            .direction(ListDirection::BottomToTop)
            .block(block::Block::bordered().title(" history  "));
        frame.render_stateful_widget(log_records, log_area, &mut self.log_handle.list_state);

        // Render log window scrollbar.
        frame.render_stateful_widget(
            Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .symbols(scrollbar::VERTICAL)
                .begin_symbol(None)
                .end_symbol(None),
            log_area.inner(Margin {
                vertical: 1,
                horizontal: 1,
            }),
            &mut self.log_handle.scroll_state,
        );

        // Render user input area.
        let username = self.username.clone();
        let user_input = Paragraph::new(self.user_input.value.as_str())
            .style(Style::default())
            .block(
                block::Block::bordered()
                    .title(format!(" {username}@{}  ", self.addr).light_green()),
            );
        frame.render_widget(user_input, user_input_area);
        frame.set_cursor_position(Position::new(
            // Draw the cursor at the current position in the input field.
            // This position is can be controlled via the left and right arrow key
            user_input_area.x + self.user_input.char_idx as u16 + 1,
            // Move one line down, from the border to the input line
            user_input_area.y + 1,
        ));

        // Render user input help message.
        let help_message = vec![
            "press ".into(),
            "Tab".bold().white(),
            " to view help, press ".into(),
            "Enter".bold().white(),
            " to record a command, or press ".into(),
            "Esc".bold().white(),
            " to exit".into(),
        ];
        let help_message = Paragraph::new(Line::from(help_message));
        frame.render_widget(help_message, help_area);

        // Render the help menu.
        if self.show_help_menu {
            let vertical = Layout::vertical([Constraint::Max(29)]).flex(Flex::Center);
            let horizontal = Layout::horizontal([Constraint::Max(92)]).flex(Flex::Center);
            let [help_menu_area] = vertical.areas(frame.area());
            let [help_menu_area] = horizontal.areas(help_menu_area);
            frame.render_widget(Clear, help_menu_area); // clears out the background

            // Render help text.
            let help_items = self.help_handle.list_items.clone();
            let help_items = List::new(help_items)
                .direction(ListDirection::BottomToTop)
                .block(block::Block::bordered().title(" commands  "));
            frame.render_stateful_widget(
                help_items,
                help_menu_area,
                &mut self.help_handle.list_state,
            );

            // Render help scrollbar.
            frame.render_stateful_widget(
                Scrollbar::new(ScrollbarOrientation::VerticalRight)
                    .symbols(scrollbar::VERTICAL)
                    .begin_symbol(None)
                    .end_symbol(None),
                help_menu_area.inner(Margin {
                    vertical: 1,
                    horizontal: 1,
                }),
                &mut self.help_handle.scroll_state,
            );
        }
    }
}