mcserver 0.3.3

Minecraft Multiplexer
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
use std::{future::pending, io::IsTerminal, mem, path::PathBuf};

use crossterm::event::{Event, EventStream, KeyCode, KeyEvent, KeyModifiers};
use futures::{StreamExt, future::Either};
use kdl::KdlDocument;
use miette::{Context, IntoDiagnostic, bail};
use ratatui::{
    DefaultTerminal, Frame,
    layout::{Constraint, Layout},
    style::{Color, Style, Stylize},
    widgets::{Block, Borders, List, ListItem, Paragraph, Wrap},
};
use tokio::{
    io::{self, AsyncReadExt, AsyncWriteExt},
    pin,
    time::sleep,
};

use crate::{
    core::{ClientMessage, Config, LineBuffer, ServerMessage, config, display_bytes},
    read_message, servers, write_message,
};

#[derive(Debug)]
enum ServerState {
    Normal,
    Escaping,
    Dead,
}

#[derive(Debug)]
enum Mode {
    Selecting,
    Console {
        attached_server: usize,
        name: String,
        input: String,
        output: LineBuffer,
        state: ServerState,
        blink: bool,
    },
}

impl Mode {
    fn output(index: usize, name: String) -> Self {
        Self::Console {
            attached_server: index,
            name,
            input: String::new(),
            output: LineBuffer::new(),
            state: ServerState::Normal,
            blink: false,
        }
    }
}

#[allow(dead_code)]
pub struct App {
    config: Config,
    mode: Mode,
    document: Option<KdlDocument>,
    servers: Vec<String>,
    selected_server: usize,
    exiting: bool,
}

#[macro_export]
macro_rules! stderr_log {
    ($($arg:tt)*) => {{
        #[cfg(debug_assertions)]
        if !std::io::stderr().is_terminal() {
            eprintln!($($arg)*);
        }
    }};
}

macro_rules! try_attach {
    ($app:ident, $writer:expr) => {{
        let name = $app
            .servers
            .get($app.selected_server)
            .wrap_err("Invalid server index")?
            .clone();

        $app.request_attach($writer, name.clone())
            .await
            .into_diagnostic()
            .wrap_err("Failed to attach to server")?;

        $app.mode = Mode::output($app.selected_server, name);
    }};
}

impl App {
    pub async fn try_new() -> miette::Result<Self> {
        let (config, document) = config::read()
            .await
            .into_diagnostic()
            .wrap_err("Failed to create/read config")?;

        stderr_log!("{config:?}");

        let servers = servers::read(config.servers_directory.as_ref())
            .await?
            .into_iter()
            .map(PathBuf::into_string)
            .collect::<Result<Vec<String>, PathBuf>>()
            // TODO: put question mark symbols where there is non utf-8 data
            .map_err(crate::core::Error::NonUtf8Path)
            .into_diagnostic()?;

        Ok(Self {
            config,
            document,
            servers,
            selected_server: 0usize,
            mode: Mode::Selecting,
            exiting: false,
        })
    }

    pub async fn request_attach(
        &self,
        mut writer: impl AsyncWriteExt + Unpin,
        server_name: impl Into<String>,
    ) -> io::Result<()> {
        let name = server_name.into();
        write_message!(writer, ClientMessage::Attach { name: name.clone() }).await
    }

