1use crate::{Axis, Event, Flags, Id, Signal, Spec, Ui, fit, px};
2use accesskit::Role;
3use draw::RasterImage;
4use draw::edit::{self, Command, Movement};
5use parley::{
6 Affinity,
7 editing::{Cursor, Selection},
8};
9use std::{hash::Hash, time::Duration};
10use winit::{
11 event::Ime,
12 keyboard::{Key, ModifiersState, NamedKey},
13 window::CursorIcon,
14};
15
16/// A labelled push button that fills with the accent tint under the pointer.
17pub fn button(ui: &mut Ui, part: impl Hash, text: &str) -> Signal {
18 let theme = &ui.theme;
19 let spec = Spec {
20 flags: Flags::CLICKABLE,
21 size: [fit(), px(theme.font_size * 2.0)],
22 text: Some(text),
23 fill: Some(theme.chip),
24 hover_fill: Some(theme.hover()),
25 hover_border: Some(theme.accent),
26 radius: 4.0,
27 pad: [theme.font_size * 0.75, 0.0],
28 center: true,
29 role: Some(Role::Button),
30 ..Spec::default()
31 };
32 ui.leaf(part, spec)
33}
34
35/// Cancel and a dialog's default button `text`, which takes no clicks while not `enabled`,
36/// in the platform's order: the default last on macOS and GNOME, first on Windows, as their
37/// own dialogs place them. The default wears the accent around it. Whether each was clicked,
38/// Cancel first.
39pub fn dialog_buttons(ui: &mut Ui, text: &str, enabled: bool) -> [bool; 2] {
40 let [cancel, chosen, _] = dialog_buttons_with(ui, text, enabled, |_| false);
41 [cancel, chosen]
42}
43
44/// `dialog_buttons` with another button, which `other` builds and says was clicked: after the
45/// default on Windows, before Cancel elsewhere. Whether each was clicked, Cancel, the default,
46/// then the other.
47pub fn dialog_buttons_with(
48 ui: &mut Ui,
49 text: &str,
50 enabled: bool,
51 other: impl FnOnce(&mut Ui) -> bool,
52) -> [bool; 3] {
53 let default = |ui: &mut Ui| {
54 let theme = &ui.theme;
55 let spec = Spec {
56 flags: if enabled {
57 Flags::CLICKABLE
58 } else {
59 Flags::default()
60 },
61 size: [fit(), px(theme.font_size * 2.0)],
62 text: Some(text),
63 color: (!enabled).then_some(theme.text_dim),
64 fill: Some(theme.chip),
65 hover_fill: enabled.then(|| theme.hover()),
66 border: enabled.then_some(theme.accent),
67 radius: 4.0,
68 pad: [theme.font_size * 0.75, 0.0],
69 center: true,
70 role: Some(Role::DefaultButton),
71 ..Spec::default()
72 };
73 let clicked = ui.leaf("default", spec).clicked;
74 if !enabled && let Some(node) = ui.access(ui.id("default")) {
75 node.set_disabled();
76 }
77 clicked
78 };
79 let windows = edit::Platform::CURRENT == edit::Platform::Windows;
80 let mut chosen = windows && default(ui);
81 let other = other(ui);
82 let cancel = button(ui, "cancel", "Cancel").clicked;
83 if !windows {
84 chosen = default(ui);
85 }
86 [cancel, chosen, other]
87}
88
89/// A short tag in the accent's colour, centred in a box `height` tall, as BETA marks a
90/// feature still settling beside its name.
91pub fn badge(ui: &mut Ui, part: impl Hash, text: &str, height: f32) {
92 let theme = &ui.theme;
93 let [red, green, blue, _] = theme.accent;
94 let tall = (theme.font_size * 1.15).min(height).round();
95 let spec = Spec {
96 size: [fit(), px(tall)],
97 text: Some(text),
98 font_size: Some((theme.font_size * 0.7).round()),
99 bold: true,
100 color: Some(theme.accent),
101 fill: Some([red, green, blue, 0.16]),
102 radius: 3.0,
103 pad: [4.0, 0.0],
104 center: true,
105 ..Spec::default()
106 };
107 ui.open(
108 part,
109 Spec {
110 size: [crate::children(), px(height)],
111 pad: [0.0, ((height - tall) / 2.0).max(0.0)],
112 ..Spec::default()
113 },
114 );
115 ui.leaf("text", spec);
116 ui.close();
117}
118
119/// The width `badge` takes for `text`.
120pub fn badge_width(ui: &mut Ui, text: &str) -> f32 {
121 let size = (ui.theme.font_size * 0.7).round();
122 ui.texts.label(text, size, ui.frame).size[0] + 8.0
123}
124
125/// A check box before `label`, `checked` or not; a click on either reports for the caller
126/// to toggle.
127pub fn check_box(ui: &mut Ui, part: impl Hash, label: &str, checked: bool) -> Signal {
128 let theme = ui.theme.clone();
129 let [height, side] = [theme.font_size * 2.0, 16.0];
130 let margin = (height - side) / 2.0;
131 let id = ui.open(
132 part,
133 Spec {
134 flags: Flags::CLICKABLE,
135 size: [crate::children(), px(height)],
136 gap: 8.0,
137 role: Some(Role::CheckBox),
138 ..Spec::default()
139 },
140 );
141 if let Some(node) = ui.access(id) {
142 node.set_toggled(checked.into());
143 }
144 // A box's signal is taken once, so its hover and click are read together.
145 let signal = ui.signal(id);
146 ui.leaf(
147 "box",
148 Spec {
149 size: [px(side), px(height)],
150 inset: [0.0, margin, 0.0, margin],
151 fill: Some(if checked { theme.accent } else { theme.base }),
152 border: Some(if checked || signal.hovered {
153 theme.accent
154 } else {
155 crate::mix(theme.chip, theme.text, 0.45)
156 }),
157 radius: 3.0,
158 icon: checked.then_some(crate::popup::CHECK),
159 color: Some([1.0; 4]),
160 ..Spec::default()
161 },
162 );
163 ui.leaf(
164 "label",
165 Spec {
166 size: [fit(), px(height)],
167 text: Some(label),
168 ..Spec::default()
169 },
170 );
171 ui.close();
172 signal
173}
174
175/// How a segmented control draws its choice, as the platform draws its own.
176#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
177pub enum Segments {
178 /// A raised face sliding along a sunken track: macOS since 11, libadwaita's toggle
179 /// groups and Windows 11's segmented control.
180 #[default]
181 Track,
182 /// Buttons joined in a row, the chosen one pressed in: Mac OS X 10.6's segmented control
183 /// and Windows 7's toggle groups.
184 Joined,
185}
186
187/// `choices` side by side, equally wide, with `chosen` picked: a radio group named `label`
188/// for assistive technology. Tab enters at the choice, and arrows pick the one beside it.
189/// Returns the choice a click or the keyboard picks.
190pub fn segmented(
191 ui: &mut Ui,
192 part: impl Hash,
193 label: &str,
194 choices: &[&str],
195 chosen: usize,
196) -> Option<usize> {
197 let theme = ui.theme.clone();
198 let joined = ui.segments == Segments::Joined;
199 let dark = draw::oklab(theme.text)[0] > 0.5;
200 let [red, green, blue, _] = theme.text;
201 let ink = |alpha| [red, green, blue, alpha];
202 let height = theme.font_size * 2.0;
203 let widest = (choices.iter()).fold(0.0_f32, |widest, choice| widest.max(ui.measure(choice)[0]));
204 let width = (widest + 2.0 * theme.font_size).round();
205 // A track shows around its face; joined buttons fill their border.
206 let inset = if joined { 1.0 } else { 2.0 };
207 let button = |shade: f32| {
208 if dark {
209 crate::mix(theme.popup, theme.text, shade)
210 } else {
211 crate::mix([1.0; 4], theme.chip, 0.75 - shade * 4.0)
212 }
213 };
214 let group = ui.open(
215 part,
216 Spec {
217 size: [crate::children(), px(height)],
218 fill: Some(if joined {
219 button(0.12)
220 } else {
221 ink(if dark { 0.1 } else { 0.07 })
222 }),
223 gradient: joined.then(|| button(0.06)),
224 border: joined.then_some(theme.chip),
225 radius: if joined { 4.0 } else { 6.0 },
226 pad: [inset, inset],
227 role: Some(Role::RadioGroup),
228 ..Spec::default()
229 },
230 );
231 if let Some(node) = ui.access(group) {
232 node.set_label(label);
233 node.set_orientation(accesskit::Orientation::Horizontal);
234 }
235 let target = chosen as f32 * width;
236 let slid = if joined {
237 ui.hold(group.child("slide"), target)
238 } else {
239 ui.animate(group.child("slide"), target)
240 };
241 ui.leaf(
242 "thumb",
243 Spec {
244 flags: Flags::FLOAT,
245 size: [px(width), px(height - 2.0 * inset)],
246 position: [inset + slid, inset],
247 fill: Some(match (joined, dark) {
248 (true, _) => theme.accent,
249 (false, true) => crate::mix(theme.popup, theme.text, 0.3),
250 (false, false) => [1.0; 4],
251 }),
252 gradient: joined.then(|| crate::mix(theme.accent, [0.0, 0.0, 0.0, 1.0], 0.25)),
253 border: (!joined && !dark).then(|| ink(0.08)),
254 shadow: (!joined && !dark).then_some([0.0, 0.0, 0.0, 0.12]),
255 radius: if joined { 3.0 } else { 4.0 },
256 ..Spec::default()
257 },
258 );
259 // Rules between the choices; a track leaves them out beside its face.
260 for between in 1..choices.len() {
261 if !joined && (between == chosen || between == chosen + 1) {
262 continue;
263 }
264 let length = if joined { height - 2.0 } else { height * 0.5 };
265 ui.leaf(
266 ("rule", between),
267 Spec {
268 flags: Flags::FLOAT,
269 size: [px(1.0), px(length)],
270 position: [
271 inset + between as f32 * width - 0.5,
272 (height - length) / 2.0,
273 ],
274 fill: Some(if joined { theme.chip } else { ink(0.15) }),
275 ..Spec::default()
276 },
277 );
278 }
279 let mut picked = None;
280 for (index, choice) in choices.iter().enumerate() {
281 let on = index == chosen;
282 let id = ui.open(
283 index,
284 Spec {
285 flags: Flags::CLICKABLE,
286 size: [px(width), crate::fill()],
287 text: Some(choice),
288 color: Some(if on && joined { [1.0; 4] } else { theme.text }),
289 hover_fill: (!on).then(|| ink(0.06)),
290 radius: if joined { 3.0 } else { 4.0 },
291 center: true,
292 role: Some(Role::RadioButton),
293 ..Spec::default()
294 },
295 );
296 if let Some(node) = ui.access(id) {
297 node.set_toggled(on.into());
298 }
299 ui.close();
300 let signal = ui.signal(id);
301 // The keyboard's arrows pick the segment they move to, as a radio group's do.
302 let arrived = ui.lasted(id.child("focus"), signal.focused) == Duration::ZERO;
303 if !on && (signal.clicked || signal.focused && arrived) {
304 picked = Some(index);
305 }
306 }
307 ui.close();
308 picked
309}
310
311/// Scrollers the platform paints, fixed along the content's edges, as Mac OS X 10.6's are.
312pub struct Scrollers {
313 /// Across a scroller, in logical pixels.
314 pub thickness: f32,
315 pub paint: Box<dyn FnMut(&Scroller) -> PaintedScroller>,
316}
317
318/// A scroller as it is to be painted, in logical pixels.
319pub struct Scroller {
320 pub axis: Axis,
321 pub length: f32,
322 pub scale: f32,
323 /// Where the offset lies in its range, from 0 to 1.
324 pub value: f32,
325 /// How much of the content shows, from 0 to 1.
326 pub proportion: f32,
327 /// The part held down.
328 pub held: Option<ScrollerPart>,
329 /// Whether the window is key, which colours the knob.
330 pub active: bool,
331}
332
333#[derive(Clone, Copy, Debug, PartialEq, Eq)]
334pub enum ScrollerPart {
335 Decrement,
336 Increment,
337 Knob,
338 /// The track either side of the knob, which pages.
339 Slot,
340}
341
342/// A painted scroller and where its parts lie along it, from its start in logical pixels.
343#[derive(Clone)]
344pub struct PaintedScroller {
345 /// `length` by `thickness`, at the scroller's scale.
346 pub image: RasterImage,
347 pub knob: [f32; 2],
348 pub slot: [f32; 2],
349 pub decrement: [f32; 2],
350 pub increment: [f32; 2],
351}
352
353/// How long a held arrow or track waits before repeating, and then between steps.
354const REPEAT_DELAY: Duration = Duration::from_millis(300);
355const REPEAT: Duration = Duration::from_millis(50);
356
357/// A scrollbar along the far edge of the current box, for content whose scroll offset
358/// ranges over `range` while `view` of it shows, all in one unit: the platform's scroller
359/// where `Ui::scrollers` has one, otherwise a thumb in `color` over the content. With a
360/// `corner`, its far end leaves room for the other axis's scrollbar. Returns the offset
361/// the scrollbar chose.
362#[allow(clippy::too_many_arguments)]
363pub fn scrollbar(
364 ui: &mut Ui,
365 part: impl Hash,
366 axis: Axis,
367 offset: f32,
368 range: [f32; 2],
369 view: f32,
370 corner: bool,
371 color: [f32; 4],
372) -> Option<f32> {
373 if ui.scrollers.is_some() {
374 return system_scrollbar(ui, part, axis, offset, range, view, corner);
375 }
376 let along = usize::from(axis == Axis::Y);
377 let rect = ui.laid_out(ui.current())?;
378 let length = rect[along + 2] - rect[along];
379 let cross = rect[3 - along] - rect[1 - along];
380 let span = range[1] - range[0];
381 // A thumb keeps 4 from each end and the box's far edge, and is 6 across.
382 let track = length - 8.0 - if corner { 10.0 } else { 0.0 };
383 if span <= 0.0 || track <= 0.0 {
384 return None;
385 }
386 let size = (track * view / (view + span)).max(28.0).min(track);
387 let start = 4.0 + ((offset - range[0]) / span).clamp(0.0, 1.0) * (track - size);
388 let id = ui.id(&part);
389 let signal = ui.signal(id);
390 let pointer = ui.pointer().map(|pointer| pointer[along] - rect[along]);
391 if signal.pressed
392 && let Some(pointer) = pointer
393 {
394 ui.state(id).grab = pointer - start;
395 }
396 let chosen = signal.dragging.then_some(pointer).flatten().map(|pointer| {
397 let travel = (track - size).max(f32::EPSILON);
398 let fraction = ((pointer - ui.state(id).grab - 4.0) / travel).clamp(0.0, 1.0);
399 range[0] + fraction * span
400 });
401 let mut position = [0.0; 2];
402 position[along] = start;
403 position[1 - along] = cross - 10.0;
404 let mut extent = [px(6.0); 2];
405 extent[along] = px(size);
406 ui.leaf(
407 &part,
408 Spec {
409 flags: Flags::CLICKABLE | Flags::FLOAT,
410 size: extent,
411 position,
412 fill: Some(color),
413 hover_fill: Some([color[0], color[1], color[2], (color[3] * 1.6).min(1.0)]),
414 radius: 3.0,
415 cursor: Some(CursorIcon::Default),
416 ..Spec::default()
417 },
418 );
419 chosen
420}
421
422fn system_scrollbar(
423 ui: &mut Ui,
424 part: impl Hash,
425 axis: Axis,
426 offset: f32,
427 range: [f32; 2],
428 view: f32,
429 corner: bool,
430) -> Option<f32> {
431 let along = usize::from(axis == Axis::Y);
432 let rect = ui.laid_out(ui.current())?;
433 let span = range[1] - range[0];
434 let thickness = ui.scrollers.as_ref()?.thickness;
435 let length = rect[along + 2] - rect[along] - if corner { thickness } else { 0.0 };
436 if span <= 0.0 || length <= 0.0 {
437 return None;
438 }
439 let id = ui.id(&part);
440 let signal = ui.signal(id);
441 let pointer = ui.pointer().map(|pointer| pointer[along] - rect[along]);
442 let now = ui.now;
443 if !signal.pressed && !signal.dragging {
444 ui.state(id).held = None;
445 }
446 let request = Scroller {
447 axis,
448 length,
449 scale: ui.scale,
450 value: ((offset - range[0]) / span).clamp(0.0, 1.0),
451 proportion: (view / (view + span)).clamp(0.0, 1.0),
452 held: ui.state(id).held.map(|(part, _)| part),
453 active: ui.window_focused,
454 };
455 let painted = (ui.scrollers.as_mut()?.paint)(&request);
456 let within = |[start, end]: [f32; 2], at: f32| start <= at && at < end;
457 let line = (view / 20.0).max(1.0);
458 let mut chosen = None;
459 if let Some(at) = pointer
460 && (signal.pressed || signal.dragging)
461 {
462 if signal.pressed {
463 let hit = [
464 (ScrollerPart::Decrement, painted.decrement),
465 (ScrollerPart::Increment, painted.increment),
466 (ScrollerPart::Knob, painted.knob),
467 (ScrollerPart::Slot, painted.slot),
468 ]
469 .into_iter()
470 .find(|(_, extent)| within(*extent, at));
471 ui.state(id).held = hit.map(|(part, _)| (part, now));
472 ui.state(id).grab = at - painted.knob[0];
473 }
474 match ui.state(id).held {
475 Some((ScrollerPart::Knob, _)) => {
476 let travel =
477 (painted.slot[1] - painted.slot[0]) - (painted.knob[1] - painted.knob[0]);
478 let from = at - ui.state(id).grab - painted.slot[0];
479 let fraction = (from / travel.max(f32::EPSILON)).clamp(0.0, 1.0);
480 chosen = Some(range[0] + fraction * span);
481 }
482 Some((part, due)) if now >= due => {
483 let step = match part {
484 ScrollerPart::Decrement => -line,
485 ScrollerPart::Increment => line,
486 // The track pages towards the pointer and stops once the knob is under it.
487 _ if within(painted.knob, at) => 0.0,
488 _ if at < painted.knob[0] => line - view,
489 _ => view - line,
490 };
491 let delay = if signal.pressed { REPEAT_DELAY } else { REPEAT };
492 ui.state(id).held = Some((part, now + delay));
493 chosen = Some((offset + step).clamp(range[0], range[1]));
494 }
495 _ => {}
496 }
497 // A held part repeats on later frames.
498 ui.animating = true;
499 }
500 let mut position = [0.0; 2];
501 position[1 - along] = rect[3 - along] - rect[1 - along] - thickness;
502 let mut extent = [px(thickness); 2];
503 extent[along] = px(length);
504 ui.leaf(
505 &part,
506 Spec {
507 flags: Flags::CLICKABLE | Flags::FLOAT,
508 size: extent,
509 position,
510 image: Some(&painted.image),
511 cursor: Some(CursorIcon::Default),
512 ..Spec::default()
513 },
514 );
515 if axis == Axis::Y && corner {
516 // The corner between the two scrollers shows the content's white, as AppKit's does.
517 ui.leaf(
518 ("corner", &part),
519 Spec {
520 flags: Flags::FLOAT,
521 size: [px(thickness); 2],
522 position: [position[0], length],
523 fill: Some([1.0; 4]),
524 ..Spec::default()
525 },
526 );
527 }
528 chosen
529}
530
531/// A single-line field editing `text`, showing `placeholder` while empty. Presses, drags
532/// and keys select and edit as on the page: a double press selects a word, a triple press
533/// everything, and dragging extends by that unit.
534pub fn text_field(
535 ui: &mut Ui,
536 id: Id,
537 text: &mut String,
538 placeholder: &str,
539 spec: Spec<'_>,
540) -> Signal {
541 field(ui, id, text, placeholder, spec, false)
542}
543
544/// A text field for a password, showing and announcing a bullet for each character.
545pub fn password_field(
546 ui: &mut Ui,
547 id: Id,
548 text: &mut String,
549 placeholder: &str,
550 spec: Spec<'_>,
551) -> Signal {
552 field(ui, id, text, placeholder, spec, true)
553}
554
555fn field(
556 ui: &mut Ui,
557 id: Id,
558 text: &mut String,
559 placeholder: &str,
560 spec: Spec<'_>,
561 secret: bool,
562) -> Signal {
563 const BULLET: &str = "\u{2022}";
564 // The text laid out, and where its offsets fall in `text`: a secret shows bullets.
565 let masked = |text: &str| {
566 if secret {
567 BULLET.repeat(text.chars().count())
568 } else {
569 text.to_owned()
570 }
571 };
572 let to_text = |text: &str, index: usize| match secret {
573 true => (text.char_indices().map(|(at, _)| at))
574 .nth(index / BULLET.len())
575 .unwrap_or(text.len()),
576 false => index,
577 };
578 let to_shown = |text: &str, index: usize| match secret {
579 true => text[..index].chars().count() * BULLET.len(),
580 false => index,
581 };
582 let mut shown_text = masked(text);
583 let signal = ui.signal(id);
584 let pad = spec.pad[0];
585 let size = ui.theme.font_size;
586 let modifiers = edit_modifiers(ui.modifiers());
587 let pointer = ui
588 .pointer()
589 .zip(ui.laid_out(id))
590 .map(|(pointer, rect)| pointer[0] - rect[0] - pad)
591 .filter(|_| signal.pressed || signal.dragging);
592 let state = ui.state(id);
593 let (mut selection, mut press, select) = (state.selection, state.press, state.select.take());
594 let before = [selection.anchor(), selection.focus()];
595 let (texts, frame) = (&mut ui.texts, ui.frame);
596 let mut label = texts.label(&shown_text, size, frame);
597 if let Some(x) = pointer {
598 let layout = &label.layout;
599 let unit = if signal.pressed { signal.unit } else { press.1 };
600 let hit = Cursor::from_point(layout, x, label.size[1] / 2.0);
601 let target = edit::selection_at(layout, hit, x, unit);
602 selection = if signal.pressed {
603 let pressed = if modifiers.shift {
604 Selection::new(selection.anchor(), target.focus())
605 } else {
606 target
607 };
608 press = (pressed, unit);
609 pressed
610 } else {
611 let [anchor, focus] = edit::drag(
612 [press.0.anchor(), press.0.focus()],
613 [target.anchor(), target.focus()],
614 unit,
615 |cursor| cursor.index(),
616 );
617 Selection::new(anchor, focus)
618 };
619 }
620 selection = if let Some([anchor, focus]) = select {
621 Selection::new(
622 Cursor::from_byte_index(&label.layout, anchor, Affinity::Downstream),
623 Cursor::from_byte_index(&label.layout, focus, Affinity::Upstream),
624 )
625 } else {
626 selection.refresh(&label.layout)
627 };
628 for event in &signal.events {
629 let layout = &label.layout;
630 let (range, inserted) = match event {
631 Event::Ime(Ime::Commit(committed)) => (selection.text_range(), committed.as_str()),
632 Event::Key { key, text: typed } => {
633 let key = edit_key(key);
634 // One line has no break for Control-K to join, nor room for Home, End and the
635 // page keys to scroll.
636 let command = match (Command::from_key(&key, modifiers), &key) {
637 (Some(Command::Kill), _) => Some(Command::DeleteTo(Movement::LineEnd)),
638 (
639 Some(
640 Command::ScrollPage { .. }
641 | Command::MovePage { .. }
642 | Command::MoveParagraphs { .. },
643 ),
644 _,
645 ) => None,
646 (None, edit::Key::Named(edit::NamedKey::Home)) => {
647 Some(Command::Move(Movement::DocumentStart))
648 }
649 (None, edit::Key::Named(edit::NamedKey::End)) => {
650 Some(Command::Move(Movement::DocumentEnd))
651 }
652 (command, _) => command,
653 };
654 let collapsed = selection.is_collapsed();
655 match (command, key) {
656 (Some(Command::Move(movement)), _) => {
657 selection = edit::step(layout, selection, movement, modifiers.shift);
658 continue;
659 }
660 (Some(Command::DeleteTo(movement)), _) if collapsed => (
661 edit::step(layout, selection, movement, true).text_range(),
662 "",
663 ),
664 (Some(Command::Delete { backward }), _) if collapsed => {
665 let caret = selection.focus();
666 let cluster = caret.logical_clusters(layout)[usize::from(!backward)];
667 (
668 cluster.map_or(caret.index()..caret.index(), |cluster| {
669 cluster.text_range()
670 }),
671 "",
672 )
673 }
674 (Some(_), _) => (selection.text_range(), ""),
675 (None, edit::Key::Character(character))
676 if modifiers.command && character.eq_ignore_ascii_case("a") =>
677 {
678 selection = Selection::new(
679 Cursor::from_byte_index(layout, 0, Affinity::Downstream),
680 Cursor::from_byte_index(layout, usize::MAX, Affinity::Upstream),
681 );
682 continue;
683 }
684 (None, _) => match typed.as_deref().filter(|typed| {
685 !modifiers.command
686 && !modifiers.control
687 && !typed.is_empty()
688 && !typed.chars().any(char::is_control)
689 }) {
690 Some(typed) => (selection.text_range(), typed),
691 None => continue,
692 },
693 }
694 }
695 _ => continue,
696 };
697 let range = to_text(text, range.start)..to_text(text, range.end);
698 text.replace_range(range.clone(), inserted);
699 shown_text = masked(text);
700 label = texts.label(&shown_text, size, frame);
701 selection = Selection::from_byte_index(
702 &label.layout,
703 to_shown(text, range.start + inserted.len()),
704 Affinity::Downstream,
705 );
706 }
707 let moved = signal.pressed || before != [selection.anchor(), selection.focus()];
708 let state = ui.state(id);
709 state.selection = selection;
710 state.press = press;
711 let theme = ui.theme.clone();
712 let shown = if text.is_empty() {
713 placeholder
714 } else {
715 shown_text.as_str()
716 };
717 let height = spec.size[1];
718 let backdrop = spec.fill.unwrap_or(theme.base);
719 ui.open_as(
720 id,
721 Spec {
722 flags: spec.flags | Flags::CLICKABLE | Flags::FOCUSABLE,
723 text: Some(shown),
724 color: Some(if text.is_empty() {
725 theme.text_dim
726 } else {
727 theme.text
728 }),
729 cursor: Some(CursorIcon::Text),
730 role: spec.role.or(Some(if secret {
731 Role::PasswordInput
732 } else {
733 Role::TextInput
734 })),
735 ..spec
736 },
737 );
738 if let Some(node) = ui.access(id) {
739 node.set_value(shown_text.as_str());
740 if !placeholder.is_empty() {
741 node.set_placeholder(placeholder);
742 }
743 }
744 if signal.focused {
745 let line = label.size[1];
746 let top = match height.size {
747 crate::Size::Pixels(height) => (height - line) / 2.0,
748 _ => 0.0,
749 };
750 let fill = if ui.window_focused {
751 theme.selection
752 } else {
753 theme.inactive_selection
754 };
755 for (rect, _) in selection.geometry(&label.layout) {
756 ui.mark(
757 [pad + rect.x0 as f32, top, pad + rect.x1 as f32, top + line],
758 fill,
759 0.0,
760 );
761 }
762 if ui.window_focused && selection.is_collapsed() {
763 let opacity = ui.blink(id, moved);
764 let x = pad + selection.focus().geometry(&label.layout, 0.0).x0 as f32;
765 let half = edit::CARET_WIDTH / 2.0;
766 ui.mark(
767 [x - half, top, x + half, top + line],
768 edit::caret_color(theme.caret, backdrop, opacity),
769 half,
770 );
771 }
772 }
773 ui.close();
774 signal
775}
776
777/// A winit key in the editing vocabulary text fields and the page share.
778pub fn edit_key(key: &Key) -> edit::Key {
779 use edit::NamedKey as Edit;
780 match key {
781 Key::Character(text) => edit::Key::Character(text.to_string()),
782 Key::Named(named) => edit::Key::Named(match named {
783 NamedKey::Escape => Edit::Escape,
784 NamedKey::Tab => Edit::Tab,
785 NamedKey::Space => Edit::Space,
786 NamedKey::Enter => Edit::Enter,
787 NamedKey::Backspace => Edit::Backspace,
788 NamedKey::Delete => Edit::Delete,
789 NamedKey::ArrowLeft => Edit::ArrowLeft,
790 NamedKey::ArrowRight => Edit::ArrowRight,
791 NamedKey::ArrowUp => Edit::ArrowUp,
792 NamedKey::ArrowDown => Edit::ArrowDown,
793 NamedKey::Home => Edit::Home,
794 NamedKey::End => Edit::End,
795 NamedKey::PageUp => Edit::PageUp,
796 NamedKey::PageDown => Edit::PageDown,
797 NamedKey::F7 => Edit::F7,
798 NamedKey::F11 => Edit::F11,
799 NamedKey::Alt
800 | NamedKey::AltGraph
801 | NamedKey::Control
802 | NamedKey::Shift
803 | NamedKey::Super
804 | NamedKey::Meta => Edit::Modifier,
805 _ => Edit::Other,
806 }),
807 _ => edit::Key::Named(Edit::Other),
808 }
809}
810
811pub fn edit_modifiers(modifiers: ModifiersState) -> edit::Modifiers {
812 edit::Modifiers {
813 shift: modifiers.shift_key(),
814 control: modifiers.control_key(),
815 option: modifiers.alt_key(),
816 command: if edit::Platform::CURRENT == edit::Platform::MacOs {
817 modifiers.super_key()
818 } else {
819 modifiers.control_key()
820 },
821 }
822}