use glam::Vec2;
use crate::draw_list::DrawList;
use crate::edit::{Edit, Motion};
use crate::font::Font;
use crate::menu::MenuStyle;
use crate::style::{Declaration, SheetId, Sides};
use crate::text::FontAtlas;
use crate::tree::{
AvailableSpace, Behavior, ClipboardRequest, Length, LengthAuto, NodeKey, Position, TextInput,
TextInputOptions, Ui,
};
use crate::widget::{ButtonState, NATURAL_FONT_SIZE, PointerInput, UiState, WidgetId};
use super::keyboard::{KeyCap, KeyboardLayout, TouchKeyboard};
use super::{ConsoleStyle, LogView};
pub const CONSOLE_HEIGHT_FRACTION: f32 = 0.45;
pub const COMPLETION_ROWS: usize = 8;
pub const PROMPT: &str = "] ";
pub const SEND_LABEL: &str = "SEND";
pub const SEND_ID: WidgetId = WidgetId::MAX;
const WARM_UP_EXTENT: Vec2 = Vec2::new(960.0, 720.0);
pub const MINIMUM_LOG_ROWS: usize = 6;
pub const MINIMUM_FIELD_COLUMNS: usize = 24;
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ConsoleInput {
Nothing,
Submitted(String),
Key(KeyCap),
Picked(usize),
}
#[derive(Debug)]
pub struct ConsolePanel {
ui: Ui,
line: String,
log: LogView,
prefix: String,
candidates: Vec<String>,
queued: Vec<Edit>,
send: ButtonState,
send_clicked: bool,
picked: Option<usize>,
field_key: Option<NodeKey>,
editing: bool,
sheet: SheetId,
sheet_scale: f32,
keyboard: TouchKeyboard,
keyboard_shown: bool,
}
impl ConsolePanel {
#[must_use]
pub fn new() -> Self {
let style = ConsoleStyle::pixel_art(1);
let mut ui = Ui::new();
let sheet = ui.add_stylesheet("crcbl-ui console", &scale_sheet(&style));
let mut panel = Self {
ui,
line: String::new(),
log: LogView::new(),
prefix: String::new(),
candidates: Vec::new(),
queued: Vec::new(),
send: ButtonState::Idle,
send_clicked: false,
picked: None,
field_key: None,
editing: false,
sheet,
sheet_scale: style.scale,
keyboard: TouchKeyboard::new(),
keyboard_shown: false,
};
let atlas = FontAtlas::built_in();
panel.ui.begin_frame(PointerInput::default());
panel.ui.set_text_input(TextInput::default());
let field = {
let Self {
ui,
line,
log,
prefix,
candidates,
..
} = &mut panel;
let built = build(
ui,
line,
log,
prefix,
candidates,
WARM_UP_EXTENT,
&style,
&atlas,
);
ui.layout(Vec2::ZERO, AvailableSpace::definite(WARM_UP_EXTENT), &atlas);
built.field
};
panel.ui.engage(field);
panel.field_key = Some(field);
panel.editing = panel.ui.text_editing();
panel
}
#[must_use]
pub const fn keyboard(&self) -> &TouchKeyboard {
&self.keyboard
}
#[must_use]
pub const fn keyboard_shown(&self) -> bool {
self.keyboard_shown
}
pub const fn show_keyboard(&mut self, shown: bool) {
self.keyboard_shown = shown;
}
#[must_use]
pub fn line(&self) -> &str {
&self.line
}
pub fn set_line(&mut self, text: &str) {
self.line.clear();
self.line.push_str(text);
self.edit(Edit::Move {
motion: Motion::End,
select: false,
});
}
pub fn edit(&mut self, edit: Edit) {
self.queued.push(edit);
}
#[must_use]
pub const fn is_editing(&self) -> bool {
self.editing
}
#[must_use]
pub const fn log(&self) -> &LogView {
&self.log
}
pub const fn log_mut(&mut self) -> &mut LogView {
&mut self.log
}
#[must_use]
pub const fn send_state(&self) -> ButtonState {
self.send
}
#[must_use]
pub fn candidates(&self) -> &[String] {
&self.candidates
}
#[must_use]
pub fn completion_prefix(&self) -> &str {
&self.prefix
}
pub fn set_completion(&mut self, prefix: &str, candidates: &[&str]) {
self.prefix.clear();
self.prefix.push_str(prefix);
self.candidates.clear();
self.candidates
.extend(candidates.iter().map(|name| (*name).to_owned()));
}
pub fn clear_completion(&mut self) {
self.prefix.clear();
self.candidates.clear();
}
pub fn submit(&mut self) -> Option<String> {
let line = std::mem::take(&mut self.line);
self.clear_completion();
self.log.scroll_to_bottom();
if line.trim().is_empty() {
return None;
}
Some(line)
}
pub fn set_fallback_fonts(&mut self, fonts: impl IntoIterator<Item = impl Into<Font>>) {
self.ui.set_fallback_fonts(fonts);
}
pub fn take_clipboard_requests(&mut self) -> Vec<ClipboardRequest> {
self.ui.take_clipboard_requests()
}
#[must_use]
pub fn text_input_area(&self) -> Option<(Vec2, Vec2)> {
self.ui.text_input_area()
}
pub fn point(
&mut self,
layout: &ConsoleLayout,
ui: &mut UiState,
pointer: PointerInput,
) -> ConsoleInput {
if std::mem::take(&mut self.send_clicked) {
return self
.submit()
.map_or(ConsoleInput::Nothing, ConsoleInput::Submitted);
}
if let Some(index) = self.picked.take() {
return ConsoleInput::Picked(index);
}
if !self.keyboard_shown {
return ConsoleInput::Nothing;
}
match self.keyboard.point(layout.keyboard(), ui, pointer) {
None => ConsoleInput::Nothing,
Some(KeyCap::Enter) => self
.submit()
.map_or(ConsoleInput::Nothing, ConsoleInput::Submitted),
Some(cap) => ConsoleInput::Key(cap),
}
}
pub fn layout(
&mut self,
extent: (u32, u32),
atlas: &FontAtlas,
pointer: PointerInput,
input: TextInput,
) -> ConsoleLayout {
let screen = Vec2::new(extent.0 as f32, extent.1 as f32);
let mut chosen = ConsoleStyle::pixel_art(1);
for scale in 2..=MenuStyle::MAX_SCALE {
let style = ConsoleStyle::pixel_art(scale);
if fits(screen, atlas, &style) {
chosen = style;
} else {
break;
}
}
self.layout_with(extent, atlas, &chosen, pointer, input)
}
pub fn layout_with(
&mut self,
extent: (u32, u32),
atlas: &FontAtlas,
style: &ConsoleStyle,
pointer: PointerInput,
input: TextInput,
) -> ConsoleLayout {
let screen = Vec2::new(extent.0 as f32, extent.1 as f32);
if style.scale != self.sheet_scale {
if let Err(errors) = self.ui.replace_stylesheet(self.sheet, &scale_sheet(style)) {
crcbl_core::warn!("console: its own stylesheet did not parse: {errors:?}");
} else {
self.sheet_scale = style.scale;
}
}
self.ui.begin_frame(pointer);
self.queued.extend(input.edits);
let engaged = self
.field_key
.is_some_and(|key| self.ui.engaged() == Some(key));
let edits = if engaged {
std::mem::take(&mut self.queued)
} else {
Vec::new()
};
self.ui.set_text_input(TextInput {
dt: input.dt,
edits,
clipboard: input.clipboard,
preedit: input.preedit,
extend: input.extend,
});
let built = {
let Self {
ui,
line,
log,
prefix,
candidates,
..
} = self;
let built = build(ui, line, log, prefix, candidates, screen, style, atlas);
ui.layout(Vec2::ZERO, AvailableSpace::definite(screen), atlas);
built
};
if self.ui.engaged() != Some(built.field) {
self.ui.engage(built.field);
}
self.field_key = Some(built.field);
self.editing = self.ui.text_editing();
self.send = built.send_state;
self.send_clicked = built.send_clicked;
self.picked = built.picked;
let rect = |key| self.ui.rect(key).expect("laid out this frame");
let keyboard = if self.keyboard_shown {
self.keyboard.layout(screen)
} else {
KeyboardLayout::default()
};
ConsoleLayout {
style: *style,
screen,
panel: rect(built.panel),
log: rect(built.log),
field: rect(built.field_well),
prompt_pos: rect(built.prompt).0,
text_pos: rect(built.field).0,
input_right: rect(built.field).1.x,
send: rect(built.send),
completion: built.candidates.iter().copied().map(rect).collect(),
keyboard,
}
}
pub fn render(&self, dl: &mut DrawList, layout: &ConsoleLayout, atlas: &FontAtlas) {
self.ui.emit(dl);
if self.keyboard_shown {
self.keyboard
.render(dl, layout.keyboard(), atlas, layout.style());
}
}
}
impl Default for ConsolePanel {
fn default() -> Self {
Self::new()
}
}
struct Built {
panel: NodeKey,
log: NodeKey,
field_well: NodeKey,
field: NodeKey,
prompt: NodeKey,
send: NodeKey,
candidates: Vec<NodeKey>,
send_state: ButtonState,
send_clicked: bool,
picked: Option<usize>,
}
#[expect(
clippy::too_many_arguments,
reason = "the panel's fields, split so the tree and the line can be borrowed apart"
)]
fn build(
ui: &mut Ui,
line: &mut String,
log: &LogView,
prefix: &str,
candidates: &[String],
screen: Vec2,
style: &ConsoleStyle,
atlas: &FontAtlas,
) -> Built {
use Declaration as D;
let px = LengthAuto::Px;
let pad = style.padding;
let row = style.row_height();
let panel_height = (screen.y * CONSOLE_HEIGHT_FRACTION).round();
let screen_style = [
D::Width(px(screen.x)),
D::Height(px(screen.y)),
D::FontSize(style.text_size),
];
let panel_style = [
D::Width(LengthAuto::Percent(1.0)),
D::Height(px(panel_height)),
D::Padding(Sides::Top, Length::Px(pad.y)),
D::Padding(Sides::Bottom, Length::Px(pad.y)),
D::Padding(Sides::Left, Length::Px(pad.x)),
D::Padding(Sides::Right, Length::Px(pad.x)),
D::BorderWidth(Sides::Bottom, style.scale),
D::RowGap(Length::Px(pad.y)),
D::Background(style.panel_color),
D::BorderColor(style.border_color),
];
let well_style = [
D::Padding(Sides::Top, Length::Px(pad.y)),
D::Padding(Sides::Bottom, Length::Px(pad.y)),
D::Padding(Sides::Left, Length::Px(pad.x)),
D::Padding(Sides::Right, Length::Px(pad.x)),
D::BorderWidth(Sides::All, style.scale),
D::Background(style.field_color),
D::BorderColor(style.border_color),
];
let send_style = [
D::Padding(Sides::Top, Length::Px(pad.y)),
D::Padding(Sides::Bottom, Length::Px(pad.y)),
D::Padding(Sides::Left, Length::Px(pad.x)),
D::Padding(Sides::Right, Length::Px(pad.x)),
D::BorderWidth(Sides::All, style.scale),
D::Margin(Sides::Left, px(pad.x)),
];
let advance = style.advance(atlas);
let columns = if advance > 0.0 {
((screen.x - 2.0 * pad.x) / advance).max(0.0) as usize
} else {
0
};
let rows = if row > 0.0 {
(panel_height / row).max(0.0) as usize + 1
} else {
0
};
let visible = log.visible_rows(rows, columns);
let mut panel_key = None;
let mut log_key = None;
let mut well_key = None;
let mut input_key = None;
let mut prompt_key = None;
let mut send_key = None;
let mut rows_built = Vec::new();
let mut send_state = ButtonState::Idle;
let mut send_clicked = false;
let mut picked = None;
ui.block("console-screen", &screen_style, |ui| {
panel_key = Some(
ui.block("console", &panel_style, |ui| {
log_key = Some(
ui.block(".console-log", &[], |ui| {
for (level, text) in &visible {
ui.span(
".console-line",
text.as_str(),
&[D::Color(style.level_color(*level))],
);
}
})
.key,
);
ui.block(".console-row", &[], |ui| {
well_key = Some(
ui.block(".console-field", &well_style, |ui| {
prompt_key = Some(
ui.span(".console-prompt", PROMPT, &[D::Color(style.prompt_color)])
.key,
);
let options = TextInputOptions {
keep_caret: true,
..TextInputOptions::default()
};
input_key =
Some(ui.text_input_with(".console-input", line, options).key);
})
.key,
);
let send =
ui.block_with("button.console-send", &send_style, Behavior::BUTTON, |ui| {
ui.span(".button-label", SEND_LABEL, &[]);
});
send_key = Some(send.key);
send_clicked = send.clicked;
send_state = if send.pressed {
ButtonState::Pressed
} else if send.hovered {
ButtonState::Hovered
} else {
ButtonState::Idle
};
});
})
.key,
);
let fits = if row > 0.0 {
((screen.y - panel_height) / row).max(0.0) as usize
} else {
0
};
let count = candidates.len().min(COMPLETION_ROWS).min(fits);
if count == 0 {
return;
}
let left = (text_inset(atlas, style) - pad.x).max(0.0);
let list_style = [
D::Position(Position::Absolute),
D::Inset(Sides::Top, px(panel_height)),
D::Inset(Sides::Left, px(left)),
D::MaxWidth(px((screen.x - left).max(0.0))),
D::Background(style.completion_color),
];
let candidate_style = [
D::Height(px(row)),
D::Padding(Sides::Left, Length::Px(pad.x)),
D::Padding(Sides::Right, Length::Px(pad.x)),
];
let matched = prefix.chars().count();
ui.block(".console-completion", &list_style, |ui| {
for (index, candidate) in candidates[..count].iter().enumerate() {
let head: String = candidate.chars().take(matched).collect();
let tail: String = candidate.chars().skip(matched).collect();
let candidate_row = ui.block_keyed_with(
index,
".console-candidate",
&candidate_style,
Behavior::BUTTON,
|ui| {
if !head.is_empty() {
ui.span(
".console-match",
head.as_str(),
&[D::Color(style.match_color)],
);
}
if !tail.is_empty() {
ui.span(
".console-tail",
tail.as_str(),
&[D::Color(style.candidate_color)],
);
}
},
);
if candidate_row.clicked {
picked = Some(index);
}
rows_built.push(candidate_row.key);
}
});
});
Built {
panel: panel_key.expect("the screen builds its panel"),
log: log_key.expect("the panel builds its log"),
field_well: well_key.expect("the input row builds its well"),
field: input_key.expect("the well builds its input"),
prompt: prompt_key.expect("the well builds its prompt"),
send: send_key.expect("the input row builds its button"),
candidates: rows_built,
send_state,
send_clicked,
picked,
}
}
fn text_inset(atlas: &FontAtlas, style: &ConsoleStyle) -> f32 {
2.0f32.mul_add(
style.padding.x,
style.scale + atlas.text_width(PROMPT, style.text_size / NATURAL_FONT_SIZE),
)
}
fn probe(screen: Vec2, atlas: &FontAtlas, style: &ConsoleStyle) -> (usize, usize) {
let pad = style.padding;
let row = style.row_height();
let advance = style.advance(atlas);
if row <= 0.0 || advance <= 0.0 {
return (0, 0);
}
let glyphs = style.text_size / NATURAL_FONT_SIZE;
let panel_height = (screen.y * CONSOLE_HEIGHT_FRACTION).round();
let input_row = 2.0f32.mul_add(pad.y + style.scale, row);
let log_height = panel_height - 3.0 * pad.y - style.scale - input_row;
let rows = (log_height / row).max(0.0) as usize;
let send = atlas.text_width(SEND_LABEL, glyphs) + 2.0 * (pad.x + style.scale);
let well = screen.x - 3.0 * pad.x - send;
let input = well - 2.0 * (pad.x + style.scale) - atlas.text_width(PROMPT, glyphs);
let columns = (input / advance).max(0.0) as usize;
(rows, columns)
}
fn fits(screen: Vec2, atlas: &FontAtlas, style: &ConsoleStyle) -> bool {
let (rows, columns) = probe(screen, atlas, style);
rows >= MINIMUM_LOG_ROWS && columns >= MINIMUM_FIELD_COLUMNS
}
fn scale_sheet(style: &ConsoleStyle) -> String {
format!(
"text-input.console-input > .text-input-caret {{ width: {}px; }}\n",
style.caret_width,
)
}
#[derive(Debug, Clone, PartialEq)]
pub struct ConsoleLayout {
style: ConsoleStyle,
screen: Vec2,
panel: (Vec2, Vec2),
log: (Vec2, Vec2),
field: (Vec2, Vec2),
prompt_pos: Vec2,
text_pos: Vec2,
input_right: f32,
send: (Vec2, Vec2),
completion: Vec<(Vec2, Vec2)>,
keyboard: KeyboardLayout,
}
impl ConsoleLayout {
#[must_use]
pub const fn style(&self) -> &ConsoleStyle {
&self.style
}
#[must_use]
pub const fn screen(&self) -> Vec2 {
self.screen
}
#[must_use]
pub const fn panel(&self) -> (Vec2, Vec2) {
self.panel
}
#[must_use]
pub const fn log(&self) -> (Vec2, Vec2) {
self.log
}
#[must_use]
pub const fn field(&self) -> (Vec2, Vec2) {
self.field
}
#[must_use]
pub const fn prompt_pos(&self) -> Vec2 {
self.prompt_pos
}
#[must_use]
pub const fn text_pos(&self) -> Vec2 {
self.text_pos
}
#[must_use]
pub const fn send(&self) -> (Vec2, Vec2) {
self.send
}
#[must_use]
pub fn completion(&self) -> &[(Vec2, Vec2)] {
&self.completion
}
#[must_use]
pub const fn keyboard(&self) -> &KeyboardLayout {
&self.keyboard
}
#[must_use]
pub fn covers(&self, point: Vec2) -> bool {
let inside = |(min, max): (Vec2, Vec2)| {
point.x >= min.x && point.x <= max.x && point.y >= min.y && point.y <= max.y
};
inside(self.panel) || (!self.keyboard.keys().is_empty() && self.keyboard.contains(point))
}
#[must_use]
pub fn log_rows(&self) -> usize {
LogView::rows_in(self.log, &self.style)
}
#[must_use]
pub fn field_columns(&self, atlas: &FontAtlas) -> usize {
LogView::columns_in(
(self.text_pos, Vec2::new(self.input_right, self.text_pos.y)),
atlas,
&self.style,
)
}
}
#[cfg(test)]
mod tests;