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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use std::{iter::repeat_n, num::NonZeroU32, str::FromStr};
use crate::{
color_table::parse_color,
misc::{Style, Weight},
SegmentSize, SegmentStyle, Text3d, Text3dSegment,
};
trait Flip {
fn flip(&mut self);
}
impl Flip for Option<Weight> {
fn flip(&mut self) {
*self = match *self {
Some(w) if w <= Weight::NORMAL => Some(Weight::BOLD),
None => Some(Weight::BOLD),
_ => Some(Weight::NORMAL),
}
}
}
impl Flip for Option<Style> {
fn flip(&mut self) {
*self = match *self {
Some(Style::Normal) | None => Some(Style::Italic),
_ => Some(Style::Italic),
}
}
}
impl Flip for Option<bool> {
fn flip(&mut self) {
*self = match *self {
Some(false) | None => Some(true),
Some(true) => Some(false),
}
}
}
impl Text3d {
/// Call [`Text3d::parse`] with no custom parsing functions.
///
/// Only standard styles are supported, see [`Text3d::parse`] for details.
pub fn parse_raw(text: &str) -> Result<Self, ParseError> {
Text3d::parse(
text,
|command| Err(ParseError::BadCommand(command.into())),
|style| Err(ParseError::MissingStyle(style.into())),
)
}
/// Parse rich text string.
///
/// # Example
///
/// ```
/// "Deals **{blue:{damage_number}}** {red:fire} damage to the enemy."
/// ```
///
/// # Syntax
///
/// ## Style
///
/// ```md
/// {style:value}
/// ```
///
/// This is equivalent to `<style>value</style>` in html.
/// The left hand side is the name of the style, it will be passed to the `stylesheet` function.
///
/// Style commands also can be chained:
///
/// ```md
/// Deals {red, s-black, s-10: 10} damage!
/// ```
///
/// ## Standard Styles
///
/// These will be parsed regardless of the `stylesheet` function:
///
/// * `red` Parses Css color names as fill color.
/// * `#ff00ff` Parses hex color (accepts 3, 4, 6, 8 digits) as fill color.
/// * `s-4` Sets stroke to a number.
/// * `s-red` Parses color names as stroke color.
/// * `v-4.0` Sets the `magic_number` field.
/// * `f-Roboto` Sets the font to Roboto.
/// * `#18` Sets font size to `18`.
/// * `*1.5` Sets font size to `1.5` times the original.
/// * `h1` - `h4` Sets font size to `2`, `1.75`, `1.5`, `1.25` times the original.
///
/// ## Dynamic value
///
/// ```md
/// { value }
/// ```
///
/// Without `:` values in brackets are treated as dynamic values and passed to the `fetch_string` function.
/// The result should either be a string fetched from the world
/// or an [`Entity`](bevy::ecs::entity::Entity) with a [`FetchedTextSegment`](crate::FetchedTextSegment) component.
///
///
/// ## Markdown
///
/// A subset of markdown features are supported:
/// * `*emphasis*`
/// * `**strong**`
/// * `__underline__`
/// * `~~strikethrough~~`
/// * `\*` escape character
///
/// ## Inputs
///
/// * `fetch_string`: Parses strings to obtain values from the world.
/// * [`Text3dSegment::String`] should be returned for static values.
/// * [`Text3dSegment::Extract`] should be returned after spawning a string fetcher for dynamic values.
/// * `stylesheet`: Parses strings as [`SegmentStyle`].
///
/// We trim whitespaces before passing arguments to these functions.
pub fn parse(
text: &str,
mut fetch_string: impl FnMut(&str) -> Result<(Text3dSegment, SegmentStyle), ParseError>,
mut stylesheet: impl FnMut(&str) -> Result<SegmentStyle, ParseError>,
) -> Result<Self, ParseError> {
#[derive(Debug, Clone, Copy)]
enum ParseState {
Text,
Command,
Image,
}
let mut buffer = String::new();
let mut state = ParseState::Text;
let mut segments = Vec::new();
let mut styles = vec![SegmentStyle::default()];
macro_rules! style {
() => {
styles.last().ok_or(ParseError::BracketMismatch)?
};
(mut) => {
styles.last_mut().ok_or(ParseError::BracketMismatch)?
};
}
use ParseState::*;
let mut iter = text.chars().peekable();
while let Some(c) = iter.next() {
match (c, state) {
('{', Text) => {
push_segment(&buffer, &mut segments, &mut styles)?;
buffer.clear();
state = Command;
}
(':', Command) => match buffer.trim().split(",").collect::<Vec<_>>().as_slice() {
["image"] => {
buffer.clear();
state = Image;
}
style_slice => {
let mut style = style!().clone();
for s in style_slice {
style = style.join(parse_style(s.trim(), &mut stylesheet)?)
}
styles.push(style);
buffer.clear();
state = Text;
}
},
('}', Text) => {
push_segment(&buffer, &mut segments, &mut styles)?;
buffer.clear();
let _ = styles.pop();
}
('}', Command) => {
let (segment, style) = fetch_string(buffer.trim())?;
let style = style!().clone().join(style);
segments.push((segment, style));
buffer.clear();
state = Text;
}
('}', Image) => {
return Err(ParseError::NotSupported("image"));
}
('*', Text) => {
push_segment(&buffer, &mut segments, &mut styles)?;
buffer.clear();
let mut stars = 1;
while let Some(c) = iter.peek() {
if *c == '*' {
stars += 1;
iter.next();
} else {
break;
}
}
match stars {
1 => style!(mut).style.flip(),
2 => style!(mut).weight.flip(),
3 => {
style!(mut).style.flip();
style!(mut).weight.flip();
}
n if n % 2 == 0 => (),
_ => style!(mut).style.flip(),
}
}
('_', Text) if iter.peek() == Some(&'_') => {
push_segment(&buffer, &mut segments, &mut styles)?;
buffer.clear();
iter.next();
style!(mut).underline.flip()
}
('~', Text) if iter.peek() == Some(&'~') => {
push_segment(&buffer, &mut segments, &mut styles)?;
buffer.clear();
iter.next();
style!(mut).strikethrough.flip()
}
(c, Command | Image) => buffer.push(c),
('\\', Text) => {
if let Some(c) = iter.peek() {
buffer.push(*c);
iter.next();
} else {
buffer.push('\\');
}
}
(c, Text) if c.is_whitespace() => {
let mut linebreaks = if c == '\n' { 1 } else { 0 };
while let Some(c) = iter.peek() {
if !c.is_whitespace() {
break;
} else if *c == '\n' {
linebreaks += 1;
}
iter.next();
}
match linebreaks {
0 => buffer.push(' '),
n => buffer.extend(repeat_n('\n', n)),
}
}
(c, Text) => {
buffer.push(c);
}
}
}
push_segment(&buffer, &mut segments, &mut styles)?;
Ok(Text3d { segments })
}
}
fn parse_style(
style: &str,
mut stylesheet: impl FnMut(&str) -> Result<SegmentStyle, ParseError>,
) -> Result<SegmentStyle, ParseError> {
if let Some(number) = style.strip_prefix("v-") {
if let Ok(magic_number) = f32::from_str(number) {
Ok(SegmentStyle {
magic_number: Some(magic_number),
..Default::default()
})
} else {
stylesheet(style)
}
} else if let Some(name) = style.strip_prefix("s-") {
if let Ok(int) = u32::from_str(name) {
Ok(SegmentStyle {
stroke: NonZeroU32::new(int),
..Default::default()
})
} else if let Some(color) = parse_color(name) {
Ok(SegmentStyle {
stroke_color: Some(color),
..Default::default()
})
} else {
stylesheet(style)
}
} else if let Some(name) = style.strip_prefix("f-") {
Ok(SegmentStyle {
font: Some(name.into()),
..Default::default()
})
} else if let Some(name) = style.strip_prefix("#") {
if let Ok(size) = name.parse::<f32>() {
Ok(SegmentStyle {
size: Some(SegmentSize::Flat(size)),
..Default::default()
})
} else {
stylesheet(style)
}
} else if let Some(name) = style.strip_prefix("*") {
if let Ok(size) = name.parse::<f32>() {
Ok(SegmentStyle {
size: Some(SegmentSize::Multiply(size)),
..Default::default()
})
} else {
stylesheet(style)
}
} else if let Some(color) = parse_color(style) {
Ok(SegmentStyle {
fill_color: Some(color),
..Default::default()
})
} else {
match style {
"bold" => Ok(SegmentStyle {
weight: Some(Weight::BOLD),
..Default::default()
}),
"italic" => Ok(SegmentStyle {
style: Some(Style::Italic),
..Default::default()
}),
"underline" => Ok(SegmentStyle {
underline: Some(true),
..Default::default()
}),
"strikethrough" => Ok(SegmentStyle {
strikethrough: Some(true),
..Default::default()
}),
"h1" => Ok(SegmentStyle {
size: Some(SegmentSize::Multiply(2.0)),
..Default::default()
}),
"h2" => Ok(SegmentStyle {
size: Some(SegmentSize::Multiply(1.75)),
..Default::default()
}),
"h3" => Ok(SegmentStyle {
size: Some(SegmentSize::Multiply(1.5)),
..Default::default()
}),
"h4" => Ok(SegmentStyle {
size: Some(SegmentSize::Multiply(1.25)),
..Default::default()
}),
_ => stylesheet(style),
}
}
}
fn push_segment(
buffer: &str,
spans: &mut Vec<(Text3dSegment, SegmentStyle)>,
styles: &mut [SegmentStyle],
) -> Result<(), ParseError> {
if !buffer.is_empty() {
spans.push((
Text3dSegment::String(buffer.into()),
styles.last().ok_or(ParseError::BracketMismatch)?.clone(),
));
}
Ok(())
}
/// Error emitted when parsing rich text.
#[derive(Debug, thiserror::Error)]
pub enum ParseError {
#[error("Feature {0} is not supported.")]
NotSupported(&'static str),
#[error("Bracket mismatch.")]
BracketMismatch,
#[error("Bad command: {0}")]
BadCommand(String),
#[error("Style {0} missing.")]
MissingStyle(String),
#[error("{0}")]
Custom(String),
}