-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathtext.rs
485 lines (460 loc) · 20.6 KB
/
text.rs
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
// Copyright 2024 the Parley Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT
use accesskit::{Node, TreeUpdate};
use core::default::Default;
use parley::{GenericFamily, StyleProperty, editor::SplitString, layout::PositionedLayoutItem};
use std::time::{Duration, Instant};
use vello::{
Scene,
kurbo::{Affine, Line, Stroke},
peniko::color::palette,
peniko::{Brush, Fill},
};
use winit::{
event::{Ime, Modifiers, Touch, WindowEvent},
keyboard::{Key, NamedKey},
};
pub use parley::layout::editor::Generation;
use parley::{FontContext, LayoutContext, PlainEditor, PlainEditorDriver};
use crate::access_ids::next_node_id;
pub const INSET: f32 = 32.0;
pub struct Editor {
font_cx: FontContext,
layout_cx: LayoutContext<Brush>,
editor: PlainEditor<Brush>,
last_click_time: Option<Instant>,
click_count: u32,
pointer_down: bool,
cursor_pos: (f32, f32),
cursor_visible: bool,
modifiers: Option<Modifiers>,
start_time: Option<Instant>,
blink_period: Duration,
}
impl Editor {
pub fn new(text: &str) -> Self {
let mut editor = PlainEditor::new(32.0);
editor.set_text(text);
editor.set_scale(1.0);
let styles = editor.edit_styles();
styles.insert(StyleProperty::LineHeight(1.2));
styles.insert(GenericFamily::SystemUi.into());
styles.insert(StyleProperty::Brush(palette::css::WHITE.into()));
Self {
font_cx: Default::default(),
layout_cx: Default::default(),
editor,
last_click_time: Default::default(),
click_count: Default::default(),
pointer_down: Default::default(),
cursor_pos: Default::default(),
cursor_visible: Default::default(),
modifiers: Default::default(),
start_time: Default::default(),
blink_period: Default::default(),
}
}
fn driver(&mut self) -> PlainEditorDriver<'_, Brush> {
self.editor.driver(&mut self.font_cx, &mut self.layout_cx)
}
pub fn editor(&mut self) -> &mut PlainEditor<Brush> {
&mut self.editor
}
pub fn text(&self) -> SplitString<'_> {
self.editor.text()
}
pub fn cursor_reset(&mut self) {
self.start_time = Some(Instant::now());
// TODO: for real world use, this should be reading from the system settings
self.blink_period = Duration::from_millis(500);
self.cursor_visible = true;
}
pub fn disable_blink(&mut self) {
self.start_time = None;
}
pub fn next_blink_time(&self) -> Option<Instant> {
self.start_time.map(|start_time| {
let phase = Instant::now().duration_since(start_time);
start_time
+ Duration::from_nanos(
((phase.as_nanos() / self.blink_period.as_nanos() + 1)
* self.blink_period.as_nanos()) as u64,
)
})
}
pub fn cursor_blink(&mut self) {
self.cursor_visible = self.start_time.is_some_and(|start_time| {
let elapsed = Instant::now().duration_since(start_time);
(elapsed.as_millis() / self.blink_period.as_millis()) % 2 == 0
});
}
pub fn handle_event(&mut self, event: WindowEvent) {
match event {
WindowEvent::Resized(size) => {
self.editor
.set_width(Some(size.width as f32 - 2_f32 * INSET));
}
WindowEvent::ModifiersChanged(modifiers) => {
self.modifiers = Some(modifiers);
}
WindowEvent::KeyboardInput { event, .. } if !self.editor.is_composing() => {
if !event.state.is_pressed() {
return;
}
self.cursor_reset();
let mut drv = self.editor.driver(&mut self.font_cx, &mut self.layout_cx);
#[allow(unused)]
let (shift, action_mod) = self
.modifiers
.map(|mods| {
(
mods.state().shift_key(),
if cfg!(target_os = "macos") {
mods.state().super_key()
} else {
mods.state().control_key()
},
)
})
.unwrap_or_default();
match event.logical_key {
#[cfg(any(target_os = "windows", target_os = "macos", target_os = "linux"))]
Key::Character(c) if action_mod && matches!(c.as_str(), "c" | "x" | "v") => {
use clipboard_rs::{Clipboard, ClipboardContext};
match c.to_lowercase().as_str() {
"c" => {
if let Some(text) = drv.editor.selected_text() {
let cb = ClipboardContext::new().unwrap();
cb.set_text(text.to_owned()).ok();
}
}
"x" => {
if let Some(text) = drv.editor.selected_text() {
let cb = ClipboardContext::new().unwrap();
cb.set_text(text.to_owned()).ok();
drv.delete_selection();
}
}
"v" => {
let cb = ClipboardContext::new().unwrap();
let text = cb.get_text().unwrap_or_default();
drv.insert_or_replace_selection(&text);
}
_ => (),
}
}
Key::Character(c) if action_mod && matches!(c.to_lowercase().as_str(), "a") => {
if shift {
drv.collapse_selection();
} else {
drv.select_all();
}
}
Key::Named(NamedKey::ArrowLeft) => {
if action_mod {
if shift {
drv.select_word_left();
} else {
drv.move_word_left();
}
} else if shift {
drv.select_left();
} else {
drv.move_left();
}
}
Key::Named(NamedKey::ArrowRight) => {
if action_mod {
if shift {
drv.select_word_right();
} else {
drv.move_word_right();
}
} else if shift {
drv.select_right();
} else {
drv.move_right();
}
}
Key::Named(NamedKey::ArrowUp) => {
if shift {
drv.select_up();
} else {
drv.move_up();
}
}
Key::Named(NamedKey::ArrowDown) => {
if shift {
drv.select_down();
} else {
drv.move_down();
}
}
Key::Named(NamedKey::Home) => {
if action_mod {
if shift {
drv.select_to_text_start();
} else {
drv.move_to_text_start();
}
} else if shift {
drv.select_to_line_start();
} else {
drv.move_to_line_start();
}
}
Key::Named(NamedKey::End) => {
let this = &mut *self;
let mut drv = this.driver();
if action_mod {
if shift {
drv.select_to_text_end();
} else {
drv.move_to_text_end();
}
} else if shift {
drv.select_to_line_end();
} else {
drv.move_to_line_end();
}
}
Key::Named(NamedKey::Delete) => {
if action_mod {
drv.delete_word();
} else {
drv.delete();
}
}
Key::Named(NamedKey::Backspace) => {
if action_mod {
drv.backdelete_word();
} else {
drv.backdelete();
}
}
Key::Named(NamedKey::Enter) => {
drv.insert_or_replace_selection("\n");
}
Key::Named(NamedKey::Space) => {
drv.insert_or_replace_selection(" ");
}
Key::Character(s) => {
drv.insert_or_replace_selection(&s);
}
_ => (),
}
}
WindowEvent::Touch(Touch {
phase, location, ..
}) if !self.editor.is_composing() => {
let mut drv = self.editor.driver(&mut self.font_cx, &mut self.layout_cx);
use winit::event::TouchPhase::*;
match phase {
Started => {
// TODO: start a timer to convert to a SelectWordAtPoint
drv.move_to_point(location.x as f32 - INSET, location.y as f32 - INSET);
}
Cancelled => {
drv.collapse_selection();
}
Moved => {
// TODO: cancel SelectWordAtPoint timer
drv.extend_selection_to_point(
location.x as f32 - INSET,
location.y as f32 - INSET,
);
}
Ended => (),
}
}
WindowEvent::MouseInput { state, button, .. } => {
if button == winit::event::MouseButton::Left {
self.pointer_down = state.is_pressed();
self.cursor_reset();
if self.pointer_down && !self.editor.is_composing() {
let now = Instant::now();
if let Some(last) = self.last_click_time.take() {
if now.duration_since(last).as_secs_f64() < 0.25 {
self.click_count = (self.click_count + 1) % 4;
} else {
self.click_count = 1;
}
} else {
self.click_count = 1;
}
self.last_click_time = Some(now);
let click_count = self.click_count;
let cursor_pos = self.cursor_pos;
let mut drv = self.editor.driver(&mut self.font_cx, &mut self.layout_cx);
match click_count {
2 => drv.select_word_at_point(cursor_pos.0, cursor_pos.1),
3 => drv.select_line_at_point(cursor_pos.0, cursor_pos.1),
_ => drv.move_to_point(cursor_pos.0, cursor_pos.1),
}
}
}
}
WindowEvent::CursorMoved { position, .. } => {
let prev_pos = self.cursor_pos;
self.cursor_pos = (position.x as f32 - INSET, position.y as f32 - INSET);
// macOS seems to generate a spurious move after selecting word?
if self.pointer_down && prev_pos != self.cursor_pos && !self.editor.is_composing() {
self.cursor_reset();
let cursor_pos = self.cursor_pos;
self.driver()
.extend_selection_to_point(cursor_pos.0, cursor_pos.1);
}
}
WindowEvent::Ime(Ime::Disabled) => {
self.driver().clear_compose();
}
WindowEvent::Ime(Ime::Commit(text)) => {
self.driver().insert_or_replace_selection(&text);
}
WindowEvent::Ime(Ime::Preedit(text, cursor)) => {
if text.is_empty() {
self.driver().clear_compose();
} else {
self.driver().set_compose(&text, cursor);
}
}
_ => {}
}
}
pub fn handle_accesskit_action_request(&mut self, req: &accesskit::ActionRequest) {
if req.action == accesskit::Action::SetTextSelection {
if let Some(accesskit::ActionData::SetTextSelection(selection)) = &req.data {
self.driver().select_from_accesskit(selection);
}
}
}
/// Return the current `Generation` of the layout.
pub fn generation(&self) -> Generation {
self.editor.generation()
}
/// Draw into scene.
///
/// Returns drawn `Generation`.
pub fn draw(&mut self, scene: &mut Scene) -> Generation {
let transform = Affine::translate((INSET as f64, INSET as f64));
for rect in self.editor.selection_geometry().iter() {
scene.fill(
Fill::NonZero,
transform,
palette::css::STEEL_BLUE,
None,
&rect,
);
}
if self.cursor_visible {
if let Some(cursor) = self.editor.cursor_geometry(1.5) {
scene.fill(Fill::NonZero, transform, palette::css::WHITE, None, &cursor);
}
}
let layout = self.editor.layout(&mut self.font_cx, &mut self.layout_cx);
for line in layout.lines() {
for item in line.items() {
let PositionedLayoutItem::GlyphRun(glyph_run) = item else {
continue;
};
let style = glyph_run.style();
// We draw underlines under the text, then the strikethrough on top, following:
// https://drafts.csswg.org/css-text-decor/#painting-order
if let Some(underline) = &style.underline {
let underline_brush = &style.brush;
let run_metrics = glyph_run.run().metrics();
let offset = match underline.offset {
Some(offset) => offset,
None => run_metrics.underline_offset,
};
let width = match underline.size {
Some(size) => size,
None => run_metrics.underline_size,
};
// The `offset` is the distance from the baseline to the top of the underline
// so we move the line down by half the width
// Remember that we are using a y-down coordinate system
// If there's a custom width, because this is an underline, we want the custom
// width to go down from the default expectation
let y = glyph_run.baseline() - offset + width / 2.;
let line = Line::new(
(glyph_run.offset() as f64, y as f64),
((glyph_run.offset() + glyph_run.advance()) as f64, y as f64),
);
scene.stroke(
&Stroke::new(width.into()),
transform,
underline_brush,
None,
&line,
);
}
let mut x = glyph_run.offset();
let y = glyph_run.baseline();
let run = glyph_run.run();
let font = run.font();
let font_size = run.font_size();
let synthesis = run.synthesis();
let glyph_xform = synthesis
.skew()
.map(|angle| Affine::skew(angle.to_radians().tan() as f64, 0.0));
scene
.draw_glyphs(font)
.brush(&style.brush)
.hint(true)
.transform(transform)
.glyph_transform(glyph_xform)
.font_size(font_size)
.normalized_coords(run.normalized_coords())
.draw(
Fill::NonZero,
glyph_run.glyphs().map(|glyph| {
let gx = x + glyph.x;
let gy = y - glyph.y;
x += glyph.advance;
vello::Glyph {
id: glyph.id as _,
x: gx,
y: gy,
}
}),
);
if let Some(strikethrough) = &style.strikethrough {
let strikethrough_brush = &style.brush;
let run_metrics = glyph_run.run().metrics();
let offset = match strikethrough.offset {
Some(offset) => offset,
None => run_metrics.strikethrough_offset,
};
let width = match strikethrough.size {
Some(size) => size,
None => run_metrics.strikethrough_size,
};
// The `offset` is the distance from the baseline to the *top* of the strikethrough
// so we calculate the middle y-position of the strikethrough based on the font's
// standard strikethrough width.
// Remember that we are using a y-down coordinate system
let y = glyph_run.baseline() - offset + run_metrics.strikethrough_size / 2.;
let line = Line::new(
(glyph_run.offset() as f64, y as f64),
((glyph_run.offset() + glyph_run.advance()) as f64, y as f64),
);
scene.stroke(
&Stroke::new(width.into()),
transform,
strikethrough_brush,
None,
&line,
);
}
}
}
self.editor.generation()
}
pub fn accessibility(&mut self, update: &mut TreeUpdate, node: &mut Node) {
let mut drv = self.editor.driver(&mut self.font_cx, &mut self.layout_cx);
drv.accessibility(update, node, next_node_id, INSET.into(), INSET.into());
}
}
pub const LOREM: &str = r" Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi cursus mi sed euismod euismod. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nullam placerat efficitur tellus at semper. Morbi ac risus magna. Donec ut cursus ex. Etiam quis posuere tellus. Mauris posuere dui et turpis mollis, vitae luctus tellus consectetur. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu facilisis nisl.
Phasellus in viverra dolor, vitae facilisis est. Maecenas malesuada massa vel ultricies feugiat. Vivamus venenatis et gהתעשייה בנושא האינטרנטa nibh nec pharetra. Phasellus vestibulum elit enim, nec scelerisque orci faucibus id. Vivamus consequat purus sit amet orci egestas, non iaculis massa porttitor. Vestibulum ut eros leo. In fermentum convallis magna in finibus. Donec justo leo, maximus ac laoreet id, volutpat ut elit. Mauris sed leo non neque laoreet faucibus. Aliquam orci arcu, faucibus in molestie eget, ornare non dui. Donec volutpat nulla in fringilla elementum. Aliquam vitae ante egestas ligula tempus vestibulum sit amet sed ante. ";