    pub async fn handle_keycode(
        &mut self,
        key: KeyEvent,
        mut writer: impl AsyncWriteExt + Unpin,
    ) -> miette::Result<()> {
        match &mut self.mode {
            Mode::Selecting => match key.code {
                KeyCode::Enter => {
                    try_attach!(self, writer);
                }
                // KeyCode::Left | KeyCode::Char('h') => self.selection_left(),
                // KeyCode::Right | KeyCode::Char('l') => self.selection_right(),
                KeyCode::Up | KeyCode::Char('k') => self.selection_up(),
                KeyCode::Down | KeyCode::Char('j') => self.selection_down(),

                // TODO: these should actually by different from left and right
                KeyCode::Tab => todo!("Implement tab"),
                KeyCode::BackTab => todo!("Implement back tab"),

                // KeyCode::Esc => self.exit(),
                KeyCode::Char(ch) => match ch {
                    'q' => self.exit(),
                    'd' => todo!("Implement deletion"),
                    'u' => todo!("Implement manual server list updation"),
                    _ => {}
                },
                _ => {}
            },

            Mode::Console {
                state: ServerState::Dead,
                ..
            } => match key.code {
                KeyCode::Esc | KeyCode::Enter | KeyCode::Tab | KeyCode::BackTab => {
                    self.selection_mode()
                }
                _ => {}
            },

            // Escaping output
            Mode::Console { name, state, .. } if let ServerState::Escaping = state => {
                match key.code {
                    KeyCode::Backspace => todo!(),
                    KeyCode::Enter => {
                        let Some(selected_server) = self.servers.get(self.selected_server) else {
                            // TODO: ig this is an error
                            return Ok(());
                        };

                        *state = ServerState::Normal;

                        if name != selected_server {
                            try_attach!(self, writer);
                        }
                    }
                    KeyCode::Up | KeyCode::Char('k') => self.selection_up(),
                    KeyCode::Down | KeyCode::Char('j') => self.selection_down(),

                    KeyCode::Tab => {
                        *state = ServerState::Normal;
                    }

                    KeyCode::BackTab => self.selection_mode(),

                    KeyCode::Char('q') => self.exit(),

                    KeyCode::Delete => todo!(),
                    KeyCode::Insert => todo!(),
                    KeyCode::F(_) => todo!(),
                    KeyCode::Char(_) => todo!(),
                    KeyCode::Null => todo!(),
                    KeyCode::Esc => self.selection_mode(),
                    _ => {}
                }
            }

            Mode::Console { input, state, .. } => match key.code {
                KeyCode::Backspace => {
                    input.pop();
                }
                KeyCode::Enter => {
                    input.push('\n');

                    write_message!(
                        writer,
                        ClientMessage::ProgramInput(mem::take(input).into_bytes())
                    )
                    .await
                    .into_diagnostic()
                    .wrap_err("Failed to send input to the server")?
                }
                KeyCode::Left => todo!("Implement cursor left"),
                KeyCode::Right => todo!("Implement cursor right"),
                KeyCode::Tab => write_message!(writer, ClientMessage::ProgramInput(vec![b'\t']))
                    .await
                    .into_diagnostic()
                    .wrap_err("Failed to send tab to server")?,
                KeyCode::BackTab => {
                    *state = ServerState::Escaping;
                }
                KeyCode::Delete => todo!("Implement deletion"),
                // KeyCode::F(_) => todo!(),
                KeyCode::Char(ch) => {
                    if key.modifiers.contains(KeyModifiers::CONTROL) {
                        write_message!(
                            writer,
                            ClientMessage::ProgramInput(vec![(ch as u8) - b'a' + 1])
                        )
                        .await
                        .into_diagnostic()?;
                    } else {
                        input.push(ch);
                    }
                }
                KeyCode::Esc => {
                    *state = ServerState::Escaping;
                }
                _ => {}
            },
        };

        Ok(())
    }

    pub async fn run(
        &mut self,
        terminal: &mut DefaultTerminal,
        (mut reader, mut writer): (impl AsyncReadExt + Unpin, impl AsyncWriteExt + Unpin),
    ) -> miette::Result<()> {
        let mut event_reader = EventStream::new();

        let blink_event = if let Some(blink_interval) = self.config.blink_interval {
            Either::Left(sleep(blink_interval))
        } else {
            Either::Right(pending())
        };

        pin!(blink_event);

        loop {
            if self.exiting {
                writer
                    .shutdown()
                    .await
                    .into_diagnostic()
                    .wrap_err("Failed to send shutdown packet")?;
                break Ok(());
            }

            terminal
                .draw(|frame| self.render(frame))
                .into_diagnostic()
                .wrap_err("Failed to render tui")?;

            tokio::select! {
                    event = &mut event_reader.next() => {
                        let Some(event) = event else {
                            bail!("Failed to read from terminal");
                        };

                        let Event::Key(key) = event.into_diagnostic().wrap_err("Failed to read key input")? else {
                            // only care about those keys!!
                            continue;
                        };

                        self.handle_keycode(key, &mut writer).await?;
                    }

                    _ = &mut blink_event => {
                        blink_event.set(if let Some(blink_interval) = self.config.blink_interval {
                            Either::Left(sleep(blink_interval))
                        } else {
                            Either::Right(pending())
                        });

                        if let Mode::Console { blink, .. } = &mut self.mode {
                            *blink = !*blink;
                        }
                    }

                    length = reader.read_u32() => {
                        let length = match length {
                            Ok(length) => length,
                            Err(err) => match err.kind() {
                                io::ErrorKind::UnexpectedEof => {
                                    stderr_log!("Server closed");
                                    return Err(err).into_diagnostic().wrap_err("Server connection severed");
                                },
                                _ => return Err(err).into_diagnostic(),
                            },
                        };

                        match read_message!(reader, length).await.into_diagnostic().wrap_err("Failed to receive message from server")? {
                            ServerMessage::KillFailure(err) => stderr_log!("Failed to kill child: {err}"),
                            ServerMessage::KillSuccess => stderr_log!("Successfully killed the child process"),
                            ServerMessage::Closed => if let Mode::Console { input, state, .. } = &mut self.mode {
                                *input = "Press enter to return...".to_string();
                                *state = ServerState::Dead;
                            },
                            ServerMessage::Message(message) => {
                                stderr_log!("Received a message from the server: {message}");
                            },
                            ServerMessage::AlreadyStarted => {
                                stderr_log!("The server has already started apparently");
                            },
                            ServerMessage::NotAttached => {
                                stderr_log!("The server has not yet started apparently");
                            },
                            ServerMessage::Output(bytes) => if let Mode::Console { output, .. } = &mut self.mode {
                                output.push(display_bytes(&bytes).to_string());
                            },
                            ServerMessage::History(history) => if let Mode::Console { output, .. } = &mut self.mode {
                                history.into_iter().for_each(|line|{
                                    output.push(display_bytes(&line).to_string())
                                });
                            }
                        }
                    }
            }
        }
    }

