Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/ui/virtual_keyboard.rs
6595 views
1
//! Virtual keyboard example
2
3
use bevy::{
4
color::palettes::css::NAVY,
5
core_widgets::{Activate, CoreWidgetsPlugins},
6
ecs::relationship::RelatedSpawnerCommands,
7
feathers::{
8
controls::virtual_keyboard, dark_theme::create_dark_theme, theme::UiTheme, FeathersPlugin,
9
},
10
input_focus::{tab_navigation::TabNavigationPlugin, InputDispatchPlugin},
11
prelude::*,
12
};
13
14
fn main() {
15
App::new()
16
.add_plugins((
17
DefaultPlugins,
18
CoreWidgetsPlugins,
19
InputDispatchPlugin,
20
TabNavigationPlugin,
21
FeathersPlugin,
22
))
23
.insert_resource(UiTheme(create_dark_theme()))
24
.add_systems(Startup, setup)
25
.run();
26
}
27
28
#[derive(Component)]
29
struct VirtualKey(String);
30
31
fn on_virtual_key_pressed(
32
In(Activate(virtual_key_entity)): In<Activate>,
33
virtual_key_query: Query<&VirtualKey>,
34
) {
35
if let Ok(VirtualKey(label)) = virtual_key_query.get(virtual_key_entity) {
36
println!("key pressed: {label}");
37
}
38
}
39
40
fn setup(mut commands: Commands) {
41
// ui camera
42
commands.spawn(Camera2d);
43
let callback = commands.register_system(on_virtual_key_pressed);
44
45
let layout = [
46
vec!["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", ","],
47
vec!["Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P"],
48
vec!["A", "S", "D", "F", "G", "H", "J", "K", "L", "'"],
49
vec!["Z", "X", "C", "V", "B", "N", "M", "-", "/"],
50
vec!["space", "enter", "backspace"],
51
vec!["left", "right", "up", "down", "home", "end"],
52
];
53
54
let keys_iter = layout.into_iter().map(|row| {
55
row.into_iter()
56
.map(|label| {
57
let label_string = label.to_string();
58
(label_string.clone(), VirtualKey(label_string))
59
})
60
.collect()
61
});
62
63
commands
64
.spawn(Node {
65
width: percent(100),
66
height: percent(100),
67
align_items: AlignItems::End,
68
justify_content: JustifyContent::Center,
69
..default()
70
})
71
.with_children(|parent: &mut RelatedSpawnerCommands<ChildOf>| {
72
parent
73
.spawn((
74
Node {
75
flex_direction: FlexDirection::Column,
76
border: px(5).into(),
77
row_gap: px(5),
78
padding: px(5).into(),
79
align_items: AlignItems::Center,
80
margin: px(25).into(),
81
..Default::default()
82
},
83
BackgroundColor(NAVY.into()),
84
BorderColor::all(Color::WHITE),
85
BorderRadius::all(px(10)),
86
))
87
.with_children(|parent: &mut RelatedSpawnerCommands<ChildOf>| {
88
parent.spawn(Text::new("virtual keyboard"));
89
parent.spawn(virtual_keyboard(keys_iter, callback));
90
});
91
});
92
}
93
94