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
|
use std::{sync::{Arc, Mutex}, io::{stdout, Stdout}, fs::{File, OpenOptions}};
use bevy::{prelude::*, utils::{HashSet, Uuid, HashMap, tracing::{subscriber, level_filters::LevelFilter}}, log::tracing_subscriber};
use crossterm::{event::{Event, KeyCode, EnableMouseCapture, PushKeyboardEnhancementFlags, KeyboardEnhancementFlags}, terminal::{EnterAlternateScreen, enable_raw_mode}, ExecutableCommand};
use ratatui::{backend::CrosstermBackend, Frame, layout::Rect};
use crate::events::TerminalInputEvent;
#[derive(Resource, Default)]
pub struct TerminalInput {
pressed_keys: HashSet<KeyCode>,
released_keys: HashSet<KeyCode>,
}
impl TerminalInput {
pub fn is_pressed(&self, code: KeyCode) -> bool {
self.pressed_keys.contains(&code)
}
pub fn is_released(&self, code: KeyCode) -> bool {
self.released_keys.contains(&code)
}
pub(super) fn press(&mut self, code: KeyCode) {
if !self.is_pressed(code) {
self.pressed_keys.insert(code);
}
}
pub(super) fn release(&mut self, code: KeyCode) {
if self.is_pressed(code) {
self.pressed_keys.remove(&code);
}
if !self.is_released(code) {
self.released_keys.insert(code);
}
}
}
#[derive(Resource, Default)]
pub(super) struct EventQueue(pub(super) Arc<Mutex<Vec<Event>>>);
#[derive(Resource)]
pub struct Terminal(pub ratatui::Terminal<CrosstermBackend<Stdout>>);
impl Default for Terminal {
fn default() -> Self {
stdout().execute(EnterAlternateScreen).unwrap();
stdout().execute(EnableMouseCapture).unwrap();
stdout().execute(PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::REPORT_EVENT_TYPES)).unwrap();
enable_raw_mode().unwrap();
let mut terminal = ratatui::Terminal::new(CrosstermBackend::new(stdout())).expect("Failed to create terminal");
terminal.clear().expect("Failed to clear terminal");
Self(terminal)
}
}
#[derive(Resource, Default)]
pub struct TerminalUI {
widgets: HashMap<Uuid, Box<dyn TerminalWidget + Sync + Send>>
}
impl TerminalUI {
pub fn insert_widget(&mut self, widget: Box<dyn TerminalWidget + Sync + Send>) -> Uuid {
let id = Uuid::new_v4();
self.widgets.insert(id, widget);
id
}
pub fn get_widget(&mut self, id: Uuid) -> Option<&mut Box<dyn TerminalWidget + Sync + Send>> {
self.widgets.get_mut(&id)
}
pub fn destroy_widget(&mut self, id: Uuid) {
self.widgets.remove(&id);
}
pub fn widgets(&mut self) -> Vec<&mut Box<dyn TerminalWidget + Sync + Send>> {
let mut vec = self.widgets.values_mut().collect::<Vec<_>>();
vec.sort_by(|a, b| { a.depth().cmp(&b.depth()).reverse() });
vec
}
}
pub trait TerminalWidget {
fn init(&mut self) {}
fn update(&mut self) {}
fn render(&mut self, frame: &mut Frame, rect: Rect);
fn handle_events(&mut self, _event: &TerminalInputEvent, commands: &mut Commands) {}
fn depth(&self) -> u32 { 0 }
}
|