    pub async fn run_attached(
        &mut self,
        terminal: &mut DefaultTerminal,
        (reader, mut writer): (impl AsyncReadExt + Unpin, impl AsyncWriteExt + Unpin),
        name: String,
    ) -> miette::Result<()> {
        self.selected_server = self
            .servers
            .iter()
            .position(|server| *server == name)
            .wrap_err("Server not found")?;

        try_attach!(self, &mut writer);

        self.run(terminal, (reader, writer)).await
    }

    fn draw_servers_list_widget(&self) -> List<'_> {
        let servers_iter = self.servers.iter().enumerate();

        if let Mode::Console {
            attached_server, ..
        } = self.mode
        {
            List::new(servers_iter.map(|(idx, name)| {
                let item = if idx == self.selected_server {
                    ListItem::from(format!("> {name}")).bold()
                } else {
                    ListItem::from(format!("  {name}"))
                };

                if idx == attached_server {
                    item.fg(Color::Black).bg(Color::White)
                } else {
                    item
                }
            }))
        } else {
            List::new(servers_iter.map(|(idx, name)| {
                if idx == self.selected_server {
                    ListItem::from(format!("> {name}")).bold()
                } else {
                    ListItem::from(format!("  {name}"))
                }
            }))
        }
        // List::new(self.servers.iter().enumerate().map(|(idx, name)| {
        //     ListItem::new(if idx == self.selected_server {
        //         Text::styled(format!("> {name}"), Style::new().bold())
        //     } else {
        //         Text::raw(format!("  {name}"))
        //     })
        // }))
        .block(Block::new().title("Servers").borders(Borders::ALL))
    }

    fn render(&self, frame: &mut Frame) {
        // Hella dark:
        // 26, 27, 38
        //
        // 30, 31, 42
        //
        // Very light, neutral, middle ground, valid color
        // 46, 52, 64

        if let Some(background_color) = self.config.terminal_interface_config.background_color {
            let background_block = Block::new().style(Style::new().bg(background_color));

            frame.render_widget(background_block, frame.area());
        }

        let Mode::Console {
            input,
            output,
            state,
            blink,
            ..
        } = &self.mode
        else {
            frame.render_widget(self.draw_servers_list_widget(), frame.area());
            return;
        };

        let output_area = if matches!(state, ServerState::Escaping) {
            let main_sections = Layout::horizontal([Constraint::Length(30), Constraint::Fill(1)])
                .split(frame.area());

            frame.render_widget(self.draw_servers_list_widget(), main_sections[0]);

            main_sections[1]
        } else {
            frame.area()
        };

        let output_text_width = output_area.width.saturating_sub(2) as usize;
        let output_lines_available = output_area.height.saturating_sub(2) as usize;

        // mono
        // negro
        // ------------
        // yes
        // sir
        // man
        // yesman

        let mut output_text = output
            .iter()
            // use skip here to get the maximum number of lines that might need to be used
            // Then, the lines that aren't used will simply not be rendered
            .skip(output.len().saturating_sub(output_lines_available))
            .fold(String::new(), |mut acc, item| {
                acc.push_str(item);
                // acc.push('\n');
                acc
            });

        output_text.push_str(input);

        if *blink {
            output_text.push('█');
        }

        let lines = output_text
            .split('\n')
            .flat_map(|line| textwrap::wrap(line, output_text_width))
            .count();

        let output_widget = Paragraph::new(output_text)
            .block(Block::new().title("Console").borders(Borders::ALL))
            .wrap(Wrap { trim: false })
            .scroll((lines.saturating_sub(output_lines_available) as u16, 0));

        frame.render_widget(output_widget, output_area);
    }

    fn selection_mode(&mut self) {
        self.mode = Mode::Selecting;
    }

    fn selection_up(&mut self) {
        self.selected_server = self.selected_server.saturating_sub(1);
    }

    fn selection_down(&mut self) {
        self.selected_server = usize::min(self.selected_server + 1, self.servers.len() - 1);
    }

    pub fn exit(&mut self) {
        self.exiting = true;
    }
}