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 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
// 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
//! The [`EditField`] and [`EditBox`] widgets, plus supporting items
use crate::{ScrollBar, ScrollMsg};
use kas::event::components::{TextInput, TextInputAction};
use kas::event::{
Command, CursorIcon, ElementState, FocusSource, PhysicalKey, Scroll, ScrollDelta,
};
use kas::geom::Vec2;
use kas::prelude::*;
use kas::text::{NotReady, SelectionHelper, Text};
use kas::theme::{Background, FrameStyle, TextClass};
use std::fmt::{Debug, Display};
use std::marker::PhantomData;
use std::ops::Range;
use std::str::FromStr;
use unicode_segmentation::{GraphemeCursor, UnicodeSegmentation};
#[derive(Clone, Debug, Default, PartialEq)]
enum LastEdit {
#[default]
None,
Insert,
Delete,
Paste,
}
enum EditAction {
None,
Unused,
Activate,
Edit,
}
/// Event-handling *guard* for [`EditField`], [`EditBox`]
///
/// This is the most generic interface; see also constructors of [`EditField`],
/// [`EditBox`] for common use-cases.
///
/// All methods on this trait are passed a reference to the [`EditField`] as
/// parameter. The guard itself is a public field: `edit.guard`.
///
/// All methods have a default implementation which does nothing.
pub trait EditGuard: Sized {
/// Data type
type Data;
/// Configure guard
///
/// This function is called when the attached widget is configured.
fn configure(edit: &mut EditField<Self>, cx: &mut ConfigCx) {
let _ = (edit, cx);
}
/// Update guard
///
/// This function is called when input data is updated.
///
/// Note that this method may be called during editing as a result of a
/// message sent by [`Self::edit`] or another cause. It is recommended to
/// ignore updates for editable widgets with key focus
/// ([`EditField::has_edit_focus`]) to avoid overwriting user input;
/// [`Self::focus_lost`] may update the content instead.
/// For read-only fields this is not recommended (but `has_edit_focus` will
/// not be true anyway).
fn update(edit: &mut EditField<Self>, cx: &mut ConfigCx, data: &Self::Data) {
let _ = (edit, cx, data);
}
/// Activation guard
///
/// This function is called when the widget is "activated", for example by
/// the Enter/Return key for single-line edit boxes. Its result is returned
/// from `handle_event`.
///
/// The default implementation:
///
/// - If the field is editable, calls [`Self::focus_lost`] and returns
/// returns [`Used`].
/// - If the field is not editable, returns [`Unused`].
fn activate(edit: &mut EditField<Self>, cx: &mut EventCx, data: &Self::Data) -> IsUsed {
if edit.editable {
Self::focus_lost(edit, cx, data);
Used
} else {
Unused
}
}
/// Focus-gained guard
///
/// This function is called when the widget gains keyboard input focus.
fn focus_gained(edit: &mut EditField<Self>, cx: &mut EventCx, data: &Self::Data) {
let _ = (edit, cx, data);
}
/// Focus-lost guard
///
/// This function is called when the widget loses keyboard input focus.
fn focus_lost(edit: &mut EditField<Self>, cx: &mut EventCx, data: &Self::Data) {
let _ = (edit, cx, data);
}
/// Edit guard
///
/// This function is called when contents are updated by the user.
fn edit(edit: &mut EditField<Self>, cx: &mut EventCx, data: &Self::Data) {
let _ = (edit, cx, data);
}
}
/// Ignore all events and data updates
///
/// This guard should probably not be used for a functional user-interface but
/// may be useful in mock UIs.
#[autoimpl(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct DefaultGuard<A>(PhantomData<A>);
impl<A: 'static> EditGuard for DefaultGuard<A> {
type Data = A;
}
impl_scope! {
/// An [`EditGuard`] for read-only strings
///
/// This may be used with read-only edit fields, essentially resulting in a
/// fancier version of [`Text`](crate::Text) or
/// [`ScrollText`](crate::ScrollText).
#[autoimpl(Debug ignore self.value_fn, self.on_afl)]
pub struct StringGuard<A> {
value_fn: Box<dyn Fn(&A) -> String>,
on_afl: Option<Box<dyn Fn(&mut EventCx, &A, &str)>>,
edited: bool,
}
impl Self {
/// Construct with a value function
///
/// On update, `value_fn` is used to extract a value from input data.
/// If, however, the input field has focus, the update is ignored.
///
/// No other action happens unless [`Self::with_msg`] is used.
pub fn new(value_fn: impl Fn(&A) -> String + 'static) -> Self {
StringGuard {
value_fn: Box::new(value_fn),
on_afl: None,
edited: false,
}
}
/// Call the handler `f` on activation / focus loss
///
/// On field **a**ctivation and **f**ocus **l**oss (AFL) after an edit,
/// `f` is called.
pub fn with(mut self, f: impl Fn(&mut EventCx, &A, &str) + 'static) -> Self {
debug_assert!(self.on_afl.is_none());
self.on_afl = Some(Box::new(f));
self
}
/// Send the message generated by `f` on activation / focus loss
///
/// On field **a**ctivation and **f**ocus **l**oss (AFL) after an edit,
/// `f` is used to construct a message to be emitted via [`EventCx::push`].
pub fn with_msg<M: Debug + 'static>(self, f: impl Fn(&str) -> M + 'static) -> Self {
self.with(move |cx, _, value| cx.push(f(value)))
}
}
impl EditGuard for Self {
type Data = A;
fn focus_lost(edit: &mut EditField<Self>, cx: &mut EventCx, data: &A) {
if edit.guard.edited {
edit.guard.edited = false;
if let Some(ref on_afl) = edit.guard.on_afl {
return on_afl(cx, data, edit.get_str());
}
}
// Reset data on focus loss (update is inhibited with focus).
// No need if we just sent a message (should cause an update).
let string = (edit.guard.value_fn)(data);
let action = edit.set_string(string);
cx.action(edit, action);
}
fn update(edit: &mut EditField<Self>, cx: &mut ConfigCx, data: &A) {
if !edit.has_edit_focus() {
let string = (edit.guard.value_fn)(data);
let action = edit.set_string(string);
cx.action(edit, action);
}
}
fn edit(edit: &mut EditField<Self>, _: &mut EventCx, _: &Self::Data) {
edit.guard.edited = true;
}
}
}
impl_scope! {
/// An [`EditGuard`] for parsable types
///
/// This guard displays a value formatted from input data, updates the error
/// state according to parse success on each keystroke, and sends a message
/// on focus loss (where successful parsing occurred).
#[autoimpl(Debug ignore self.value_fn, self.on_afl)]
pub struct ParseGuard<A, T: Debug + Display + FromStr> {
parsed: Option<T>,
value_fn: Box<dyn Fn(&A) -> T>,
on_afl: Box<dyn Fn(&mut EventCx, T)>,
}
impl Self {
/// Construct
///
/// On update, `value_fn` is used to extract a value from input data
/// which is then formatted as a string via [`Display`].
/// If, however, the input field has focus, the update is ignored.
///
/// On every edit, the guard attempts to parse the field's input as type
/// `T` via [`FromStr`], caching the result and setting the error state.
///
/// On field activation and focus loss when a `T` value is cached (see
/// previous paragraph), `on_afl` is used to construct a message to be
/// emitted via [`EventCx::push`]. The cached value is then cleared to
/// avoid sending duplicate messages.
pub fn new<M: Debug + 'static>(
value_fn: impl Fn(&A) -> T + 'static,
on_afl: impl Fn(T) -> M + 'static,
) -> Self {
ParseGuard {
parsed: None,
value_fn: Box::new(value_fn),
on_afl: Box::new(move |cx, value| cx.push(on_afl(value))),
}
}
}
impl EditGuard for Self {
type Data = A;
fn focus_lost(edit: &mut EditField<Self>, cx: &mut EventCx, data: &A) {
if let Some(value) = edit.guard.parsed.take() {
(edit.guard.on_afl)(cx, value);
} else {
// Reset data on focus loss (update is inhibited with focus).
// No need if we just sent a message (should cause an update).
let value = (edit.guard.value_fn)(data);
let action = edit.set_string(format!("{}", value));
cx.action(edit, action);
}
}
fn edit(edit: &mut EditField<Self>, cx: &mut EventCx, _: &A) {
edit.guard.parsed = edit.get_str().parse().ok();
let action = edit.set_error_state(edit.guard.parsed.is_none());
cx.action(edit, action);
}
fn update(edit: &mut EditField<Self>, cx: &mut ConfigCx, data: &A) {
if !edit.has_edit_focus() {
let value = (edit.guard.value_fn)(data);
let action = edit.set_string(format!("{}", value));
cx.action(&edit, action);
edit.guard.parsed = None;
}
}
}
}
impl_scope! {
/// An as-you-type [`EditGuard`] for parsable types
///
/// This guard displays a value formatted from input data, updates the error
/// state according to parse success on each keystroke, and sends a message
/// immediately (where successful parsing occurred).
#[autoimpl(Debug ignore self.value_fn, self.on_afl)]
pub struct InstantParseGuard<A, T: Debug + Display + FromStr> {
value_fn: Box<dyn Fn(&A) -> T>,
on_afl: Box<dyn Fn(&mut EventCx, T)>,
}
impl Self {
/// Construct
///
/// On update, `value_fn` is used to extract a value from input data
/// which is then formatted as a string via [`Display`].
/// If, however, the input field has focus, the update is ignored.
///
/// On every edit, the guard attempts to parse the field's input as type
/// `T` via [`FromStr`]. On success, the result is converted to a
/// message via `on_afl` then emitted via [`EventCx::push`].
pub fn new<M: Debug + 'static>(
value_fn: impl Fn(&A) -> T + 'static,
on_afl: impl Fn(T) -> M + 'static,
) -> Self {
InstantParseGuard {
value_fn: Box::new(value_fn),
on_afl: Box::new(move |cx, value| cx.push(on_afl(value))),
}
}
}
impl EditGuard for Self {
type Data = A;
fn focus_lost(edit: &mut EditField<Self>, cx: &mut EventCx, data: &A) {
// Always reset data on focus loss
let value = (edit.guard.value_fn)(data);
let action = edit.set_string(format!("{}", value));
cx.action(edit, action);
}
fn edit(edit: &mut EditField<Self>, cx: &mut EventCx, _: &A) {
let result = edit.get_str().parse();
let action = edit.set_error_state(result.is_err());
cx.action(edit.id(), action);
if let Ok(value) = result {
(edit.guard.on_afl)(cx, value);
}
}
fn update(edit: &mut EditField<Self>, cx: &mut ConfigCx, data: &A) {
if !edit.has_edit_focus() {
let value = (edit.guard.value_fn)(data);
let action = edit.set_string(format!("{}", value));
cx.action(&edit, action);
}
}
}
}
impl_scope! {
/// A text-edit box
///
/// A single- or multi-line editor for unformatted text.
/// See also notes on [`EditField`].
///
/// By default, the editor supports a single-line only;
/// [`Self::with_multi_line`] and [`Self::with_class`] can be used to change this.
#[autoimpl(Deref, DerefMut, HasStr using self.inner)]
#[autoimpl(Clone, Default, Debug where G: trait)]
#[widget]
pub struct EditBox<G: EditGuard = DefaultGuard<()>> {
core: widget_core!(),
#[widget]
inner: EditField<G>,
#[widget(&())]
bar: ScrollBar<kas::dir::Down>,
frame_offset: Offset,
frame_size: Size,
inner_margin: i32,
}
impl Layout for Self {
fn size_rules(&mut self, sizer: SizeCx, mut axis: AxisInfo) -> SizeRules {
axis.sub_other(self.frame_size.extract(axis.flipped()));
let mut rules = self.inner.size_rules(sizer.re(), axis);
let bar_rules = self.bar.size_rules(sizer.re(), axis);
if axis.is_horizontal() && self.multi_line() {
self.inner_margin = rules.margins_i32().1.max(bar_rules.margins_i32().0);
rules.append(bar_rules);
}
let frame_rules = sizer.frame(FrameStyle::EditBox, axis);
let (rules, offset, size) = frame_rules.surround(rules);
self.frame_offset.set_component(axis, offset);
self.frame_size.set_component(axis, size);
rules
}
fn set_rect(&mut self, cx: &mut ConfigCx, outer_rect: Rect) {
self.core.rect = outer_rect;
let mut rect = outer_rect;
rect.pos += self.frame_offset;
rect.size -= self.frame_size;
let mut bar_rect = Rect::ZERO;
if self.multi_line() {
let bar_width = cx.size_cx().scroll_bar_width();
let x1 = rect.pos.0 + rect.size.0;
let x0 = x1 - bar_width;
bar_rect = Rect::new(Coord(x0, rect.pos.1), Size(bar_width, rect.size.1));
rect.size.0 = (rect.size.0 - bar_width - self.inner_margin).max(0);
}
self.bar.set_rect(cx, bar_rect);
self.inner.set_rect(cx, rect);
self.inner.set_outer_rect(outer_rect, FrameStyle::EditBox);
self.update_scroll_bar(cx);
}
fn find_id(&mut self, coord: Coord) -> Option<Id> {
if !self.rect().contains(coord) {
return None;
}
if self.max_scroll_offset().1 > 0 {
if let Some(id) = self.bar.find_id(coord) {
return Some(id);
}
}
// If coord is over self but not over self.bar, we assign
// the event to self.inner without further question.
Some(self.inner.id())
}
fn draw(&mut self, mut draw: DrawCx) {
draw.recurse(&mut self.inner);
if self.max_scroll_offset().1 > 0 {
draw.recurse(&mut self.bar);
}
}
}
impl Events for Self {
type Data = G::Data;
fn handle_messages(&mut self, cx: &mut EventCx<'_>, _: &G::Data) {
if let Some(ScrollMsg(y)) = cx.try_pop() {
self.inner
.set_scroll_offset(cx, Offset(self.inner.view_offset.0, y));
}
}
fn handle_scroll(&mut self, cx: &mut EventCx<'_>, _: &G::Data, _: Scroll) {
self.update_scroll_bar(cx);
}
}
impl Self {
fn update_scroll_bar(&mut self, cx: &mut EventState) {
let max_offset = self.inner.max_scroll_offset().1;
let action = self.bar.set_limits(max_offset, self.inner.rect().size.1);
cx.action(&self, action);
self.bar.set_value(cx, self.inner.view_offset.1);
}
}
impl HasString for Self {
fn set_string(&mut self, string: String) -> Action {
let mut action = self.inner.set_string(string);
if action.contains(Action::SCROLLED) {
action.remove(Action::SCROLLED);
let max_offset = self.inner.max_scroll_offset().1;
action |= self.bar.set_limits(max_offset, self.inner.rect().size.1);
}
action
}
}
impl ToString for Self {
fn to_string(&self) -> String {
self.inner.to_string()
}
}
}
impl<G: EditGuard> EditBox<G> {
/// Construct an `EditBox` with an [`EditGuard`]
#[inline]
pub fn new(guard: G) -> EditBox<G> {
EditBox {
core: Default::default(),
inner: EditField::new(guard),
bar: Default::default(),
frame_offset: Default::default(),
frame_size: Default::default(),
inner_margin: Default::default(),
}
}
}
impl<A: 'static> EditBox<DefaultGuard<A>> {
/// Construct an `EditBox` with the given inital `text` (no event handling)
#[inline]
pub fn text<S: ToString>(text: S) -> Self {
EditBox {
inner: EditField::text(text),
..Default::default()
}
}
/// Construct a read-only `EditBox` displaying some `String` value
#[inline]
pub fn string(value_fn: impl Fn(&A) -> String + 'static) -> EditBox<StringGuard<A>> {
EditBox::new(StringGuard::new(value_fn)).with_editable(false)
}
/// Construct an `EditBox` for a parsable value (e.g. a number)
///
/// On update, `value_fn` is used to extract a value from input data
/// which is then formatted as a string via [`Display`].
/// If, however, the input field has focus, the update is ignored.
///
/// On every edit, the guard attempts to parse the field's input as type
/// `T` via [`FromStr`], caching the result and setting the error state.
///
/// On field activation and focus loss when a `T` value is cached (see
/// previous paragraph), `on_afl` is used to construct a message to be
/// emitted via [`EventCx::push`]. The cached value is then cleared to
/// avoid sending duplicate messages.
#[inline]
pub fn parser<T: Debug + Display + FromStr, M: Debug + 'static>(
value_fn: impl Fn(&A) -> T + 'static,
msg_fn: impl Fn(T) -> M + 'static,
) -> EditBox<ParseGuard<A, T>> {
EditBox::new(ParseGuard::new(value_fn, msg_fn))
}
/// Construct an `EditBox` for a parsable value (e.g. a number)
///
/// On update, `value_fn` is used to extract a value from input data
/// which is then formatted as a string via [`Display`].
/// If, however, the input field has focus, the update is ignored.
///
/// On every edit, the guard attempts to parse the field's input as type
/// `T` via [`FromStr`]. On success, the result is converted to a
/// message via `on_afl` then emitted via [`EventCx::push`].
pub fn instant_parser<T: Debug + Display + FromStr, M: Debug + 'static>(
value_fn: impl Fn(&A) -> T + 'static,
msg_fn: impl Fn(T) -> M + 'static,
) -> EditBox<InstantParseGuard<A, T>> {
EditBox::new(InstantParseGuard::new(value_fn, msg_fn))
}
}
impl<A: 'static> EditBox<StringGuard<A>> {
/// Assign a message function for a `String` value
///
/// The `msg_fn` is called when the field is activated (<kbd>Enter</kbd>)
/// and when it loses focus after content is changed.
///
/// This method sets self as editable (see [`Self::with_editable`]).
#[must_use]
pub fn with_msg<M>(mut self, msg_fn: impl Fn(&str) -> M + 'static) -> Self
where
M: Debug + 'static,
{
self.inner.guard = self.inner.guard.with_msg(msg_fn);
self.inner.editable = true;
self
}
}
impl<G: EditGuard> EditBox<G> {
/// Set the initial text (inline)
///
/// This method should only be used on a new `EditBox`.
#[inline]
#[must_use]
pub fn with_text(mut self, text: impl ToString) -> Self {
self.inner = self.inner.with_text(text);
self
}
/// Set whether this widget is editable (inline)
#[inline]
#[must_use]
pub fn with_editable(mut self, editable: bool) -> Self {
self.inner = self.inner.with_editable(editable);
self
}
/// Set whether this `EditBox` uses multi-line mode
///
/// This setting has two effects: the vertical size allocation is increased
/// and wrapping is enabled if true. Default: false.
///
/// This method is ineffective if the text class is set by
/// [`Self::with_class`] to anything other than [`TextClass::Edit`].
#[inline]
#[must_use]
pub fn with_multi_line(mut self, multi_line: bool) -> Self {
self.inner = self.inner.with_multi_line(multi_line);
self
}
/// Set the text class used
#[inline]
#[must_use]
pub fn with_class(mut self, class: TextClass) -> Self {
self.inner = self.inner.with_class(class);
self
}
/// Adjust the height allocation (inline)
#[inline]
#[must_use]
pub fn with_lines(mut self, min_lines: i32, ideal_lines: i32) -> Self {
self.set_lines(min_lines, ideal_lines);
self
}
/// Adjust the width allocation (inline)
#[inline]
#[must_use]
pub fn with_width_em(mut self, min_em: f32, ideal_em: f32) -> Self {
self.set_width_em(min_em, ideal_em);
self
}
}
impl_scope! {
/// A text-edit field (single- or multi-line)
///
/// This widget implements the mechanics of text layout and event handling.
/// If you want a box with a border, use [`EditBox`] instead.
///
/// By default, the editor supports a single-line only;
/// [`Self::with_multi_line`] and [`Self::with_class`] can be used to change this.
///
/// ### Event handling
///
/// This widget attempts to handle all standard text-editor input and scroll
/// events.
///
/// Key events for moving the edit cursor (e.g. arrow keys) are consumed
/// only if the edit cursor is moved while key events for adjusting or using
/// the selection (e.g. `Command::Copy` and `Command::Deselect`)
/// are consumed only when a selection exists. In contrast, key events for
/// inserting or deleting text are always consumed.
///
/// [`Command::Enter`] inserts a line break in multi-line mode, but in
/// single-line mode or if the <kbd>Shift</kbd> key is held it is treated
/// the same as [`Command::Activate`].
///
/// ### Performance and limitations
///
/// Text representation is via a single [`String`]. Edit operations are
/// `O(n)` where `n` is the length of text (with text layout algorithms
/// having greater cost than copying bytes in the backing [`String`]).
/// This isn't necessarily *slow*; when run with optimizations the type can
/// handle type-setting around 20kB of UTF-8 in under 10ms (with significant
/// scope for optimization, given that currently layout is re-run from
/// scratch on each key stroke). Regardless, this approach is not designed
/// to scale to handle large documents via a single `EditField` widget.
#[impl_default(where G: Default)]
#[autoimpl(Clone, Debug where G: trait)]
#[widget{
navigable = true;
hover_highlight = true;
cursor_icon = CursorIcon::Text;
}]
pub struct EditField<G: EditGuard = DefaultGuard<()>> {
core: widget_core!(),
outer_rect: Rect,
frame_style: FrameStyle,
view_offset: Offset,
editable: bool,
class: TextClass = TextClass::Edit(false),
align: AlignPair,
width: (f32, f32) = (8.0, 16.0),
lines: (i32, i32) = (1, 1),
text: Text<String>,
text_size: Size,
selection: SelectionHelper,
edit_x_coord: Option<f32>,
old_state: Option<(String, usize, usize)>,
last_edit: LastEdit,
has_key_focus: bool,
error_state: bool,
input_handler: TextInput,
/// The associated [`EditGuard`] implementation
pub guard: G,
}
impl Layout for Self {
fn size_rules(&mut self, sizer: SizeCx, axis: AxisInfo) -> SizeRules {
let (min, ideal) = if axis.is_horizontal() {
let dpem = sizer.dpem();
((self.width.0 * dpem).cast_ceil(), (self.width.1 * dpem).cast_ceil())
} else {
let height = sizer.line_height(self.class);
(self.lines.0 * height, self.lines.1 * height)
};
let margins = sizer.text_margins().extract(axis);
let (stretch, align) = if axis.is_horizontal() || self.multi_line() {
(Stretch::High, axis.align_or_default())
} else {
(Stretch::None, axis.align_or_center())
};
self.align.set_component(axis, align);
SizeRules::new(min, ideal, margins, stretch)
}
fn set_rect(&mut self, cx: &mut ConfigCx, rect: Rect) {
self.core.rect = rect;
self.outer_rect = rect;
cx.text_set_size(&mut self.text, self.class, rect.size, Some(self.align));
self.text_size = Vec2::from(self.text.bounding_box().unwrap().1).cast_ceil();
self.view_offset = self.view_offset.min(self.max_scroll_offset());
}
fn find_id(&mut self, coord: Coord) -> Option<Id> {
self.outer_rect.contains(coord).then_some(self.id())
}
fn draw(&mut self, mut draw: DrawCx) {
let bg = if self.has_error() {
Background::Error
} else {
Background::Default
};
draw.frame(self.outer_rect, self.frame_style, bg);
let mut rect = self.rect();
rect.size = rect.size.max(self.text_size);
draw.with_clip_region(self.rect(), self.view_offset, |mut draw| {
if self.selection.is_empty() {
draw.text(rect, &self.text, self.class);
} else {
// TODO(opt): we could cache the selection rectangles here to make
// drawing more efficient (self.text.highlight_lines(range) output).
// The same applies to the edit marker below.
draw.text_selected(
rect,
&self.text,
self.selection.range(),
self.class,
);
}
if self.editable && draw.ev_state().has_key_focus(self.id_ref()).0 {
draw.text_cursor(
rect,
&self.text,
self.class,
self.selection.edit_pos(),
);
}
});
}
}
impl Events for Self {
type Data = G::Data;
fn configure(&mut self, cx: &mut ConfigCx) {
G::configure(self, cx);
}
fn update(&mut self, cx: &mut ConfigCx, data: &G::Data) {
G::update(self, cx, data);
}
fn handle_event(&mut self, cx: &mut EventCx, data: &G::Data, event: Event) -> IsUsed {
match event {
Event::NavFocus(source) if source.key_or_synthetic() => {
if !self.has_key_focus {
cx.request_key_focus(self.id(), source);
}
if source == FocusSource::Key && !self.class.multi_line() {
self.selection.clear();
self.selection.set_edit_pos(self.text.str_len());
cx.redraw(self);
}
Used
}
Event::NavFocus(_) => Used,
Event::LostNavFocus => {
if !self.class.multi_line() {
self.selection.set_empty();
cx.redraw(self);
}
Used
}
Event::SelFocus(source) => {
// NOTE: sel focus implies key focus since we only request
// the latter. We must set before calling self.set_primary.
self.has_key_focus = true;
if source == FocusSource::Pointer {
self.set_primary(cx);
}
Used
}
Event::KeyFocus => {
self.has_key_focus = true;
cx.set_scroll(Scroll::Rect(self.rect()));
G::focus_gained(self, cx, data);
Used
}
Event::LostKeyFocus => {
self.has_key_focus = false;
cx.redraw(&self);
G::focus_lost(self, cx, data);
Used
}
Event::LostSelFocus => {
self.selection.set_empty();
cx.redraw(self);
Used
}
Event::Command(cmd, code) => {
if self.has_key_focus {
match self.control_key(cx, data, cmd, code) {
Ok(r) => r,
Err(NotReady) => Used,
}
} else {
Unused
}
}
Event::Key(event, false) if event.state == ElementState::Pressed => {
if let Some(text) = event.text {
self.received_text(cx, data, &text)
} else {
if let Some(cmd) = cx.config().shortcuts(|s| s.try_match(cx.modifiers(), &event.logical_key)) {
match self.control_key(cx, data, cmd, Some(event.physical_key)) {
Ok(r) => r,
Err(NotReady) => Used,
}
} else {
Unused
}
}
}
Event::Scroll(delta) => {
let delta2 = match delta {
ScrollDelta::LineDelta(x, y) => cx.config().scroll_distance((x, y)),
ScrollDelta::PixelDelta(coord) => coord,
};
self.pan_delta(cx, delta2)
}
Event::PressStart { press } if press.is_tertiary() =>
press.grab(self.id())
.with_mode(kas::event::GrabMode::Click)
.with_cx(cx),
Event::PressEnd { press, .. } if press.is_tertiary() => {
if let Some(content) = cx.get_primary() {
self.set_edit_pos_from_coord(cx, press.coord);
self.selection.set_empty();
let pos = self.selection.edit_pos();
let range = self.trim_paste(&content);
let len = range.len();
self.old_state =
Some((self.text.clone_string(), pos, self.selection.sel_pos()));
self.last_edit = LastEdit::Paste;
self.text.replace_range(pos..pos, &content[range]);
self.selection.set_pos(pos + len);
self.edit_x_coord = None;
self.prepare_text(cx);
G::edit(self, cx, data);
}
Used
}
event => match self.input_handler.handle(cx, self.id(), event) {
TextInputAction::None => Used,
TextInputAction::Unused => Unused,
TextInputAction::Pan(delta) => self.pan_delta(cx, delta),
TextInputAction::Focus { coord, action } => {
if let Some(coord) = coord {
self.set_edit_pos_from_coord(cx, coord);
}
self.selection.action(&self.text, action);
if self.has_key_focus {
self.set_primary(cx);
} else {
cx.request_key_focus(self.id(), FocusSource::Pointer);
}
Used
}
},
}
}
}
impl Scrollable for Self {
fn scroll_axes(&self, size: Size) -> (bool, bool) {
let max = self.max_scroll_offset();
(max.0 > size.0, max.1 > size.1)
}
fn max_scroll_offset(&self) -> Offset {
let text_size = Offset::conv(self.text_size);
let self_size = Offset::conv(self.rect().size);
(text_size - self_size).max(Offset::ZERO)
}
fn scroll_offset(&self) -> Offset {
self.view_offset
}
fn set_scroll_offset(&mut self, cx: &mut EventCx, offset: Offset) -> Offset {
let new_offset = offset.min(self.max_scroll_offset()).max(Offset::ZERO);
if new_offset != self.view_offset {
self.view_offset = new_offset;
// No widget moves so do not need to report Action::REGION_MOVED
cx.redraw(self);
}
new_offset
}
}
impl HasStr for Self {
fn get_str(&self) -> &str {
self.text.text()
}
}
impl HasString for Self {
fn set_string(&mut self, string: String) -> Action {
if *self.text.text() == string {
return Action::empty();
}
let mut action = Action::REDRAW;
let len = string.len();
self.text.set_string(string);
self.selection.set_max_len(len);
if self.text.try_prepare().is_ok() {
self.text_size = Vec2::from(self.text.bounding_box().unwrap().1).cast_ceil();
self.view_offset = self.view_offset.min(self.max_scroll_offset());
action = Action::SCROLLED;
}
action | self.set_error_state(false)
}
}
impl ToString for Self {
fn to_string(&self) -> String {
self.text.text().clone()
}
}
}
impl<G: EditGuard> EditField<G> {
/// Construct an `EditBox` with an [`EditGuard`]
#[inline]
pub fn new(guard: G) -> EditField<G> {
EditField {
core: Default::default(),
outer_rect: Rect::ZERO,
frame_style: FrameStyle::None,
view_offset: Default::default(),
editable: true,
class: TextClass::Edit(false),
align: Default::default(),
width: (8.0, 16.0),
lines: (1, 1),
text: Default::default(),
text_size: Default::default(),
selection: Default::default(),
edit_x_coord: None,
old_state: None,
last_edit: Default::default(),
has_key_focus: false,
error_state: false,
input_handler: Default::default(),
guard,
}
}
}
impl<A: 'static> EditField<DefaultGuard<A>> {
/// Construct an `EditField` with the given inital `text` (no event handling)
#[inline]
pub fn text<S: ToString>(text: S) -> Self {
let text = text.to_string();
let len = text.len();
EditField {
editable: true,
class: TextClass::Edit(false),
text: Text::new(text),
selection: SelectionHelper::new(len, len),
..Default::default()
}
}
/// Construct a read-only `EditField` displaying some `String` value
#[inline]
pub fn string(value_fn: impl Fn(&A) -> String + 'static) -> EditField<StringGuard<A>> {
EditField::new(StringGuard::new(value_fn)).with_editable(false)
}
/// Construct an `EditField` for a parsable value (e.g. a number)
///
/// On update, `value_fn` is used to extract a value from input data
/// which is then formatted as a string via [`Display`].
/// If, however, the input field has focus, the update is ignored.
///
/// On every edit, the guard attempts to parse the field's input as type
/// `T` via [`FromStr`], caching the result and setting the error state.
///
/// On field activation and focus loss when a `T` value is cached (see
/// previous paragraph), `on_afl` is used to construct a message to be
/// emitted via [`EventCx::push`]. The cached value is then cleared to
/// avoid sending duplicate messages.
#[inline]
pub fn parser<T: Debug + Display + FromStr, M: Debug + 'static>(
value_fn: impl Fn(&A) -> T + 'static,
msg_fn: impl Fn(T) -> M + 'static,
) -> EditField<ParseGuard<A, T>> {
EditField::new(ParseGuard::new(value_fn, msg_fn))
}
/// Construct an `EditField` for a parsable value (e.g. a number)
///
/// On update, `value_fn` is used to extract a value from input data
/// which is then formatted as a string via [`Display`].
/// If, however, the input field has focus, the update is ignored.
///
/// On every edit, the guard attempts to parse the field's input as type
/// `T` via [`FromStr`]. On success, the result is converted to a
/// message via `on_afl` then emitted via [`EventCx::push`].
pub fn instant_parser<T: Debug + Display + FromStr, M: Debug + 'static>(
value_fn: impl Fn(&A) -> T + 'static,
msg_fn: impl Fn(T) -> M + 'static,
) -> EditField<InstantParseGuard<A, T>> {
EditField::new(InstantParseGuard::new(value_fn, msg_fn))
}
}
impl<A: 'static> EditField<StringGuard<A>> {
/// Assign a message function for a `String` value
///
/// The `msg_fn` is called when the field is activated (<kbd>Enter</kbd>)
/// and when it loses focus after content is changed.
///
/// This method sets self as editable (see [`Self::with_editable`]).
#[must_use]
pub fn with_msg<M>(mut self, msg_fn: impl Fn(&str) -> M + 'static) -> Self
where
M: Debug + 'static,
{
self.guard = self.guard.with_msg(msg_fn);
self.editable = true;
self
}
}
impl<G: EditGuard> EditField<G> {
/// Set outer rect
///
/// Optionally, call this immediately after [`Self::set_rect`] with the
/// "outer" rect and frame style. In this case, a frame will be drawn using
/// this `outer_rect` and `style`. The advantages are:
///
/// - The "error state" background can correctly fill the frame
/// - Clicks on the frame get registered as clicks on self
///
/// Any other widgets painted over the `outer_rect` should be drawn after
/// the `EditField`.
#[inline]
pub fn set_outer_rect(&mut self, outer_rect: Rect, style: FrameStyle) {
self.outer_rect = outer_rect;
self.frame_style = style;
}
/// Set the initial text (inline)
///
/// This method should only be used on a new `EditField`.
#[inline]
#[must_use]
pub fn with_text(mut self, text: impl ToString) -> Self {
let text = text.to_string();
let len = text.len();
self.text.set_string(text);
self.selection.set_pos(len);
self
}
/// Set whether this `EditField` is editable (inline)
#[inline]
#[must_use]
pub fn with_editable(mut self, editable: bool) -> Self {
self.editable = editable;
self
}
/// Get whether this `EditField` is editable
pub fn is_editable(&self) -> bool {
self.editable
}
/// Set whether this `EditField` is editable
pub fn set_editable(&mut self, editable: bool) {
self.editable = editable;
}
/// Set whether this `EditField` uses multi-line mode
///
/// This method does two things:
///
/// - Changes the text class (see [`Self::with_class`])
/// - Changes the vertical height allocation (see [`Self::with_lines`])
#[inline]
#[must_use]
pub fn with_multi_line(mut self, multi_line: bool) -> Self {
self.class = TextClass::Edit(multi_line);
self.lines = match multi_line {
false => (1, 1),
true => (4, 7),
};
self
}
/// True if the editor uses multi-line mode
///
/// See also: [`Self::with_multi_line`]
#[inline]
pub fn multi_line(&self) -> bool {
self.class.multi_line()
}
/// Set the text class used
#[inline]
#[must_use]
pub fn with_class(mut self, class: TextClass) -> Self {
self.class = class;
self
}
/// Get the text class used
#[inline]
pub fn class(&self) -> TextClass {
self.class
}
/// Adjust the height allocation
#[inline]
pub fn set_lines(&mut self, min_lines: i32, ideal_lines: i32) {
self.lines = (min_lines, ideal_lines);
}
/// Adjust the height allocation (inline)
#[inline]
#[must_use]
pub fn with_lines(mut self, min_lines: i32, ideal_lines: i32) -> Self {
self.set_lines(min_lines, ideal_lines);
self
}
/// Adjust the width allocation
#[inline]
pub fn set_width_em(&mut self, min_em: f32, ideal_em: f32) {
self.width = (min_em, ideal_em);
}
/// Adjust the width allocation (inline)
#[inline]
#[must_use]
pub fn with_width_em(mut self, min_em: f32, ideal_em: f32) -> Self {
self.set_width_em(min_em, ideal_em);
self
}
/// Get whether the widget has edit focus
///
/// This is true when the widget is editable and has keyboard focus.
#[inline]
pub fn has_edit_focus(&self) -> bool {
self.editable && self.has_key_focus
}
/// Get whether the input state is erroneous
#[inline]
pub fn has_error(&self) -> bool {
self.error_state
}
/// Set the error state
///
/// When true, the input field's background is drawn red.
/// This state is cleared by [`Self::set_string`].
// TODO: possibly change type to Option<String> and display the error
pub fn set_error_state(&mut self, error_state: bool) -> Action {
self.error_state = error_state;
Action::REDRAW
}
fn prepare_text(&mut self, cx: &mut EventCx) {
if !self.text.env().bounds.1.is_finite() {
// Do not attempt to prepare before bounds are set.
return;
}
if !self.text.required_action().is_ready() {
let start = std::time::Instant::now();
self.text.prepare().expect("invalid font_id");
self.text_size = Vec2::from(self.text.bounding_box().unwrap().1).cast_ceil();
log::trace!(
target: "kas_perf::widgets::edit", "prepare_text: {}μs",
start.elapsed().as_micros(),
);
}
cx.redraw(&self);
self.set_view_offset_from_edit_pos(cx);
}
fn trim_paste(&self, text: &str) -> Range<usize> {
let mut end = text.len();
if !self.multi_line() {
// We cut the content short on control characters and
// ignore them (preventing line-breaks and ignoring any
// actions such as recursive-paste).
for (i, c) in text.char_indices() {
if c < '\u{20}' || ('\u{7f}'..='\u{9f}').contains(&c) {
end = i;
break;
}
}
}
0..end
}
fn received_text(&mut self, cx: &mut EventCx, data: &G::Data, text: &str) -> IsUsed {
if !self.editable {
return Unused;
}
let pos = self.selection.edit_pos();
let selection = self.selection.range();
let have_sel = selection.start < selection.end;
if self.last_edit != LastEdit::Insert || have_sel {
self.old_state = Some((self.text.clone_string(), pos, self.selection.sel_pos()));
self.last_edit = LastEdit::Insert;
}
if have_sel {
self.text.replace_range(selection.clone(), text);
self.selection.set_pos(selection.start + text.len());
} else {
// TODO(kas-text) support the following:
// self.text.insert_str(pos, text);
let mut s = self.text.clone_string();
s.insert_str(pos, text);
self.text.set_text(s);
// END workaround
self.selection.set_pos(pos + text.len());
}
self.edit_x_coord = None;
self.prepare_text(cx);
G::edit(self, cx, data);
Used
}
fn control_key(
&mut self,
cx: &mut EventCx,
data: &G::Data,
cmd: Command,
code: Option<PhysicalKey>,
) -> Result<IsUsed, NotReady> {
let editable = self.editable;
let mut shift = cx.modifiers().shift_key();
let mut buf = [0u8; 4];
let pos = self.selection.edit_pos();
let len = self.text.str_len();
let multi_line = self.multi_line();
let selection = self.selection.range();
let have_sel = selection.end > selection.start;
let string;
enum Action<'a> {
None,
Unused,
Activate,
Edit,
Insert(&'a str, LastEdit),
Delete(Range<usize>),
Move(usize, Option<f32>),
}
let action = match cmd {
Command::Escape | Command::Deselect if !selection.is_empty() => {
self.selection.set_empty();
cx.redraw(&self);
Action::None
}
Command::Activate => Action::Activate,
Command::Enter if shift || !multi_line => Action::Activate,
Command::Enter if editable && multi_line => {
Action::Insert('\n'.encode_utf8(&mut buf), LastEdit::Insert)
}
// NOTE: we might choose to optionally handle Tab in the future,
// but without some workaround it prevents keyboard navigation.
// Command::Tab => Action::Insert('\t'.encode_utf8(&mut buf), LastEdit::Insert),
Command::Left | Command::Home if !shift && have_sel => {
Action::Move(selection.start, None)
}
Command::Left if pos > 0 => {
let mut cursor = GraphemeCursor::new(pos, len, true);
cursor
.prev_boundary(self.text.text(), 0)
.unwrap()
.map(|pos| Action::Move(pos, None))
.unwrap_or(Action::None)
}
Command::Right | Command::End if !shift && have_sel => {
Action::Move(selection.end, None)
}
Command::Right if pos < len => {
let mut cursor = GraphemeCursor::new(pos, len, true);
cursor
.next_boundary(self.text.text(), 0)
.unwrap()
.map(|pos| Action::Move(pos, None))
.unwrap_or(Action::None)
}
Command::WordLeft if pos > 0 => {
let mut iter = self.text.text()[0..pos].split_word_bound_indices();
let mut p = iter.next_back().map(|(index, _)| index).unwrap_or(0);
while self.text.text()[p..]
.chars()
.next()
.map(|c| c.is_whitespace())
.unwrap_or(false)
{
if let Some((index, _)) = iter.next_back() {
p = index;
} else {
break;
}
}
Action::Move(p, None)
}
Command::WordRight if pos < len => {
let mut iter = self.text.text()[pos..].split_word_bound_indices().skip(1);
let mut p = iter.next().map(|(index, _)| pos + index).unwrap_or(len);
while self.text.text()[p..]
.chars()
.next()
.map(|c| c.is_whitespace())
.unwrap_or(false)
{
if let Some((index, _)) = iter.next() {
p = pos + index;
} else {
break;
}
}
Action::Move(p, None)
}
Command::Up | Command::Down if multi_line => {
let x = match self.edit_x_coord {
Some(x) => x,
None => self
.text
.text_glyph_pos(pos)?
.next_back()
.map(|r| r.pos.0)
.unwrap_or(0.0),
};
let mut line = self.text.find_line(pos)?.map(|r| r.0).unwrap_or(0);
// We can tolerate invalid line numbers here!
line = match cmd {
Command::Up => line.wrapping_sub(1),
Command::Down => line.wrapping_add(1),
_ => unreachable!(),
};
const HALF: usize = usize::MAX / 2;
let nearest_end = match line {
0..=HALF => len,
_ => 0,
};
self.text
.line_index_nearest(line, x)?
.map(|pos| Action::Move(pos, Some(x)))
.unwrap_or(Action::Move(nearest_end, None))
}
Command::Home if pos > 0 => {
let pos = self.text.find_line(pos)?.map(|r| r.1.start).unwrap_or(0);
Action::Move(pos, None)
}
Command::End if pos < len => {
let pos = self.text.find_line(pos)?.map(|r| r.1.end).unwrap_or(len);
Action::Move(pos, None)
}
Command::DocHome if pos > 0 => Action::Move(0, None),
Command::DocEnd if pos < len => Action::Move(len, None),
Command::PageUp | Command::PageDown if multi_line => {
let mut v = self
.text
.text_glyph_pos(pos)?
.next_back()
.map(|r| r.pos.into())
.unwrap_or(Vec2::ZERO);
if let Some(x) = self.edit_x_coord {
v.0 = x;
}
const FACTOR: f32 = 2.0 / 3.0;
let mut h_dist = self.text.env().bounds.1 * FACTOR;
if cmd == Command::PageUp {
h_dist *= -1.0;
}
v.1 += h_dist;
Action::Move(self.text.text_index_nearest(v.into())?, Some(v.0))
}
Command::Delete | Command::DelBack if editable && have_sel => {
Action::Delete(selection.clone())
}
Command::Delete if editable => {
let mut cursor = GraphemeCursor::new(pos, len, true);
cursor
.next_boundary(self.text.text(), 0)
.unwrap()
.map(|next| Action::Delete(pos..next))
.unwrap_or(Action::None)
}
Command::DelBack if editable => {
// We always delete one code-point, not one grapheme cluster:
let prev = self.text.text()[0..pos]
.char_indices()
.next_back()
.map(|(i, _)| i)
.unwrap_or(0);
Action::Delete(prev..pos)
}
Command::DelWord if editable => {
let next = self.text.text()[pos..]
.split_word_bound_indices()
.nth(1)
.map(|(index, _)| pos + index)
.unwrap_or(len);
Action::Delete(pos..next)
}
Command::DelWordBack if editable => {
let prev = self.text.text()[0..pos]
.split_word_bound_indices()
.next_back()
.map(|(index, _)| index)
.unwrap_or(0);
Action::Delete(prev..pos)
}
Command::SelectAll => {
self.selection.set_sel_pos(0);
shift = true; // hack
Action::Move(len, None)
}
Command::Cut if editable && have_sel => {
cx.set_clipboard((self.text.text()[selection.clone()]).into());
Action::Delete(selection.clone())
}
Command::Copy if have_sel => {
cx.set_clipboard((self.text.text()[selection.clone()]).into());
Action::None
}
Command::Paste if editable => {
if let Some(content) = cx.get_clipboard() {
let range = self.trim_paste(&content);
string = content;
Action::Insert(&string[range], LastEdit::Paste)
} else {
Action::None
}
}
Command::Undo | Command::Redo if editable => {
// TODO: maintain full edit history (externally?)
if let Some((state, pos2, sel_pos)) = self.old_state.as_mut() {
self.text.swap_string(state);
self.selection.set_edit_pos(*pos2);
*pos2 = pos;
let pos = *sel_pos;
*sel_pos = self.selection.sel_pos();
self.selection.set_sel_pos(pos);
self.edit_x_coord = None;
self.last_edit = LastEdit::None;
}
Action::Edit
}
_ => Action::Unused,
};
let result = match action {
Action::None => EditAction::None,
Action::Unused => EditAction::Unused,
Action::Activate => EditAction::Activate,
Action::Edit => EditAction::Edit,
Action::Insert(s, edit) => {
let mut pos = pos;
if have_sel {
self.old_state =
Some((self.text.clone_string(), pos, self.selection.sel_pos()));
self.last_edit = edit;
self.text.replace_range(selection.clone(), s);
pos = selection.start;
} else {
if self.last_edit != edit {
self.old_state =
Some((self.text.clone_string(), pos, self.selection.sel_pos()));
self.last_edit = edit;
}
self.text.replace_range(pos..pos, s);
}
self.selection.set_pos(pos + s.len());
self.edit_x_coord = None;
EditAction::Edit
}
Action::Delete(sel) => {
if self.last_edit != LastEdit::Delete {
self.old_state =
Some((self.text.clone_string(), pos, self.selection.sel_pos()));
self.last_edit = LastEdit::Delete;
}
self.text.replace_range(sel.clone(), "");
self.selection.set_pos(sel.start);
self.edit_x_coord = None;
EditAction::Edit
}
Action::Move(pos, x_coord) => {
self.selection.set_edit_pos(pos);
if !shift {
self.selection.set_empty();
} else {
self.set_primary(cx);
}
self.edit_x_coord = x_coord;
cx.redraw(&self);
EditAction::None
}
};
self.prepare_text(cx);
Ok(match result {
EditAction::None => Used,
EditAction::Unused => Unused,
EditAction::Activate => {
if let Some(code) = code {
cx.depress_with_key(self.id(), code);
}
G::activate(self, cx, data)
}
EditAction::Edit => {
G::edit(self, cx, data);
Used
}
})
}
fn set_edit_pos_from_coord(&mut self, cx: &mut EventCx, coord: Coord) {
let rel_pos = (coord - self.rect().pos + self.view_offset).cast();
if let Ok(pos) = self.text.text_index_nearest(rel_pos) {
if pos != self.selection.edit_pos() {
self.selection.set_edit_pos(pos);
self.set_view_offset_from_edit_pos(cx);
self.edit_x_coord = None;
cx.redraw(self);
}
}
}
fn set_primary(&self, cx: &mut EventCx) {
if self.has_key_focus && !self.selection.is_empty() && cx.has_primary() {
let range = self.selection.range();
cx.set_primary(String::from(&self.text.as_str()[range]));
}
}
// Pan by given delta.
fn pan_delta(&mut self, cx: &mut EventCx, mut delta: Offset) -> IsUsed {
let new_offset = (self.view_offset - delta)
.min(self.max_scroll_offset())
.max(Offset::ZERO);
if new_offset != self.view_offset {
delta -= self.view_offset - new_offset;
self.view_offset = new_offset;
cx.redraw(self);
}
cx.set_scroll(if delta == Offset::ZERO {
Scroll::Scrolled
} else {
Scroll::Offset(delta)
});
Used
}
/// Update view_offset after edit_pos changes
///
/// A redraw is assumed since edit_pos moved.
fn set_view_offset_from_edit_pos(&mut self, cx: &mut EventCx) {
let edit_pos = self.selection.edit_pos();
if let Some(marker) = self
.text
.text_glyph_pos(edit_pos)
.ok()
.and_then(|mut m| m.next_back())
{
let bounds = Vec2::from(self.text.env().bounds);
let min_x = marker.pos.0 - bounds.0;
let min_y = marker.pos.1 - marker.descent - bounds.1;
let max_x = marker.pos.0;
let max_y = marker.pos.1 - marker.ascent;
let min = Offset(min_x.cast_ceil(), min_y.cast_ceil());
let max = Offset(max_x.cast_floor(), max_y.cast_floor());
let max = max.min(self.max_scroll_offset());
let new_offset = self.view_offset.max(min).min(max);
if new_offset != self.view_offset {
self.view_offset = new_offset;
cx.set_scroll(Scroll::Scrolled);
}
}
}
}