1use arrayvec::ArrayVec;
14use icu_segmenter::WordSegmenter;
15use malloc_size_of_derive::MallocSizeOf;
16use servo_base::text::Utf32CodeUnits;
17use style::computed_values::_webkit_text_security::T as WebKitTextSecurity;
18use style::computed_values::white_space_collapse::T as WhiteSpaceCollapse;
19use style::properties::ComputedValues;
20use style::values::specified::text::{TextTransform, TextTransformCase};
21
22use crate::flow::inline::construct::InlineFormattingContextBuilder;
23
24const MAX_CASE_MAPPING_LENGTH: usize = 3;
30
31#[derive(Clone)]
38pub struct CharacterTransformIteration {
39 consumed: Utf32CodeUnits,
41 characters: ArrayVec<char, MAX_CASE_MAPPING_LENGTH>,
43}
44
45impl CharacterTransformIteration {
46 fn case_mapped(iterator: impl ExactSizeIterator<Item = char>) -> Self {
47 debug_assert!(iterator.len() <= MAX_CASE_MAPPING_LENGTH);
48 Self {
49 consumed: Utf32CodeUnits(1),
50 characters: iterator.collect(),
51 }
52 }
53
54 fn one_to_one(character: char) -> Self {
55 Self {
56 consumed: Utf32CodeUnits(1),
57 characters: std::iter::once(character).collect(),
58 }
59 }
60
61 fn collapse(amount_collapsed: usize, character: Option<char>) -> Self {
62 Self {
63 consumed: Utf32CodeUnits(amount_collapsed),
64 characters: character.into_iter().collect(),
65 }
66 }
67
68 fn is_one_to_one(&self) -> bool {
69 self.characters.len() == 1 && self.consumed.0 == 1
70 }
71
72 pub fn characters(&self) -> &[char] {
73 &self.characters
74 }
75}
76
77pub struct WhitespaceCollapse<InputIterator> {
78 input_iterator: InputIterator,
79 white_space_collapse: WhiteSpaceCollapse,
80
81 trimming_leading_white_space: bool,
86
87 following_newline: bool,
90
91 character_pending_to_return: Option<char>,
95}
96
97impl<InputIterator: Iterator<Item = char>> WhitespaceCollapse<InputIterator> {
98 pub fn new(
99 input_iterator: InputIterator,
100 white_space_collapse: WhiteSpaceCollapse,
101 should_trim_leading_white_space: bool,
102 ) -> Self {
103 Self {
104 input_iterator,
105 white_space_collapse,
106 following_newline: false,
107 trimming_leading_white_space: should_trim_leading_white_space,
108 character_pending_to_return: None,
109 }
110 }
111
112 fn iteration_for_collapsed_whitespace(
116 &self,
117 collapsed_whitespace: usize,
118 ) -> CharacterTransformIteration {
119 if !self.following_newline && !self.trimming_leading_white_space {
120 CharacterTransformIteration::collapse(collapsed_whitespace, Some(' '))
121 } else {
122 CharacterTransformIteration::collapse(collapsed_whitespace, None)
123 }
124 }
125
126 fn iteration_for_collected_white_space(
127 &self,
128 collected_whitespace: usize,
129 ) -> Option<CharacterTransformIteration> {
130 (collected_whitespace != 0)
131 .then(|| self.iteration_for_collapsed_whitespace(collected_whitespace))
132 }
133}
134
135impl<InputIterator: Iterator<Item = char>> Iterator for WhitespaceCollapse<InputIterator> {
136 type Item = CharacterTransformIteration;
137
138 fn next(&mut self) -> Option<Self::Item> {
139 if self.white_space_collapse == WhiteSpaceCollapse::Preserve ||
145 self.white_space_collapse == WhiteSpaceCollapse::BreakSpaces
146 {
147 return match self.input_iterator.next() {
152 Some('\r') => Some(CharacterTransformIteration::one_to_one(' ')),
153 next => next.map(CharacterTransformIteration::one_to_one),
154 };
155 }
156
157 if let Some(character) = self.character_pending_to_return.take() {
158 self.trimming_leading_white_space = false;
160 self.following_newline = false;
161 return Some(CharacterTransformIteration::one_to_one(character));
162 }
163
164 let mut collected_whitespace = 0;
169
170 while let Some(character) = self.input_iterator.next() {
171 if InlineFormattingContextBuilder::is_document_white_space(character) &&
175 character != '\n'
176 {
177 collected_whitespace += 1;
178 continue;
179 }
180
181 if character == '\n' {
185 let iteration = if self.white_space_collapse != WhiteSpaceCollapse::Collapse {
196 CharacterTransformIteration::collapse(collected_whitespace + 1, Some('\n'))
197 } else {
198 self.iteration_for_collapsed_whitespace(collected_whitespace + 1)
199 };
200
201 self.following_newline = true;
202 return Some(iteration);
203 }
204
205 if let Some(iteration) = self.iteration_for_collected_white_space(collected_whitespace)
216 {
217 self.character_pending_to_return = Some(character);
218 return Some(iteration);
219 }
220
221 self.trimming_leading_white_space = false;
223 self.following_newline = false;
224 return Some(CharacterTransformIteration::one_to_one(character));
225 }
226
227 self.iteration_for_collected_white_space(collected_whitespace)
228 }
229}
230
231pub(crate) struct TextTransformationIterator<'a>(
232 Box<dyn Iterator<Item = CharacterTransformIteration> + 'a>,
233);
234
235impl<'a> TextTransformationIterator<'a> {
236 pub(crate) fn new(
237 text: &'a str,
238 style: &ComputedValues,
239 trim_leading_white_space: bool,
240 on_word_boundary: bool,
241 ) -> Self {
242 let text_security = style.clone__webkit_text_security();
243 let chars = text
244 .chars()
245 .map(move |character| map_character_for_webkit_text_security(text_security, character));
246 let white_space_collapse = style.clone_white_space_collapse();
247 let iterator =
248 WhitespaceCollapse::new(chars, white_space_collapse, trim_leading_white_space);
249
250 let text_transform = style.clone_text_transform();
253 let iterator = match text_transform.case() {
254 TextTransformCase::None => {
255 Box::new(iterator) as Box<dyn Iterator<Item = CharacterTransformIteration>>
256 },
257 TextTransformCase::Lowercase => {
258 Box::new(simple_case_transform_iterator(iterator, |character| {
259 CharacterTransformIteration::case_mapped(character.to_lowercase())
260 }))
261 },
262 TextTransformCase::Uppercase => {
263 Box::new(simple_case_transform_iterator(iterator, |character| {
264 CharacterTransformIteration::case_mapped(character.to_uppercase())
265 }))
266 },
267 TextTransformCase::Capitalize => Box::new(capitalization_iterator(
268 iterator,
269 text.len(),
270 on_word_boundary,
271 )),
272 };
274 if text_transform.intersects(TextTransform::FULL_WIDTH) {
275 }
277 if text_transform.intersects(TextTransform::FULL_SIZE_KANA) {
278 }
280
281 Self(iterator)
282 }
283}
284
285impl Iterator for TextTransformationIterator<'_> {
286 type Item = CharacterTransformIteration;
287 fn next(&mut self) -> Option<Self::Item> {
288 self.0.next()
289 }
290}
291
292fn simple_case_transform_iterator(
293 input_iterator: impl Iterator<Item = CharacterTransformIteration>,
294 mapping: impl Fn(char) -> CharacterTransformIteration,
295) -> impl Iterator<Item = CharacterTransformIteration> {
296 input_iterator.map(move |iteration| {
297 if iteration.is_one_to_one() {
298 mapping(iteration.characters[0])
299 } else {
300 iteration
301 }
302 })
303}
304
305pub(crate) fn capitalization_iterator(
310 input_iterator: impl Iterator<Item = CharacterTransformIteration>,
311 size_hint: usize,
312 allow_word_at_start: bool,
313) -> impl Iterator<Item = CharacterTransformIteration> {
314 let mut iterations: Vec<_> = input_iterator.collect();
315 let mut string = String::with_capacity(size_hint);
316 for iteration in &iterations {
317 string.extend(iteration.characters());
318 }
319
320 let word_segmenter = WordSegmenter::new_auto();
321 let mut bounds = word_segmenter.segment_str(&string).peekable();
322
323 let mut current_byte_index = 0;
324 for iteration in iterations.iter_mut() {
325 let bytes_to_advance: usize = iteration
326 .characters()
327 .iter()
328 .map(|character| character.len_utf8())
329 .sum();
330 if bytes_to_advance == 0 {
331 continue;
332 }
333
334 let at_word_start = bounds.peek() == Some(¤t_byte_index);
335 if at_word_start {
336 bounds.next();
337 }
338
339 if iteration.is_one_to_one() &&
344 at_word_start &&
345 (current_byte_index != 0 || allow_word_at_start)
346 {
347 *iteration =
351 CharacterTransformIteration::case_mapped(iteration.characters[0].to_uppercase());
352 }
353
354 current_byte_index += bytes_to_advance;
355 }
356
357 iterations.into_iter()
358}
359
360fn map_character_for_webkit_text_security(mode: WebKitTextSecurity, character: char) -> char {
366 if let WebKitTextSecurity::None = mode {
367 return character;
368 }
369
370 match character {
372 '\u{200B}' => '\u{200B}',
376 '\n' => '\n',
378 _ => match mode {
379 WebKitTextSecurity::None => character, WebKitTextSecurity::Circle => '○',
381 WebKitTextSecurity::Disc => '●',
382 WebKitTextSecurity::Square => '■',
383 },
384 }
385}
386
387#[derive(MallocSizeOf, Clone, Copy)]
388struct OffsetMapKnownPosition {
389 original_offset: Utf32CodeUnits,
390 final_offset: Utf32CodeUnits,
391}
392
393#[derive(Default, MallocSizeOf)]
394pub struct OffsetMap {
395 known_positions: Vec<OffsetMapKnownPosition>,
397 last_range_maps_one_to_one: bool,
399}
400
401impl std::fmt::Debug for OffsetMap {
402 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
403 f.debug_struct("OffsetMap")
404 .field("total_original_size", &self.total_original_size())
405 .field("total_final_size", &self.total_final_size())
406 .finish()
407 }
408}
409
410static IMPLICIT_KNOWN_POSITION_AT_START: OffsetMapKnownPosition = OffsetMapKnownPosition {
411 original_offset: Utf32CodeUnits(0),
412 final_offset: Utf32CodeUnits(0),
413};
414
415impl OffsetMap {
416 fn last_known_position(&self) -> &OffsetMapKnownPosition {
417 self.known_positions
418 .last()
419 .unwrap_or(&IMPLICIT_KNOWN_POSITION_AT_START)
420 }
421
422 pub fn total_original_size(&self) -> Utf32CodeUnits {
423 self.last_known_position().original_offset
424 }
425
426 pub fn total_final_size(&self) -> Utf32CodeUnits {
427 self.last_known_position().final_offset
428 }
429
430 pub fn push_range(
431 &mut self,
432 additional_original_length: Utf32CodeUnits,
433 additional_final_length: Utf32CodeUnits,
434 ) {
435 let this_range_maps_one_to_one = additional_original_length == additional_final_length;
436 if this_range_maps_one_to_one &&
437 self.last_range_maps_one_to_one &&
438 let Some(last) = self.known_positions.last_mut()
439 {
440 last.original_offset += additional_original_length;
441 last.final_offset += additional_final_length;
442 } else {
443 let last = self.last_known_position();
444 self.known_positions.push(OffsetMapKnownPosition {
445 original_offset: last.original_offset + additional_original_length,
446 final_offset: last.final_offset + additional_final_length,
447 });
448 }
449 self.last_range_maps_one_to_one = this_range_maps_one_to_one;
450 }
451
452 pub(crate) fn push_iteration(&mut self, iteration: &CharacterTransformIteration) {
453 self.push_range(
454 iteration.consumed,
455 Utf32CodeUnits(iteration.characters.len()),
456 );
457 }
458
459 pub fn map(&self, target_original_offset: Utf32CodeUnits) -> Utf32CodeUnits {
460 self.map_common(
461 target_original_offset,
462 |position| position.original_offset,
463 |position| position.final_offset,
464 )
465 }
466
467 pub fn reverse_map(&self, target_final_offset: Utf32CodeUnits) -> Utf32CodeUnits {
468 self.map_common(
469 target_final_offset,
470 |position| position.final_offset,
471 |position| position.original_offset,
472 )
473 }
474
475 fn map_common(
476 &self,
477 target_offset: Utf32CodeUnits,
478 get_input_offset: impl Copy + Fn(&OffsetMapKnownPosition) -> Utf32CodeUnits,
479 get_output_offset: impl Fn(&OffsetMapKnownPosition) -> Utf32CodeUnits,
480 ) -> Utf32CodeUnits {
481 if target_offset.0 == 0 {
482 return Utf32CodeUnits(0);
484 }
485 match self
486 .known_positions
487 .binary_search_by_key(&target_offset, get_input_offset)
488 {
489 Ok(index) => {
490 get_output_offset(&self.known_positions[index])
492 },
493 Err(index) => {
494 if let Some(position_after) = self.known_positions.get(index) {
496 let position_before = if index > 0 {
497 &self.known_positions[index - 1]
498 } else {
499 &IMPLICIT_KNOWN_POSITION_AT_START
500 };
501 debug_assert!(target_offset > get_input_offset(position_before));
502 debug_assert!(target_offset < get_input_offset(position_after));
503 let offset_within_range = target_offset - get_input_offset(position_before);
504 let candidate = get_output_offset(position_before) + offset_within_range;
505 let upper_bound = get_output_offset(position_after);
507 upper_bound.min(candidate)
508 } else {
509 get_output_offset(self.last_known_position())
511 }
512 },
513 }
514 }
515}
516
517#[test]
518fn test_offsetmap_basic_expansion() {
519 let original_string = "aßΰb";
520 let final_string = "ASS\u{3a5}\u{308}\u{301}B";
521 assert_eq!(original_string.to_uppercase(), final_string);
522
523 let mut offset_map = OffsetMap::default();
524 offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
525 'a'.to_uppercase(),
526 ));
527 offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
528 'ß'.to_uppercase(),
529 ));
530 offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
531 'ΰ'.to_uppercase(),
532 ));
533 offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
534 'b'.to_uppercase(),
535 ));
536
537 assert_eq!(offset_map.map(Utf32CodeUnits(0)).0, 0);
538 assert_eq!(offset_map.map(Utf32CodeUnits(1)).0, 1);
539 assert_eq!(offset_map.map(Utf32CodeUnits(2)).0, 3);
540 assert_eq!(offset_map.map(Utf32CodeUnits(3)).0, 6);
541 assert_eq!(offset_map.map(Utf32CodeUnits(4)).0, 7);
542
543 assert_eq!(offset_map.map(Utf32CodeUnits(5)).0, 7);
546 assert_eq!(offset_map.map(Utf32CodeUnits(100)).0, 7);
547
548 let map_substring = |offset: usize, length: usize| {
549 let start = offset_map
550 .map(Utf32CodeUnits(offset))
551 .to_utf8_code_units_in(final_string);
552 let end = offset_map
553 .map(Utf32CodeUnits(offset + length))
554 .to_utf8_code_units_in(final_string);
555 &final_string[start.0..end.0]
556 };
557 assert_eq!(map_substring(0, 1), "A");
558 assert_eq!(map_substring(0, 2), "ASS");
559 assert_eq!(map_substring(0, 3), "ASS\u{3a5}\u{308}\u{301}");
560 assert_eq!(map_substring(0, 4), "ASS\u{3a5}\u{308}\u{301}B");
561 assert_eq!(map_substring(1, 1), "SS");
562}
563
564#[test]
565fn test_offsetmap_basic_collapse() {
566 let _original_string = " aaa b \nc";
567 let final_string = "aaa b\nc";
568
569 let mut offset_map = OffsetMap::default();
570 offset_map.push_iteration(&CharacterTransformIteration::collapse(2, None));
571 offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
572 offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
573 offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
574 assert_eq!(
575 offset_map.known_positions.len(),
576 2,
577 "Consecutive one-to-one mappings are merged"
578 );
579
580 offset_map.push_iteration(&CharacterTransformIteration::collapse(2, Some(' ')));
581 offset_map.push_iteration(&CharacterTransformIteration::one_to_one('b'));
582 offset_map.push_iteration(&CharacterTransformIteration::collapse(2, Some('\n')));
583 offset_map.push_iteration(&CharacterTransformIteration::one_to_one('c'));
584
585 assert_eq!(offset_map.map(Utf32CodeUnits(0)).0, 0);
586 assert_eq!(offset_map.map(Utf32CodeUnits(1)).0, 0);
587 assert_eq!(offset_map.map(Utf32CodeUnits(2)).0, 0);
588 assert_eq!(offset_map.map(Utf32CodeUnits(3)).0, 1);
589 assert_eq!(offset_map.map(Utf32CodeUnits(4)).0, 2);
590 assert_eq!(offset_map.map(Utf32CodeUnits(5)).0, 3);
591 assert_eq!(offset_map.map(Utf32CodeUnits(6)).0, 4);
593 assert_eq!(offset_map.map(Utf32CodeUnits(7)).0, 4);
594 assert_eq!(offset_map.map(Utf32CodeUnits(8)).0, 5);
595 assert_eq!(offset_map.map(Utf32CodeUnits(9)).0, 6);
597 assert_eq!(offset_map.map(Utf32CodeUnits(10)).0, 6);
598 assert_eq!(offset_map.map(Utf32CodeUnits(11)).0, 7);
599
600 assert_eq!(offset_map.map(Utf32CodeUnits(12)).0, 7);
603 assert_eq!(offset_map.map(Utf32CodeUnits(100)).0, 7);
604
605 let map_substring = |offset: usize, length: usize| {
606 let start = offset_map.map(Utf32CodeUnits(offset)).0;
607 let end = offset_map.map(Utf32CodeUnits(offset + length)).0;
608 &final_string[start..end]
609 };
610 assert_eq!(map_substring(0, 1), "");
611 assert_eq!(map_substring(0, 3), "a");
612 assert_eq!(map_substring(0, 5), "aaa");
613 assert_eq!(map_substring(0, 6), "aaa ");
614 assert_eq!(map_substring(0, 7), "aaa ");
615 assert_eq!(map_substring(0, 8), "aaa b");
616 assert_eq!(map_substring(0, 11), "aaa b\nc");
617}