Merge pull request #37 from hecrj/feature/text-input

Text input widget
This commit is contained in:
Héctor Ramón 2019-11-05 03:43:15 +01:00 committed by GitHub
commit da2717c74d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
21 changed files with 744 additions and 63 deletions

View file

@ -1,15 +1,26 @@
/// A 2D vector.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Vector {
pub x: f32,
pub y: f32,
pub struct Vector<T = f32> {
pub x: T,
pub y: T,
}
impl Vector {
impl<T> Vector<T> {
/// Creates a new [`Vector`] with the given components.
///
/// [`Vector`]: struct.Vector.html
pub fn new(x: f32, y: f32) -> Self {
pub fn new(x: T, y: T) -> Self {
Self { x, y }
}
}
impl<T> std::ops::Add for Vector<T>
where
T: std::ops::Add<Output = T>,
{
type Output = Self;
fn add(self, b: Self) -> Self {
Self::new(self.x + b.x, self.y + b.y)
}
}

View file

@ -17,18 +17,18 @@ pub mod button;
pub mod scrollable;
pub mod slider;
pub mod text;
pub mod text_input;
#[doc(no_inline)]
pub use button::Button;
#[doc(no_inline)]
pub use slider::Slider;
#[doc(no_inline)]
pub use text::Text;
#[doc(no_inline)]
pub use scrollable::Scrollable;
#[doc(no_inline)]
pub use slider::Slider;
#[doc(no_inline)]
pub use text::Text;
#[doc(no_inline)]
pub use text_input::TextInput;
pub use checkbox::Checkbox;
pub use column::Column;

View file

@ -0,0 +1,148 @@
use crate::Length;
pub struct TextInput<'a, Message> {
pub state: &'a mut State,
pub placeholder: String,
pub value: Value,
pub width: Length,
pub max_width: Length,
pub padding: u16,
pub size: Option<u16>,
pub on_change: Box<dyn Fn(String) -> Message>,
pub on_submit: Option<Message>,
}
impl<'a, Message> TextInput<'a, Message> {
pub fn new<F>(
state: &'a mut State,
placeholder: &str,
value: &str,
on_change: F,
) -> Self
where
F: 'static + Fn(String) -> Message,
{
Self {
state,
placeholder: String::from(placeholder),
value: Value::new(value),
width: Length::Fill,
max_width: Length::Shrink,
padding: 0,
size: None,
on_change: Box::new(on_change),
on_submit: None,
}
}
/// Sets the width of the [`TextInput`].
///
/// [`TextInput`]: struct.TextInput.html
pub fn width(mut self, width: Length) -> Self {
self.width = width;
self
}
/// Sets the maximum width of the [`TextInput`].
///
/// [`TextInput`]: struct.TextInput.html
pub fn max_width(mut self, max_width: Length) -> Self {
self.max_width = max_width;
self
}
/// Sets the padding of the [`TextInput`].
///
/// [`TextInput`]: struct.TextInput.html
pub fn padding(mut self, units: u16) -> Self {
self.padding = units;
self
}
pub fn size(mut self, size: u16) -> Self {
self.size = Some(size);
self
}
pub fn on_submit(mut self, message: Message) -> Self {
self.on_submit = Some(message);
self
}
}
impl<'a, Message> std::fmt::Debug for TextInput<'a, Message>
where
Message: std::fmt::Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// TODO: Complete once stabilized
f.debug_struct("TextInput").finish()
}
}
#[derive(Debug, Default)]
pub struct State {
pub is_focused: bool,
cursor_position: usize,
}
impl State {
pub fn new() -> Self {
Self::default()
}
pub fn move_cursor_right(&mut self, value: &Value) {
let current = self.cursor_position(value);
if current < value.len() {
self.cursor_position = current + 1;
}
}
pub fn move_cursor_left(&mut self, value: &Value) {
let current = self.cursor_position(value);
if current > 0 {
self.cursor_position = current - 1;
}
}
pub fn cursor_position(&self, value: &Value) -> usize {
self.cursor_position.min(value.len())
}
}
// TODO: Use `unicode-segmentation`
pub struct Value(Vec<char>);
impl Value {
pub fn new(string: &str) -> Self {
Self(string.chars().collect())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn until(&self, index: usize) -> Self {
Self(self.0[..index.min(self.len())].iter().cloned().collect())
}
pub fn to_string(&self) -> String {
let mut string = String::new();
for c in self.0.iter() {
string.push(*c);
}
string
}
pub fn insert(&mut self, index: usize, c: char) {
self.0.insert(index, c);
}
pub fn remove(&mut self, index: usize) {
self.0.remove(index);
}
}

116
examples/todos.rs Normal file
View file

@ -0,0 +1,116 @@
use iced::{
scrollable, text::HorizontalAlignment, text_input, Align, Application,
Checkbox, Color, Column, Element, Length, Scrollable, Text, TextInput,
};
pub fn main() {
Todos::default().run()
}
#[derive(Debug, Default)]
struct Todos {
scroll: scrollable::State,
input: text_input::State,
input_value: String,
tasks: Vec<Task>,
}
#[derive(Debug, Clone)]
pub enum Message {
InputChanged(String),
CreateTask,
TaskChanged(usize, bool),
}
impl Application for Todos {
type Message = Message;
fn update(&mut self, message: Message) {
match message {
Message::InputChanged(value) => {
self.input_value = value;
}
Message::CreateTask => {
if !self.input_value.is_empty() {
self.tasks.push(Task::new(self.input_value.clone()));
self.input_value = String::new();
}
}
Message::TaskChanged(i, completed) => {
if let Some(task) = self.tasks.get_mut(i) {
task.completed = completed;
}
}
}
dbg!(self);
}
fn view(&mut self) -> Element<Message> {
let title = Text::new("todos")
.size(100)
.color(GRAY)
.horizontal_alignment(HorizontalAlignment::Center);
let input = TextInput::new(
&mut self.input,
"What needs to be done?",
&self.input_value,
Message::InputChanged,
)
.padding(15)
.size(30)
.on_submit(Message::CreateTask);
let tasks = self.tasks.iter_mut().enumerate().fold(
Column::new().spacing(20),
|column, (i, task)| {
column.push(
task.view()
.map(move |state| Message::TaskChanged(i, state)),
)
},
);
let content = Column::new()
.max_width(Length::Units(800))
.align_self(Align::Center)
.spacing(20)
.push(title)
.push(input)
.push(tasks);
Scrollable::new(&mut self.scroll)
.padding(40)
.push(content)
.into()
}
}
#[derive(Debug)]
struct Task {
description: String,
completed: bool,
}
impl Task {
fn new(description: String) -> Self {
Task {
description,
completed: false,
}
}
fn view(&mut self) -> Element<bool> {
Checkbox::new(self.completed, &self.description, |checked| checked)
.into()
}
}
// Colors
const GRAY: Color = Color {
r: 0.5,
g: 0.5,
b: 0.5,
a: 1.0,
};

View file

@ -1,7 +1,7 @@
use iced::{
button, scrollable, slider, text::HorizontalAlignment, Align, Application,
Background, Button, Checkbox, Color, Column, Element, Image, Justify,
Length, Radio, Row, Scrollable, Slider, Text,
button, scrollable, slider, text::HorizontalAlignment, text_input, Align,
Application, Background, Button, Checkbox, Color, Column, Element, Image,
Justify, Length, Radio, Row, Scrollable, Slider, Text, TextInput,
};
pub fn main() {
@ -101,7 +101,7 @@ impl Application for Tour {
}
}
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone)]
pub enum Message {
BackPressed,
NextPressed,
@ -139,6 +139,10 @@ impl Steps {
slider: slider::State::new(),
},
Step::Scrollable,
Step::TextInput {
value: String::new(),
state: text_input::State::new(),
},
Step::Debugger,
Step::End,
],
@ -201,11 +205,15 @@ enum Step {
slider: slider::State,
},
Scrollable,
TextInput {
value: String,
state: text_input::State,
},
Debugger,
End,
}
#[derive(Debug, Clone, Copy)]
#[derive(Debug, Clone)]
pub enum StepMessage {
SliderChanged(f32),
LayoutChanged(Layout),
@ -214,6 +222,7 @@ pub enum StepMessage {
TextColorChanged(Color),
LanguageSelected(Language),
ImageWidthChanged(f32),
InputChanged(String),
DebugToggled(bool),
}
@ -260,6 +269,11 @@ impl<'a> Step {
*width = new_width.round() as u16;
}
}
StepMessage::InputChanged(new_value) => {
if let Step::TextInput { value, .. } = self {
*value = new_value;
}
}
};
}
@ -272,6 +286,7 @@ impl<'a> Step {
Step::Image { .. } => true,
Step::RowsAndColumns { .. } => true,
Step::Scrollable => true,
Step::TextInput { value, .. } => !value.is_empty(),
Step::Debugger => true,
Step::End => false,
}
@ -297,6 +312,9 @@ impl<'a> Step {
Self::rows_and_columns(*layout, spacing_slider, *spacing).into()
}
Step::Scrollable => Self::scrollable().into(),
Step::TextInput { value, state } => {
Self::text_input(value, state).into()
}
Step::Debugger => Self::debugger(debug).into(),
Step::End => Self::end().into(),
}
@ -550,6 +568,38 @@ impl<'a> Step {
)
}
fn text_input(
value: &str,
state: &'a mut text_input::State,
) -> Column<'a, StepMessage> {
Self::container("Text input")
.push(Text::new(
"Use a text input to ask for different kinds of information.",
))
.push(
TextInput::new(
state,
"Type something to continue...",
value,
StepMessage::InputChanged,
)
.padding(10)
.size(30),
)
.push(Text::new(
"A text input produces a message every time it changes. It is \
very easy to keep track of its contents:",
))
.push(
Text::new(if value.is_empty() {
"You have not typed anything yet..."
} else {
value
})
.horizontal_alignment(HorizontalAlignment::Center),
)
}
fn debugger(debug: bool) -> Column<'a, StepMessage> {
Self::container("Debugger")
.push(Text::new(

View file

@ -217,7 +217,7 @@ where
/// ```
pub fn map<F, B>(self, f: F) -> Element<'a, B, Renderer>
where
Message: 'static + Copy,
Message: 'static + Clone,
Renderer: 'a,
B: 'static,
F: 'static + Fn(Message) -> B,
@ -286,7 +286,7 @@ impl<'a, A, B, Renderer> Map<'a, A, B, Renderer> {
impl<'a, A, B, Renderer> Widget<B, Renderer> for Map<'a, A, B, Renderer>
where
A: Copy,
A: Clone,
Renderer: crate::Renderer,
{
fn node(&self, renderer: &Renderer) -> Node {

View file

@ -211,10 +211,8 @@ mod node;
mod style;
mod user_interface;
pub(crate) use iced_core::Vector;
pub use iced_core::{
Align, Background, Color, Justify, Length, Point, Rectangle,
Align, Background, Color, Justify, Length, Point, Rectangle, Vector,
};
#[doc(no_inline)]

View file

@ -18,4 +18,7 @@ pub enum MouseCursor {
/// The cursor is grabbing a widget.
Grabbing,
/// The cursor is over a text widget.
Text,
}

View file

@ -29,6 +29,7 @@ pub mod row;
pub mod scrollable;
pub mod slider;
pub mod text;
pub mod text_input;
#[doc(no_inline)]
pub use button::Button;
@ -48,6 +49,8 @@ pub use scrollable::Scrollable;
pub use slider::Slider;
#[doc(no_inline)]
pub use text::Text;
#[doc(no_inline)]
pub use text_input::TextInput;
use crate::{Event, Hasher, Layout, Node, Point};

View file

@ -19,7 +19,7 @@ impl<'a, Message, Renderer> Widget<Message, Renderer>
for Button<'a, Message, Renderer>
where
Renderer: self::Renderer,
Message: Copy + std::fmt::Debug,
Message: Clone + std::fmt::Debug,
{
fn node(&self, renderer: &Renderer) -> Node {
renderer.node(&self)
@ -38,7 +38,7 @@ where
button: mouse::Button::Left,
state,
}) => {
if let Some(on_press) = self.on_press {
if let Some(on_press) = self.on_press.clone() {
let bounds = layout.bounds();
match state {
@ -108,7 +108,7 @@ impl<'a, Message, Renderer> From<Button<'a, Message, Renderer>>
for Element<'a, Message, Renderer>
where
Renderer: 'static + self::Renderer,
Message: 'static + Copy + std::fmt::Debug,
Message: 'static + Clone + std::fmt::Debug,
{
fn from(
button: Button<'a, Message, Renderer>,

View file

@ -9,7 +9,7 @@ pub use iced_core::Radio;
impl<Message, Renderer> Widget<Message, Renderer> for Radio<Message>
where
Renderer: self::Renderer,
Message: Copy + std::fmt::Debug,
Message: Clone + std::fmt::Debug,
{
fn node(&self, renderer: &Renderer) -> Node {
renderer.node(&self)
@ -29,7 +29,7 @@ where
state: ButtonState::Pressed,
}) => {
if layout.bounds().contains(cursor_position) {
messages.push(self.on_click);
messages.push(self.on_click.clone());
}
}
_ => {}
@ -85,7 +85,7 @@ impl<'a, Message, Renderer> From<Radio<Message>>
for Element<'a, Message, Renderer>
where
Renderer: self::Renderer,
Message: 'static + Copy + std::fmt::Debug,
Message: 'static + Clone + std::fmt::Debug,
{
fn from(checkbox: Radio<Message>) -> Element<'a, Message, Renderer> {
Element::new(checkbox)

View file

@ -0,0 +1,149 @@
use crate::{
input::{keyboard, mouse, ButtonState},
Element, Event, Hasher, Layout, Length, Node, Point, Rectangle, Style,
Widget,
};
pub use iced_core::{text_input::State, TextInput};
impl<'a, Message, Renderer> Widget<Message, Renderer> for TextInput<'a, Message>
where
Renderer: self::Renderer,
Message: Clone + std::fmt::Debug,
{
fn node(&self, renderer: &Renderer) -> Node {
let text_bounds =
Node::new(Style::default().width(Length::Fill).height(
Length::Units(self.size.unwrap_or(renderer.default_size())),
));
Node::with_children(
Style::default()
.width(self.width)
.max_width(self.width)
.padding(self.padding),
vec![text_bounds],
)
}
fn on_event(
&mut self,
event: Event,
layout: Layout<'_>,
cursor_position: Point,
messages: &mut Vec<Message>,
_renderer: &Renderer,
) {
match event {
Event::Mouse(mouse::Event::Input {
button: mouse::Button::Left,
state: ButtonState::Pressed,
}) => {
self.state.is_focused =
layout.bounds().contains(cursor_position);
}
Event::Keyboard(keyboard::Event::CharacterReceived(c))
if self.state.is_focused && !c.is_control() =>
{
let cursor_position = self.state.cursor_position(&self.value);
self.value.insert(cursor_position, c);
self.state.move_cursor_right(&self.value);
let message = (self.on_change)(self.value.to_string());
messages.push(message);
}
Event::Keyboard(keyboard::Event::Input {
key_code,
state: ButtonState::Pressed,
}) if self.state.is_focused => match key_code {
keyboard::KeyCode::Enter => {
if let Some(on_submit) = self.on_submit.clone() {
messages.push(on_submit);
}
}
keyboard::KeyCode::Backspace => {
let cursor_position =
self.state.cursor_position(&self.value);
if cursor_position > 0 {
self.state.move_cursor_left(&self.value);
let _ = self.value.remove(cursor_position - 1);
let message = (self.on_change)(self.value.to_string());
messages.push(message);
}
}
keyboard::KeyCode::Delete => {
let cursor_position =
self.state.cursor_position(&self.value);
if cursor_position < self.value.len() {
let _ = self.value.remove(cursor_position);
let message = (self.on_change)(self.value.to_string());
messages.push(message);
}
}
keyboard::KeyCode::Left => {
self.state.move_cursor_left(&self.value);
}
keyboard::KeyCode::Right => {
self.state.move_cursor_right(&self.value);
}
_ => {}
},
_ => {}
}
}
fn draw(
&self,
renderer: &mut Renderer,
layout: Layout<'_>,
cursor_position: Point,
) -> Renderer::Output {
let bounds = layout.bounds();
let text_bounds = layout.children().next().unwrap().bounds();
renderer.draw(&self, bounds, text_bounds, cursor_position)
}
fn hash_layout(&self, state: &mut Hasher) {
use std::any::TypeId;
use std::hash::Hash;
TypeId::of::<TextInput<'static, ()>>().hash(state);
self.width.hash(state);
self.max_width.hash(state);
self.padding.hash(state);
self.size.hash(state);
}
}
pub trait Renderer: crate::Renderer + Sized {
fn default_size(&self) -> u16;
fn draw<Message>(
&mut self,
text_input: &TextInput<'_, Message>,
bounds: Rectangle,
text_bounds: Rectangle,
cursor_position: Point,
) -> Self::Output;
}
impl<'a, Message, Renderer> From<TextInput<'a, Message>>
for Element<'a, Message, Renderer>
where
Renderer: 'static + self::Renderer,
Message: 'static + Clone + std::fmt::Debug,
{
fn from(
text_input: TextInput<'a, Message>,
) -> Element<'a, Message, Renderer> {
Element::new(text_input)
}
}

View file

@ -1,8 +1,9 @@
pub use iced_wgpu::{Primitive, Renderer};
pub use iced_winit::{
button, scrollable, slider, text, winit, Align, Background, Checkbox,
Color, Image, Justify, Length, Radio, Scrollable, Slider, Text,
button, scrollable, slider, text, text_input, winit, Align, Background,
Checkbox, Color, Image, Justify, Length, Radio, Scrollable, Slider, Text,
TextInput,
};
pub type Element<'a, Message> = iced_winit::Element<'a, Message, Renderer>;

View file

@ -1,4 +1,4 @@
use iced_native::{text, Background, Color, Rectangle};
use iced_native::{text, Background, Color, Rectangle, Vector};
#[derive(Debug, Clone)]
pub enum Primitive {
@ -25,7 +25,7 @@ pub enum Primitive {
},
Clip {
bounds: Rectangle,
offset: u32,
offset: Vector<u32>,
content: Box<Primitive>,
},
}

View file

@ -1,7 +1,7 @@
use crate::{quad, Image, Primitive, Quad, Transformation};
use iced_native::{
renderer::Debugger, renderer::Windowed, Background, Color, Layout,
MouseCursor, Point, Rectangle, Widget,
MouseCursor, Point, Rectangle, Vector, Widget,
};
use raw_window_handle::HasRawWindowHandle;
@ -23,6 +23,7 @@ mod row;
mod scrollable;
mod slider;
mod text;
mod text_input;
pub struct Renderer {
surface: Surface,
@ -43,17 +44,17 @@ pub struct Target {
pub struct Layer<'a> {
bounds: Rectangle<u32>,
y_offset: u32,
offset: Vector<u32>,
quads: Vec<Quad>,
images: Vec<Image>,
text: Vec<wgpu_glyph::Section<'a>>,
}
impl<'a> Layer<'a> {
pub fn new(bounds: Rectangle<u32>, y_offset: u32) -> Self {
pub fn new(bounds: Rectangle<u32>, offset: Vector<u32>) -> Self {
Self {
bounds,
y_offset,
offset,
quads: Vec::new(),
images: Vec::new(),
text: Vec::new(),
@ -148,18 +149,18 @@ impl Renderer {
});
let mut layers = Vec::new();
let mut current = Layer::new(
layers.push(Layer::new(
Rectangle {
x: 0,
y: 0,
width: u32::from(target.width),
height: u32::from(target.height),
},
0,
);
Vector::new(0, 0),
));
self.draw_primitive(primitive, &mut current, &mut layers);
layers.push(current);
self.draw_primitive(primitive, &mut layers);
for layer in layers {
self.flush(
@ -178,15 +179,16 @@ impl Renderer {
fn draw_primitive<'a>(
&mut self,
primitive: &'a Primitive,
layer: &mut Layer<'a>,
layers: &mut Vec<Layer<'a>>,
) {
let layer = layers.last_mut().unwrap();
match primitive {
Primitive::None => {}
Primitive::Group { primitives } => {
// TODO: Inspect a bit and regroup (?)
for primitive in primitives {
self.draw_primitive(primitive, layer, layers)
self.draw_primitive(primitive, layers)
}
}
Primitive::Text {
@ -255,7 +257,10 @@ impl Renderer {
border_radius,
} => {
layer.quads.push(Quad {
position: [bounds.x, bounds.y - layer.y_offset as f32],
position: [
bounds.x - layer.offset.x as f32,
bounds.y - layer.offset.y as f32,
],
scale: [bounds.width, bounds.height],
color: match background {
Background::Color(color) => color.into_linear(),
@ -275,18 +280,22 @@ impl Renderer {
offset,
content,
} => {
let mut new_layer = Layer::new(
let clip_layer = Layer::new(
Rectangle {
x: bounds.x as u32,
y: bounds.y as u32 - layer.y_offset,
x: bounds.x as u32 - layer.offset.x,
y: bounds.y as u32 - layer.offset.y,
width: bounds.width as u32,
height: bounds.height as u32,
},
layer.y_offset + offset,
layer.offset + *offset,
);
let new_layer = Layer::new(layer.bounds, layer.offset);
layers.push(clip_layer);
// TODO: Primitive culling
self.draw_primitive(content, &mut new_layer, layers);
self.draw_primitive(content, layers);
layers.push(new_layer);
}
@ -301,7 +310,10 @@ impl Renderer {
target: &wgpu::TextureView,
) {
let translated = transformation
* Transformation::translate(0.0, -(layer.y_offset as f32));
* Transformation::translate(
-(layer.offset.x as f32),
-(layer.offset.y as f32),
);
if layer.quads.len() > 0 {
self.quad_pipeline.draw(

View file

@ -10,6 +10,7 @@ const SIZE: f32 = 28.0;
impl checkbox::Renderer for Renderer {
fn node<Message>(&self, checkbox: &Checkbox<Message>) -> Node {
Row::<(), Self>::new()
.width(Length::Fill)
.spacing(15)
.align_items(Align::Center)
.push(

View file

@ -1,7 +1,7 @@
use crate::{Primitive, Renderer};
use iced_native::{
scrollable, Background, Color, Layout, MouseCursor, Point, Rectangle,
Scrollable, Widget,
Scrollable, Vector, Widget,
};
const SCROLLBAR_WIDTH: u16 = 10;
@ -56,9 +56,9 @@ impl scrollable::Renderer for Renderer {
let (content, mouse_cursor) =
scrollable.content.draw(self, content, cursor_position);
let primitive = Primitive::Clip {
let clip = Primitive::Clip {
bounds,
offset,
offset: Vector::new(0, offset),
content: Box::new(content),
};
@ -107,19 +107,15 @@ impl scrollable::Renderer for Renderer {
};
Primitive::Group {
primitives: vec![
primitive,
scrollbar_background,
scrollbar,
],
primitives: vec![clip, scrollbar_background, scrollbar],
}
} else {
Primitive::Group {
primitives: vec![primitive, scrollbar],
primitives: vec![clip, scrollbar],
}
}
} else {
primitive
clip
},
if is_mouse_over_scrollbar
|| scrollable.state.is_scrollbar_grabbed()

View file

@ -47,7 +47,7 @@ impl text::Renderer for Renderer {
let (width, height) = if let Some(bounds) =
glyph_brush.borrow_mut().glyph_bounds(&text)
{
(bounds.width(), bounds.height())
(bounds.width().ceil(), bounds.height().ceil())
} else {
(0.0, 0.0)
};

View file

@ -0,0 +1,171 @@
use crate::{Primitive, Renderer};
use iced_native::{
text::HorizontalAlignment, text::VerticalAlignment, text_input, Background,
Color, MouseCursor, Point, Rectangle, TextInput, Vector,
};
use std::f32;
impl text_input::Renderer for Renderer {
fn default_size(&self) -> u16 {
// TODO: Make this configurable
20
}
fn draw<Message>(
&mut self,
text_input: &TextInput<Message>,
bounds: Rectangle,
text_bounds: Rectangle,
cursor_position: Point,
) -> Self::Output {
let is_mouse_over = bounds.contains(cursor_position);
let border = Primitive::Quad {
bounds,
background: Background::Color(
if is_mouse_over || text_input.state.is_focused {
Color {
r: 0.5,
g: 0.5,
b: 0.5,
a: 1.0,
}
} else {
Color {
r: 0.7,
g: 0.7,
b: 0.7,
a: 1.0,
}
},
),
border_radius: 5,
};
let input = Primitive::Quad {
bounds: Rectangle {
x: bounds.x + 1.0,
y: bounds.y + 1.0,
width: bounds.width - 2.0,
height: bounds.height - 2.0,
},
background: Background::Color(Color::WHITE),
border_radius: 5,
};
let size = f32::from(text_input.size.unwrap_or(self.default_size()));
let text = text_input.value.to_string();
let value = Primitive::Text {
content: if text.is_empty() {
text_input.placeholder.clone()
} else {
text.clone()
},
color: if text.is_empty() {
Color {
r: 0.7,
g: 0.7,
b: 0.7,
a: 1.0,
}
} else {
Color {
r: 0.3,
g: 0.3,
b: 0.3,
a: 1.0,
}
},
bounds: Rectangle {
width: f32::INFINITY,
..text_bounds
},
size,
horizontal_alignment: HorizontalAlignment::Left,
vertical_alignment: VerticalAlignment::Center,
};
let (contents_primitive, offset) = if text_input.state.is_focused {
use wgpu_glyph::{GlyphCruncher, Scale, Section};
let text_before_cursor = &text_input
.value
.until(text_input.state.cursor_position(&text_input.value))
.to_string();
let mut text_value_width = self
.glyph_brush
.borrow_mut()
.glyph_bounds(Section {
text: text_before_cursor,
bounds: (f32::INFINITY, text_bounds.height),
scale: Scale { x: size, y: size },
..Default::default()
})
.map(|bounds| bounds.width().round())
.unwrap_or(0.0);
let spaces_at_the_end =
text_before_cursor.len() - text_before_cursor.trim_end().len();
if spaces_at_the_end > 0 {
let space_width = {
let glyph_brush = self.glyph_brush.borrow();
// TODO: Select appropriate font
let font = &glyph_brush.fonts()[0];
font.glyph(' ')
.scaled(Scale { x: size, y: size })
.h_metrics()
.advance_width
};
text_value_width += spaces_at_the_end as f32 * space_width;
}
let cursor = Primitive::Quad {
bounds: Rectangle {
x: text_bounds.x + text_value_width,
y: text_bounds.y,
width: 1.0,
height: text_bounds.height,
},
background: Background::Color(Color::BLACK),
border_radius: 0,
};
(
Primitive::Group {
primitives: vec![value, cursor],
},
Vector::new(
((text_value_width + 5.0) - text_bounds.width).max(0.0)
as u32,
0,
),
)
} else {
(value, Vector::new(0, 0))
};
let contents = Primitive::Clip {
bounds: text_bounds,
offset,
content: Box::new(contents_primitive),
};
(
Primitive::Group {
primitives: vec![border, input, contents],
},
if is_mouse_over {
MouseCursor::Text
} else {
MouseCursor::OutOfBounds
},
)
}
}

View file

@ -1,6 +1,8 @@
use crate::{
column, conversion, input::mouse, renderer::Windowed, Cache, Column,
Element, Event, Length, MouseCursor, UserInterface,
column, conversion,
input::{keyboard, mouse},
renderer::Windowed,
Cache, Column, Element, Event, Length, MouseCursor, UserInterface,
};
pub trait Application {
@ -167,6 +169,25 @@ pub trait Application {
));
}
},
WindowEvent::ReceivedCharacter(c) => {
events.push(Event::Keyboard(
keyboard::Event::CharacterReceived(c),
));
}
WindowEvent::KeyboardInput {
input:
winit::event::KeyboardInput {
virtual_keycode: Some(virtual_keycode),
state,
..
},
..
} => {
events.push(Event::Keyboard(keyboard::Event::Input {
key_code: conversion::key_code(virtual_keycode),
state: conversion::button_state(state),
}));
}
WindowEvent::CloseRequested => {
*control_flow = ControlFlow::Exit;
}

View file

@ -9,6 +9,7 @@ pub fn mouse_cursor(mouse_cursor: MouseCursor) -> winit::window::CursorIcon {
MouseCursor::Working => winit::window::CursorIcon::Progress,
MouseCursor::Grab => winit::window::CursorIcon::Grab,
MouseCursor::Grabbing => winit::window::CursorIcon::Grabbing,
MouseCursor::Text => winit::window::CursorIcon::Text,
}
}