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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! Scrollable and selectable label
use super::{ScrollBar, ScrollBarMsg};
use kas::event::components::{ScrollComponent, TextInput, TextInputAction};
use kas::event::{CursorIcon, FocusSource, Scroll};
use kas::prelude::*;
use kas::text::SelectionHelper;
use kas::text::format::FormattableText;
use kas::theme::{Text, TextClass};
#[impl_self]
mod SelectableText {
/// A text label supporting selection
///
/// The [`ScrollText`] widget should be preferred in most cases; this widget
/// is a component of `ScrollText` and has some special behaviour.
///
/// By default, this uses [`TextClass::Standard`]; see [`Self::set_class`]
/// and [`Self::with_class`].
///
/// Line-wrapping is enabled; default alignment is derived from the script
/// (usually top-left).
///
/// ### Special behaviour
///
/// This is a [`Viewport`] widget.
#[widget]
#[layout(self.text)]
pub struct SelectableText<A, T: FormattableText + 'static> {
core: widget_core!(),
text: Text<T>,
text_fn: Option<Box<dyn Fn(&ConfigCx, &A) -> T>>,
selection: SelectionHelper,
has_sel_focus: bool,
input_handler: TextInput,
}
impl Layout for Self {
fn size_rules(&mut self, cx: &mut SizeCx, axis: AxisInfo) -> SizeRules {
let mut rules = kas::MacroDefinedLayout::size_rules(self, cx, axis);
if axis.is_vertical()
&& let Some(width) = axis.other()
{
let height = self
.text
.measure_height(width.cast(), std::num::NonZero::new(3));
rules.reduce_min_to(height.cast_ceil());
}
rules
}
}
impl Viewport for Self {
#[inline]
fn content_size(&self) -> Size {
if let Ok((tl, br)) = self.text.bounding_box() {
(br - tl).cast_ceil()
} else {
Size::ZERO
}
}
fn draw_with_offset(&self, mut draw: DrawCx, rect: Rect, offset: Offset) {
let pos = self.rect().pos - offset;
if self.selection.is_empty() {
draw.text_with_position(pos, rect, &self.text);
} else {
draw.text_with_selection(pos, rect, &self.text, self.selection.range());
}
}
}
impl Tile for Self {
fn role(&self, _: &mut dyn RoleCx) -> Role<'_> {
Role::TextLabel {
text: self.text.as_str(),
cursor: self.selection.edit_index(),
sel_index: self.selection.sel_index(),
}
}
}
impl<T: FormattableText + 'static> SelectableText<(), T> {
/// Construct a `SelectableText` with the given inital `text`
///
/// The text is set from input data on update.
#[inline]
pub fn new(text: T) -> Self {
SelectableText {
core: Default::default(),
text: Text::new(text, TextClass::Standard, true),
text_fn: None,
selection: SelectionHelper::default(),
has_sel_focus: false,
input_handler: Default::default(),
}
}
/// Set or replace the text derivation function
///
/// The text is set from input data on update.
#[inline]
pub fn with_fn<A>(
self,
text_fn: impl Fn(&ConfigCx, &A) -> T + 'static,
) -> SelectableText<A, T> {
SelectableText {
core: self.core,
text: self.text,
text_fn: Some(Box::new(text_fn)),
selection: self.selection,
has_sel_focus: self.has_sel_focus,
input_handler: self.input_handler,
}
}
}
impl Self {
/// Construct an `SelectableText` with the given text derivation function
///
/// The text is set from input data on update.
#[inline]
pub fn new_fn(text_fn: impl Fn(&ConfigCx, &A) -> T + 'static) -> Self
where
T: Default,
{
SelectableText::<(), T>::new(T::default()).with_fn(text_fn)
}
/// Get text contents
#[inline]
pub fn as_str(&self) -> &str {
self.text.as_str()
}
/// Set text in an existing `Label`
///
/// Note: this must not be called before fonts have been initialised
/// (usually done by the theme when the main loop starts).
///
/// Returns `true` when the content size may have changed.
pub fn set_text(&mut self, text: T) -> bool {
self.text.set_text(text);
if !self.text.prepare() {
return false;
}
self.selection.set_max_len(self.text.str_len());
true
}
/// Get text class
#[inline]
pub fn class(&self) -> TextClass {
self.text.class()
}
/// Set text class
///
/// Default: [`TextClass::Standard`]
#[inline]
pub fn set_class(&mut self, class: TextClass) {
self.text.set_class(class);
}
/// Set text class (inline)
///
/// Default: [`TextClass::Standard`]
#[inline]
pub fn with_class(mut self, class: TextClass) -> Self {
self.text.set_class(class);
self
}
fn set_cursor_from_coord(&mut self, cx: &mut EventCx, coord: Coord) {
let rel_pos = (coord - self.rect().pos).cast();
if let Ok(index) = self.text.text_index_nearest(rel_pos) {
if index != self.selection.edit_index() {
self.selection.set_edit_index(index);
self.set_view_offset_from_cursor(cx, index);
cx.redraw();
}
}
}
fn set_primary(&self, cx: &mut EventCx) {
if self.has_sel_focus && !self.selection.is_empty() && cx.has_primary() {
let range = self.selection.range();
cx.set_primary(String::from(&self.text.as_str()[range]));
}
}
/// Update view_offset from `cursor`
///
/// This method is mostly identical to its counterpart in `EditField`.
fn set_view_offset_from_cursor(&mut self, cx: &mut EventCx, cursor: usize) {
if let Some(marker) = self
.text
.text_glyph_pos(cursor)
.ok()
.and_then(|mut m| m.next_back())
{
let y0 = (marker.pos.1 - marker.ascent).cast_floor();
let pos = Coord(marker.pos.0.cast_nearest(), y0);
let size = Size(0, i32::conv_ceil(marker.pos.1 - marker.descent) - y0);
cx.set_scroll(Scroll::Rect(Rect { pos, size }));
}
}
}
impl SelectableText<(), String> {
/// Set text contents from a string
///
/// Returns `true` when the content size may have changed.
#[inline]
pub fn set_string(&mut self, string: String) -> bool {
if self.text.set_string(string) {
self.text.prepare();
true
} else {
false
}
}
}
impl Events for Self {
type Data = A;
#[inline]
fn mouse_over_icon(&self) -> Option<CursorIcon> {
Some(CursorIcon::Text)
}
fn configure(&mut self, cx: &mut ConfigCx) {
self.text.configure(&mut cx.size_cx());
}
fn update(&mut self, cx: &mut ConfigCx, data: &A) {
if let Some(method) = self.text_fn.as_ref() {
if self.set_text(method(cx, data)) {
cx.resize();
}
}
}
fn handle_event(&mut self, cx: &mut EventCx, _: &Self::Data, event: Event) -> IsUsed {
match event {
Event::Command(cmd, _) => match cmd {
Command::Escape | Command::Deselect if !self.selection.is_empty() => {
self.selection.set_empty();
cx.redraw();
Used
}
Command::SelectAll => {
self.selection.set_sel_index(0);
self.selection.set_edit_index(self.text.str_len());
self.set_primary(cx);
cx.redraw();
Used
}
Command::Cut | Command::Copy => {
let range = self.selection.range();
cx.set_clipboard((self.text.as_str()[range]).to_string());
Used
}
_ => Unused,
},
Event::SelFocus(source) => {
self.has_sel_focus = true;
if source == FocusSource::Pointer {
self.set_primary(cx);
}
Used
}
Event::LostSelFocus => {
self.has_sel_focus = false;
self.selection.set_empty();
cx.redraw();
Used
}
event => match self.input_handler.handle(cx, self.id(), event) {
TextInputAction::Used => Used,
TextInputAction::Unused => Unused,
TextInputAction::PressStart {
coord,
clear,
repeats,
} => {
self.set_cursor_from_coord(cx, coord);
self.selection.set_anchor(clear);
if repeats > 1 {
self.selection.expand(&self.text, repeats >= 3);
}
if !self.has_sel_focus {
cx.request_sel_focus(self.id(), FocusSource::Pointer);
}
Used
}
TextInputAction::PressMove { coord, repeats } => {
self.set_cursor_from_coord(cx, coord);
if repeats > 1 {
self.selection.expand(&self.text, repeats >= 3);
}
Used
}
TextInputAction::PressEnd { .. } => {
if self.has_sel_focus {
self.set_primary(cx);
}
Used
}
},
}
}
}
}
/// A text label supporting selection
///
/// Line-wrapping is enabled; default alignment is derived from the script
/// (usually top-left).
pub type SelectableLabel<T> = SelectableText<(), T>;
#[impl_self]
mod ScrollText {
/// A text label supporting scrolling and selection
///
/// This widget is a wrapper around [`SelectableText`] enabling scrolling
/// and adding a vertical scroll bar.
///
/// By default, this uses [`TextClass::Standard`]; see [`Self::set_class`]
/// and [`Self::with_class`].
///
/// Line-wrapping is enabled; default alignment is derived from the script
/// (usually top-left).
///
/// ### Messages
///
/// [`kas::messages::SetScrollOffset`] may be used to set the scroll offset.
#[widget]
pub struct ScrollText<A, T: FormattableText + 'static> {
core: widget_core!(),
scroll: ScrollComponent,
// NOTE: text is a Viewport which doesn't use update methods, therefore we don't call them.
#[widget]
text: SelectableText<A, T>,
#[widget = &()]
vert_bar: ScrollBar<kas::dir::Down>,
}
impl Layout for Self {
fn size_rules(&mut self, cx: &mut SizeCx, axis: AxisInfo) -> SizeRules {
let mut rules = self.text.size_rules(cx, axis);
let _ = self.vert_bar.size_rules(cx, axis);
if axis.is_vertical() {
let dpem = cx.dpem(self.text.text.class());
rules.reduce_min_to((dpem * 4.0).cast_ceil());
}
rules.with_stretch(Stretch::Low)
}
fn set_rect(&mut self, cx: &mut SizeCx, mut rect: Rect, hints: AlignHints) {
self.core.set_rect(rect);
self.text.set_rect(cx, rect, hints);
let w = cx.scroll_bar_width().min(rect.size.0);
rect.pos.0 += rect.size.0 - w;
rect.size.0 = w;
self.vert_bar.set_rect(cx, rect, AlignHints::NONE);
self.update_content_size(cx);
}
fn draw(&self, mut draw: DrawCx) {
self.text
.draw_with_offset(draw.re(), self.rect(), self.scroll.offset());
// We use a new pass to draw the scroll bar over inner content, but
// only when required to minimize cost:
if self.vert_bar.currently_visible(draw.ev_state()) {
draw.with_pass(|draw| self.vert_bar.draw(draw));
}
}
}
impl Tile for Self {
fn role(&self, _: &mut dyn RoleCx) -> Role<'_> {
Role::ScrollRegion {
offset: self.scroll.offset(),
max_offset: self.scroll.max_offset(),
}
}
fn translation(&self, index: usize) -> Offset {
if index == widget_index!(self.text) {
self.scroll.offset()
} else {
Offset::ZERO
}
}
}
impl<T: FormattableText + 'static> ScrollText<(), T> {
/// Construct an `ScrollText` with the given inital `text`
///
/// The text is set from input data on update.
#[inline]
pub fn new(text: T) -> Self {
ScrollText {
core: Default::default(),
scroll: Default::default(),
text: SelectableText::new(text),
vert_bar: ScrollBar::new().with_invisible(true),
}
}
/// Set or replace the text derivation function
///
/// The text is set from input data on update.
#[inline]
pub fn with_fn<A>(
self,
text_fn: impl Fn(&ConfigCx, &A) -> T + 'static,
) -> ScrollText<A, T> {
ScrollText {
core: self.core,
scroll: self.scroll,
text: self.text.with_fn(text_fn),
vert_bar: self.vert_bar,
}
}
}
impl Self {
/// Construct an `ScrollText` with the given text derivation function
///
/// The text is set from input data on update.
#[inline]
pub fn new_fn(text_fn: impl Fn(&ConfigCx, &A) -> T + 'static) -> Self
where
T: Default,
{
ScrollText::<(), T>::new(T::default()).with_fn(text_fn)
}
/// Get text contents
pub fn as_str(&self) -> &str {
self.text.as_str()
}
/// Replace text
///
/// Note: this must not be called before fonts have been initialised
/// (usually done by the theme when the main loop starts).
pub fn set_text(&mut self, cx: &mut EventState, text: T) {
if self.text.set_text(text) {
self.update_content_size(cx);
cx.redraw(self);
}
}
/// Get text class
#[inline]
pub fn class(&self) -> TextClass {
self.text.class()
}
/// Set text class
///
/// Default: [`TextClass::Standard`]
#[inline]
pub fn set_class(&mut self, class: TextClass) {
self.text.set_class(class);
}
/// Set text class (inline)
///
/// Default: [`TextClass::Standard`]
#[inline]
pub fn with_class(mut self, class: TextClass) -> Self {
self.text.set_class(class);
self
}
fn update_content_size(&mut self, cx: &mut EventState) {
if !self.core.status.is_sized() {
return;
}
let size = self.rect().size;
let _ = self.scroll.set_sizes(size, self.text.content_size());
self.vert_bar
.set_limits(cx, self.scroll.max_offset().1, size.1);
self.vert_bar.set_value(cx, self.scroll.offset().1);
}
}
impl ScrollText<(), String> {
/// Set text contents from a string
pub fn set_string(&mut self, cx: &mut EventState, string: String) {
if self.text.set_string(string) {
self.update_content_size(cx);
}
}
}
impl Events for Self {
type Data = A;
fn probe(&self, coord: Coord) -> Id {
self.vert_bar
.try_probe(coord)
.unwrap_or_else(|| self.text.id())
}
#[inline]
fn mouse_over_icon(&self) -> Option<CursorIcon> {
Some(CursorIcon::Text)
}
fn handle_event(&mut self, cx: &mut EventCx, _: &Self::Data, event: Event) -> IsUsed {
let is_used = self
.scroll
.scroll_by_event(cx, event, self.id(), self.rect());
self.vert_bar.set_value(cx, self.scroll.offset().1);
is_used
}
fn handle_messages(&mut self, cx: &mut EventCx, _: &Self::Data) {
let action = if cx.last_child() == Some(widget_index![self.vert_bar])
&& let Some(ScrollBarMsg(y)) = cx.try_pop()
{
let offset = Offset(self.scroll.offset().0, y);
self.scroll.set_offset(offset)
} else if let Some(kas::messages::SetScrollOffset(offset)) = cx.try_pop() {
self.scroll.set_offset(offset)
} else {
return;
};
if let Some(moved) = action {
cx.action_moved(moved);
self.vert_bar.set_value(cx, self.scroll.offset().1);
}
}
fn handle_resize(&mut self, cx: &mut ConfigCx, _: &Self::Data) -> Option<ActionResize> {
let size = self.text.rect().size;
let axis = AxisInfo::new(false, Some(size.1));
let mut resize = self.text.size_rules(&mut cx.size_cx(), axis).min_size() > size.0;
let axis = AxisInfo::new(true, Some(size.0));
resize |= self.text.size_rules(&mut cx.size_cx(), axis).min_size() > size.1;
self.text
.set_rect(&mut cx.size_cx(), self.text.rect(), Default::default());
self.update_content_size(cx);
resize.then_some(ActionResize)
}
fn handle_scroll(&mut self, cx: &mut EventCx, _: &Self::Data, scroll: Scroll) {
self.scroll.scroll(cx, self.id(), self.rect(), scroll);
self.vert_bar.set_value(cx, self.scroll.offset().1);
}
}
}
/// A text label supporting scrolling and selection
///
/// This widget is a wrapper around [`SelectableText`] enabling scrolling
/// and adding a vertical scroll bar.
///
/// Line-wrapping is enabled; default alignment is derived from the script
/// (usually top-left).
pub type ScrollLabel<T> = ScrollText<(), T>;