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
use bevy_app::{App, Update};
use bevy_doryen::doryen::{AppOptions, Color, TextAlign};
use bevy_doryen::prelude::*;
use bevy_ecs::system::{Res, ResMut, Resource};
use unicode_segmentation::UnicodeSegmentation;

const WHITE: Color = (255, 255, 255, 255);

#[derive(Default, Resource)]
struct TextInput {
    text: String,
    cursor: usize,
}

pub fn main() {
    App::new()
        .insert_resource(DoryenPluginSettings {
            app_options: AppOptions {
                window_title: String::from("bevy_doryen subcell resolution demo"),
                ..Default::default()
            },
            ..Default::default()
        })
        .add_plugins(DoryenPlugin)
        .init_resource::<TextInput>()
        .add_systems(Update, update)
        .add_systems(Render, render)
        .run();
}

fn update(input: Res<Input>, mut text_input: ResMut<TextInput>) {
    // input.text returns the characters typed by the player since last update
    let text = input.text();
    if !text.is_empty() {
        text_input.text.push_str(text);
    }
    // handle backspace
    if input.key_released("Backspace") && !text_input.text.is_empty() {
        // convoluted way to remove the last character of the string
        // in a way that also works with utf-8 graphemes
        // where one character != one byte
        let mut graphemes = text_input.text.graphemes(true).rev();
        graphemes.next();
        text_input.text = graphemes.rev().collect();
    }
    // handle tab
    if input.key_released("Tab") {
        text_input.text.push_str("   ");
    }
    text_input.cursor += 1;
}

fn render(mut root_console: ResMut<RootConsole>, text_input: Res<TextInput>) {
    root_console.clear(None, None, Some(' ' as u16));
    root_console.print(
        5,
        5,
        &format!(
            "Type some text : {}{}",
            text_input.text,
            // blinking cursor
            if text_input.cursor % 25 < 12 {
                '_'
            } else {
                ' '
            }
        ),
        TextAlign::Left,
        Some(WHITE),
        None,
    );
}