1use std::fmt::{self, Debug};
4use std::rc::Rc;
5
6use waft_embedder::{Color, TargetPlatform, TextDecoration, TextRange};
7use waft_foundation::App;
8use waft_painting::{InlineSpanRef, TextSpan, TextStyle};
9use waft_services::{SpellCheckResults, SpellCheckService, SuggestionSpan, TextEditingValue};
10
11use crate::widgets::editable_text::EditableTextContextMenuBuilder;
12
13#[derive(Clone)]
19pub struct SpellCheckConfiguration {
20 pub spell_check_service: Option<Rc<dyn SpellCheckService>>,
22 pub misspelled_selection_color: Option<Color>,
28 pub misspelled_text_style: Option<TextStyle>,
35 pub spell_check_suggestions_toolbar_builder: Option<EditableTextContextMenuBuilder>,
38 spell_check_enabled: bool,
39}
40
41impl SpellCheckConfiguration {
42 pub const fn new() -> SpellCheckConfiguration {
45 SpellCheckConfiguration {
46 spell_check_service: None,
47 misspelled_selection_color: None,
48 misspelled_text_style: None,
49 spell_check_suggestions_toolbar_builder: None,
50 spell_check_enabled: true,
51 }
52 }
53
54 pub const fn disabled() -> SpellCheckConfiguration {
56 SpellCheckConfiguration {
57 spell_check_enabled: false,
58 spell_check_service: None,
59 spell_check_suggestions_toolbar_builder: None,
60 misspelled_text_style: None,
61 misspelled_selection_color: None,
62 }
63 }
64
65 pub fn spell_check_service(
67 mut self,
68 spell_check_service: Rc<dyn SpellCheckService>,
69 ) -> SpellCheckConfiguration {
70 self.spell_check_service = Some(spell_check_service);
71 self
72 }
73
74 pub fn misspelled_selection_color(
76 mut self,
77 misspelled_selection_color: Color,
78 ) -> SpellCheckConfiguration {
79 self.misspelled_selection_color = Some(misspelled_selection_color);
80 self
81 }
82
83 pub fn misspelled_text_style(
85 mut self,
86 misspelled_text_style: TextStyle,
87 ) -> SpellCheckConfiguration {
88 self.misspelled_text_style = Some(misspelled_text_style);
89 self
90 }
91
92 pub fn spell_check_suggestions_toolbar_builder(
94 mut self,
95 spell_check_suggestions_toolbar_builder: EditableTextContextMenuBuilder,
96 ) -> SpellCheckConfiguration {
97 self.spell_check_suggestions_toolbar_builder =
98 Some(spell_check_suggestions_toolbar_builder);
99 self
100 }
101
102 pub fn spell_check_enabled(&self) -> bool {
104 self.spell_check_enabled
105 }
106
107 pub fn copy_with(&self) -> SpellCheckConfiguration {
113 if !self.spell_check_enabled {
114 return SpellCheckConfiguration::disabled();
115 }
116 self.clone()
117 }
118}
119
120impl Default for SpellCheckConfiguration {
121 fn default() -> SpellCheckConfiguration {
122 SpellCheckConfiguration::new()
123 }
124}
125
126impl Debug for SpellCheckConfiguration {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 write!(
129 f,
130 "SpellCheckConfiguration({}, service: {}, text style: {:?}, toolbar builder: {})",
131 if self.spell_check_enabled {
132 "enabled"
133 } else {
134 "disabled"
135 },
136 if self.spell_check_service.is_some() {
137 "Some"
138 } else {
139 "None"
140 },
141 self.misspelled_text_style,
142 if self.spell_check_suggestions_toolbar_builder.is_some() {
143 "Some"
144 } else {
145 "None"
146 },
147 )
148 }
149}
150
151impl PartialEq for SpellCheckConfiguration {
152 fn eq(&self, other: &SpellCheckConfiguration) -> bool {
153 option_rc_ptr_eq(&self.spell_check_service, &other.spell_check_service)
154 && self.misspelled_text_style == other.misspelled_text_style
155 && option_rc_ptr_eq(
156 &self.spell_check_suggestions_toolbar_builder,
157 &other.spell_check_suggestions_toolbar_builder,
158 )
159 && self.spell_check_enabled == other.spell_check_enabled
160 }
161}
162
163fn option_rc_ptr_eq<T: ?Sized>(left: &Option<Rc<T>>, right: &Option<Rc<T>>) -> bool {
164 match (left, right) {
165 (None, None) => true,
166 (Some(left), Some(right)) => Rc::ptr_eq(left, right),
167 _ => false,
168 }
169}
170
171fn correct_spell_check_results(
180 new_text: &str,
181 results_text: &str,
182 results: &[SuggestionSpan],
183) -> Vec<SuggestionSpan> {
184 let mut corrected_spell_check_results = Vec::new();
185 let mut span_pointer = 0;
186 let mut offset = 0;
187
188 let mut search_start = 0;
191
192 while span_pointer < results.len() {
193 let current_span = &results[span_pointer];
194 let current_span_text = utf16_substring(
195 results_text,
196 current_span.range.start,
197 current_span.range.end,
198 );
199 let span_length = current_span.range.end - current_span.range.start;
200
201 let found_index =
203 index_of_word_bounded(utf16_suffix(new_text, search_start), current_span_text);
204
205 let current_span_found_exactly = current_span.range.start == found_index + search_start;
207 let current_span_found_exactly_with_offset =
208 current_span.range.start + offset == found_index + search_start;
209 let current_span_found_elsewhere = found_index >= 0;
210
211 if current_span_found_exactly || current_span_found_exactly_with_offset {
212 let adjusted_span = SuggestionSpan::new(
217 TextRange::new(
218 current_span.range.start + offset,
219 current_span.range.end + offset,
220 ),
221 current_span.suggestions.clone(),
222 );
223
224 search_start = (current_span.range.end + 1 + offset).min(utf16_len(new_text));
226 corrected_spell_check_results.push(adjusted_span);
227 } else if current_span_found_elsewhere {
228 let adjusted_span_start = search_start + found_index;
230 let adjusted_span_end = adjusted_span_start + span_length;
231 let adjusted_span = SuggestionSpan::new(
232 TextRange::new(adjusted_span_start, adjusted_span_end),
233 current_span.suggestions.clone(),
234 );
235
236 search_start = (adjusted_span_end + 1).min(utf16_len(new_text));
239 offset = adjusted_span_start - current_span.range.start;
242 corrected_spell_check_results.push(adjusted_span);
243 }
244 span_pointer += 1;
245 }
246 corrected_spell_check_results
247}
248
249pub fn build_text_span_with_spell_check_suggestions(
260 app: &App,
261 value: &TextEditingValue,
262 composing_within_current_text_range: bool,
263 style: Option<&TextStyle>,
264 misspelled_text_style: &TextStyle,
265 spell_check_results: &SpellCheckResults,
266) -> TextSpan {
267 let mut spell_check_results_spans = spell_check_results.suggestion_spans.clone();
268 let spell_check_results_text = &spell_check_results.spell_checked_text;
269
270 if spell_check_results_text != &value.text {
271 spell_check_results_spans = correct_spell_check_results(
272 &value.text,
273 spell_check_results_text,
274 &spell_check_results_spans,
275 );
276 }
277
278 let should_consider_composing_region =
284 app.platform().target_platform() == TargetPlatform::Android;
285 if should_consider_composing_region {
286 return text_span_children(
287 style,
288 build_subtrees_with_composing_region(
289 &spell_check_results_spans,
290 value,
291 style,
292 misspelled_text_style,
293 composing_within_current_text_range,
294 ),
295 );
296 }
297
298 text_span_children(
299 style,
300 build_subtrees_without_composing_region(
301 &spell_check_results_spans,
302 value,
303 style,
304 misspelled_text_style,
305 value.selection.base_offset,
306 ),
307 )
308}
309
310fn build_subtrees_without_composing_region(
315 spell_check_suggestions: &[SuggestionSpan],
316 value: &TextEditingValue,
317 style: Option<&TextStyle>,
318 misspelled_style: &TextStyle,
319 cursor_index: i32,
320) -> Vec<TextSpan> {
321 let mut text_span_tree_children = Vec::new();
322
323 let mut text_pointer = 0;
324 let mut current_span_pointer = 0;
325 let text = &value.text;
326 let text_len = utf16_len(text);
327 let misspelled_joint_style = style
328 .map(|style| style.merge(Some(misspelled_style)))
329 .unwrap_or_else(|| misspelled_style.clone());
330
331 while text_pointer < text_len && current_span_pointer < spell_check_suggestions.len() {
333 let current_span = &spell_check_suggestions[current_span_pointer];
334
335 if current_span.range.start > text_pointer {
336 let end_index = if current_span.range.start < text_len {
337 current_span.range.start
338 } else {
339 text_len
340 };
341 text_span_tree_children.push(span_text(
342 style,
343 utf16_substring(text, text_pointer, end_index),
344 ));
345 text_pointer = end_index;
346 } else {
347 let end_index = if current_span.range.end < text_len {
348 current_span.range.end
349 } else {
350 text_len
351 };
352 let cursor_in_current_span =
353 current_span.range.start <= cursor_index && current_span.range.end >= cursor_index;
354 text_span_tree_children.push(span_text(
355 if cursor_in_current_span {
356 style
357 } else {
358 Some(&misspelled_joint_style)
359 },
360 utf16_substring(text, current_span.range.start, end_index),
361 ));
362
363 text_pointer = end_index;
364 current_span_pointer += 1;
365 }
366 }
367
368 if text_pointer < text_len {
370 text_span_tree_children.push(span_text(
371 style,
372 utf16_substring(text, text_pointer, text_len),
373 ));
374 }
375
376 text_span_tree_children
377}
378
379fn build_subtrees_with_composing_region(
382 spell_check_suggestions: &[SuggestionSpan],
383 value: &TextEditingValue,
384 style: Option<&TextStyle>,
385 misspelled_style: &TextStyle,
386 composing_within_current_text_range: bool,
387) -> Vec<TextSpan> {
388 let mut text_span_tree_children = Vec::new();
389
390 let mut text_pointer = 0;
391 let mut current_span_pointer = 0;
392 let text = &value.text;
393 let text_len = utf16_len(text);
394 let composing_region = value.composing;
395 let underline = TextStyle::new().decoration(TextDecoration::UNDERLINE);
396 let composing_text_style = style
397 .map(|style| style.merge(Some(&underline)))
398 .unwrap_or(underline);
399 let misspelled_joint_style = style
400 .map(|style| style.merge(Some(misspelled_style)))
401 .unwrap_or_else(|| misspelled_style.clone());
402
403 while text_pointer < text_len && current_span_pointer < spell_check_suggestions.len() {
405 let current_span = &spell_check_suggestions[current_span_pointer];
406
407 if current_span.range.start > text_pointer {
408 let end_index = if current_span.range.start < text_len {
409 current_span.range.start
410 } else {
411 text_len
412 };
413 let text_pointer_within_composing_region = composing_region.start >= text_pointer
414 && composing_region.end <= end_index
415 && !composing_within_current_text_range;
416
417 if text_pointer_within_composing_region {
418 add_composing_region_text_spans(
419 &mut text_span_tree_children,
420 text,
421 text_pointer,
422 composing_region,
423 style,
424 &composing_text_style,
425 );
426 text_span_tree_children.push(span_text(
427 style,
428 utf16_substring(text, composing_region.end, end_index),
429 ));
430 } else {
431 text_span_tree_children.push(span_text(
432 style,
433 utf16_substring(text, text_pointer, end_index),
434 ));
435 }
436
437 text_pointer = end_index;
438 } else {
439 let end_index = if current_span.range.end < text_len {
440 current_span.range.end
441 } else {
442 text_len
443 };
444 let current_span_is_composing_region = text_pointer >= composing_region.start
445 && end_index <= composing_region.end
446 && !composing_within_current_text_range;
447 text_span_tree_children.push(span_text(
448 if current_span_is_composing_region {
449 Some(&composing_text_style)
450 } else {
451 Some(&misspelled_joint_style)
452 },
453 utf16_substring(text, current_span.range.start, end_index),
454 ));
455
456 text_pointer = end_index;
457 current_span_pointer += 1;
458 }
459 }
460
461 if text_pointer < text_len {
463 if text_pointer < composing_region.start && !composing_within_current_text_range {
464 add_composing_region_text_spans(
465 &mut text_span_tree_children,
466 text,
467 text_pointer,
468 composing_region,
469 style,
470 &composing_text_style,
471 );
472
473 if composing_region.end != text_len {
474 text_span_tree_children.push(span_text(
475 style,
476 utf16_substring(text, composing_region.end, text_len),
477 ));
478 }
479 } else {
480 text_span_tree_children.push(span_text(
481 style,
482 utf16_substring(text, text_pointer, text_len),
483 ));
484 }
485 }
486
487 text_span_tree_children
488}
489
490fn add_composing_region_text_spans(
493 tree_children: &mut Vec<TextSpan>,
494 text: &str,
495 start: i32,
496 composing_region: TextRange,
497 style: Option<&TextStyle>,
498 composing_text_style: &TextStyle,
499) {
500 tree_children.push(span_text(
501 style,
502 utf16_substring(text, start, composing_region.start),
503 ));
504 tree_children.push(span_text(
505 Some(composing_text_style),
506 utf16_substring(text, composing_region.start, composing_region.end),
507 ));
508}
509
510fn span_text(style: Option<&TextStyle>, text: impl Into<String>) -> TextSpan {
511 let span = TextSpan::new().text(text);
512 match style {
513 Some(style) => span.style(style.clone()),
514 None => span,
515 }
516}
517
518fn text_span_children(style: Option<&TextStyle>, children: Vec<TextSpan>) -> TextSpan {
519 let children: Vec<InlineSpanRef> = children.into_iter().map(TextSpan::into_span).collect();
520 let span = TextSpan::new().children(children);
521 match style {
522 Some(style) => span.style(style.clone()),
523 None => span,
524 }
525}
526
527fn utf16_len(text: &str) -> i32 {
528 text.encode_utf16().count() as i32
529}
530
531fn utf16_substring(text: &str, start: i32, end: i32) -> &str {
532 TextRange::new(start, end).text_inside(text)
533}
534
535fn utf16_suffix(text: &str, start: i32) -> &str {
536 TextRange::collapsed(start).text_after(text)
537}
538
539fn index_of_word_bounded(haystack: &str, needle: &str) -> i32 {
545 let mut utf16 = 0i32;
546 let mut byte = 0usize;
547 loop {
548 let end_byte = byte + needle.len();
549 let ends_on_boundary = needle.is_empty()
550 || (end_byte <= haystack.len() && haystack.is_char_boundary(end_byte));
551 if haystack.is_char_boundary(byte)
552 && ends_on_boundary
553 && haystack[byte..].starts_with(needle)
554 && is_word_boundary(haystack, byte)
555 && is_word_boundary(haystack, end_byte)
556 {
557 return utf16;
558 }
559 if byte >= haystack.len() {
560 return -1;
561 }
562 let Some(ch) = haystack[byte..].chars().next() else {
563 return -1;
564 };
565 byte += ch.len_utf8();
566 utf16 += ch.len_utf16() as i32;
567 }
568}
569
570fn is_word_boundary(text: &str, byte_pos: usize) -> bool {
571 let left_word = byte_pos > 0
572 && text[..byte_pos]
573 .chars()
574 .next_back()
575 .is_some_and(is_ascii_word_char);
576 let right_word = byte_pos < text.len()
577 && text[byte_pos..]
578 .chars()
579 .next()
580 .is_some_and(is_ascii_word_char);
581 left_word != right_word
582}
583
584fn is_ascii_word_char(c: char) -> bool {
585 matches!(c, 'A'..='Z' | 'a'..='z' | '0'..='9' | '_')
586}
587
588#[cfg(test)]
589mod tests {
590 use waft_foundation::AppCell;
591 use waft_painting::InlineSpan;
592
593 use super::*;
594
595 fn misspelled_style() -> TextStyle {
596 TextStyle::new().decoration(TextDecoration::UNDERLINE)
597 }
598
599 #[test]
600 fn empty_spans_yield_a_single_child_with_the_value_text() {
601 let cell = AppCell::new();
602 let app = cell.borrow_mut();
603 let text = "Hello, wrold! Hey";
604 let value = TextEditingValue::new().text(text);
605 let spell_check_results = SpellCheckResults::new(text, Vec::new());
606 let misspelled = misspelled_style();
607
608 let actual = build_text_span_with_spell_check_suggestions(
609 &app,
610 &value,
611 true,
612 None,
613 &misspelled,
614 &spell_check_results,
615 );
616 let expected = TextSpan::new().children(vec![TextSpan::new().text(text).into_span()]);
617 assert!(actual.eq_span(&expected));
618 }
619
620 #[test]
621 fn a_span_in_the_middle_gets_the_misspelled_style() {
622 let cell = AppCell::new();
623 let app = cell.borrow_mut();
624 let text = "Hello, wrold! Hey";
625 let value = TextEditingValue::new().text(text);
626 let misspelled = misspelled_style();
627 let spell_check_results = SpellCheckResults::new(
628 text,
629 vec![SuggestionSpan::new(
630 TextRange::new(7, 12),
631 vec!["world".into(), "word".into(), "old".into()],
632 )],
633 );
634
635 let actual = build_text_span_with_spell_check_suggestions(
636 &app,
637 &value,
638 true,
639 None,
640 &misspelled,
641 &spell_check_results,
642 );
643 let expected = TextSpan::new().children(vec![
644 TextSpan::new().text("Hello, ").into_span(),
645 TextSpan::new()
646 .style(misspelled.clone())
647 .text("wrold")
648 .into_span(),
649 TextSpan::new().text("! Hey").into_span(),
650 ]);
651 assert!(actual.eq_span(&expected));
652 }
653}