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
244 let text_transform = style.clone_text_transform();
246 let full_size_kana = text_transform.intersects(TextTransform::FULL_SIZE_KANA);
247 let _full_width = text_transform.intersects(TextTransform::FULL_WIDTH);
249 let chars = text.chars().map(move |character| {
252 let character = map_character_for_webkit_text_security(text_security, character);
253 map_character_for_full_size_kana(full_size_kana, character)
254 });
255 let white_space_collapse = style.clone_white_space_collapse();
256 let iterator =
257 WhitespaceCollapse::new(chars, white_space_collapse, trim_leading_white_space);
258
259 let iterator = match text_transform.case() {
260 TextTransformCase::None => {
261 Box::new(iterator) as Box<dyn Iterator<Item = CharacterTransformIteration>>
262 },
263 TextTransformCase::Lowercase => {
264 Box::new(simple_case_transform_iterator(iterator, |character| {
265 CharacterTransformIteration::case_mapped(character.to_lowercase())
266 }))
267 },
268 TextTransformCase::Uppercase => {
269 Box::new(simple_case_transform_iterator(iterator, |character| {
270 CharacterTransformIteration::case_mapped(character.to_uppercase())
271 }))
272 },
273 TextTransformCase::Capitalize => Box::new(capitalization_iterator(
274 iterator,
275 text.len(),
276 on_word_boundary,
277 )),
278 };
279
280 Self(iterator)
281 }
282}
283
284impl Iterator for TextTransformationIterator<'_> {
285 type Item = CharacterTransformIteration;
286 fn next(&mut self) -> Option<Self::Item> {
287 self.0.next()
288 }
289}
290
291fn simple_case_transform_iterator(
292 input_iterator: impl Iterator<Item = CharacterTransformIteration>,
293 mapping: impl Fn(char) -> CharacterTransformIteration,
294) -> impl Iterator<Item = CharacterTransformIteration> {
295 input_iterator.map(move |iteration| {
296 if iteration.is_one_to_one() {
297 mapping(iteration.characters[0])
298 } else {
299 iteration
300 }
301 })
302}
303
304pub(crate) fn capitalization_iterator(
309 input_iterator: impl Iterator<Item = CharacterTransformIteration>,
310 size_hint: usize,
311 allow_word_at_start: bool,
312) -> impl Iterator<Item = CharacterTransformIteration> {
313 let mut iterations: Vec<_> = input_iterator.collect();
314 let mut string = String::with_capacity(size_hint);
315 for iteration in &iterations {
316 string.extend(iteration.characters());
317 }
318
319 let word_segmenter = WordSegmenter::new_auto();
320 let mut bounds = word_segmenter.segment_str(&string).peekable();
321
322 let mut current_byte_index = 0;
323 for iteration in iterations.iter_mut() {
324 let bytes_to_advance: usize = iteration
325 .characters()
326 .iter()
327 .map(|character| character.len_utf8())
328 .sum();
329 if bytes_to_advance == 0 {
330 continue;
331 }
332
333 let at_word_start = bounds.peek() == Some(¤t_byte_index);
334 if at_word_start {
335 bounds.next();
336 }
337
338 if iteration.is_one_to_one() &&
343 at_word_start &&
344 (current_byte_index != 0 || allow_word_at_start)
345 {
346 *iteration =
350 CharacterTransformIteration::case_mapped(iteration.characters[0].to_uppercase());
351 }
352
353 current_byte_index += bytes_to_advance;
354 }
355
356 iterations.into_iter()
357}
358
359fn map_character_for_webkit_text_security(mode: WebKitTextSecurity, character: char) -> char {
365 if let WebKitTextSecurity::None = mode {
366 return character;
367 }
368
369 match character {
371 '\u{200B}' => '\u{200B}',
375 '\n' => '\n',
377 _ => match mode {
378 WebKitTextSecurity::None => character, WebKitTextSecurity::Circle => '○',
380 WebKitTextSecurity::Disc => '●',
381 WebKitTextSecurity::Square => '■',
382 },
383 }
384}
385
386fn map_character_for_full_size_kana(full_size_kana_enabled: bool, character: char) -> char {
387 if !full_size_kana_enabled {
388 character
389 } else {
390 super::small_kana::SMALL_KANA_MAPPINGS
392 .get(&character)
393 .copied()
394 .unwrap_or(character)
395 }
396}
397
398#[derive(MallocSizeOf, Clone, Copy)]
399struct OffsetMapKnownPosition {
400 original_offset: Utf32CodeUnits,
401 final_offset: Utf32CodeUnits,
402}
403
404#[derive(Default, MallocSizeOf)]
405pub struct OffsetMap {
406 known_positions: Vec<OffsetMapKnownPosition>,
408 last_range_maps_one_to_one: bool,
410}
411
412impl std::fmt::Debug for OffsetMap {
413 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
414 f.debug_struct("OffsetMap")
415 .field("total_original_size", &self.total_original_size())
416 .field("total_final_size", &self.total_final_size())
417 .finish()
418 }
419}
420
421static IMPLICIT_KNOWN_POSITION_AT_START: OffsetMapKnownPosition = OffsetMapKnownPosition {
422 original_offset: Utf32CodeUnits(0),
423 final_offset: Utf32CodeUnits(0),
424};
425
426impl OffsetMap {
427 fn last_known_position(&self) -> &OffsetMapKnownPosition {
428 self.known_positions
429 .last()
430 .unwrap_or(&IMPLICIT_KNOWN_POSITION_AT_START)
431 }
432
433 pub fn total_original_size(&self) -> Utf32CodeUnits {
434 self.last_known_position().original_offset
435 }
436
437 pub fn total_final_size(&self) -> Utf32CodeUnits {
438 self.last_known_position().final_offset
439 }
440
441 pub fn push_range(
442 &mut self,
443 additional_original_length: Utf32CodeUnits,
444 additional_final_length: Utf32CodeUnits,
445 ) {
446 let this_range_maps_one_to_one = additional_original_length == additional_final_length;
447 if this_range_maps_one_to_one &&
448 self.last_range_maps_one_to_one &&
449 let Some(last) = self.known_positions.last_mut()
450 {
451 last.original_offset += additional_original_length;
452 last.final_offset += additional_final_length;
453 } else {
454 let last = self.last_known_position();
455 self.known_positions.push(OffsetMapKnownPosition {
456 original_offset: last.original_offset + additional_original_length,
457 final_offset: last.final_offset + additional_final_length,
458 });
459 }
460 self.last_range_maps_one_to_one = this_range_maps_one_to_one;
461 }
462
463 pub(crate) fn push_iteration(&mut self, iteration: &CharacterTransformIteration) {
464 self.push_range(
465 iteration.consumed,
466 Utf32CodeUnits(iteration.characters.len()),
467 );
468 }
469
470 pub fn map(&self, target_original_offset: Utf32CodeUnits) -> Utf32CodeUnits {
471 self.map_common(
472 target_original_offset,
473 |position| position.original_offset,
474 |position| position.final_offset,
475 )
476 }
477
478 pub fn reverse_map(&self, target_final_offset: Utf32CodeUnits) -> Utf32CodeUnits {
479 self.map_common(
480 target_final_offset,
481 |position| position.final_offset,
482 |position| position.original_offset,
483 )
484 }
485
486 fn map_common(
487 &self,
488 target_offset: Utf32CodeUnits,
489 get_input_offset: impl Copy + Fn(&OffsetMapKnownPosition) -> Utf32CodeUnits,
490 get_output_offset: impl Fn(&OffsetMapKnownPosition) -> Utf32CodeUnits,
491 ) -> Utf32CodeUnits {
492 if target_offset.0 == 0 {
493 return Utf32CodeUnits(0);
495 }
496 match self
497 .known_positions
498 .binary_search_by_key(&target_offset, get_input_offset)
499 {
500 Ok(index) => {
501 get_output_offset(&self.known_positions[index])
503 },
504 Err(index) => {
505 if let Some(position_after) = self.known_positions.get(index) {
507 let position_before = if index > 0 {
508 &self.known_positions[index - 1]
509 } else {
510 &IMPLICIT_KNOWN_POSITION_AT_START
511 };
512 debug_assert!(target_offset > get_input_offset(position_before));
513 debug_assert!(target_offset < get_input_offset(position_after));
514 let offset_within_range = target_offset - get_input_offset(position_before);
515 let candidate = get_output_offset(position_before) + offset_within_range;
516 let upper_bound = get_output_offset(position_after);
518 upper_bound.min(candidate)
519 } else {
520 get_output_offset(self.last_known_position())
522 }
523 },
524 }
525 }
526}
527
528#[test]
529fn test_offsetmap_basic_expansion() {
530 let original_string = "aßΰb";
531 let final_string = "ASS\u{3a5}\u{308}\u{301}B";
532 assert_eq!(original_string.to_uppercase(), final_string);
533
534 let mut offset_map = OffsetMap::default();
535 offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
536 'a'.to_uppercase(),
537 ));
538 offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
539 'ß'.to_uppercase(),
540 ));
541 offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
542 'ΰ'.to_uppercase(),
543 ));
544 offset_map.push_iteration(&CharacterTransformIteration::case_mapped(
545 'b'.to_uppercase(),
546 ));
547
548 assert_eq!(offset_map.map(Utf32CodeUnits(0)).0, 0);
549 assert_eq!(offset_map.map(Utf32CodeUnits(1)).0, 1);
550 assert_eq!(offset_map.map(Utf32CodeUnits(2)).0, 3);
551 assert_eq!(offset_map.map(Utf32CodeUnits(3)).0, 6);
552 assert_eq!(offset_map.map(Utf32CodeUnits(4)).0, 7);
553
554 assert_eq!(offset_map.map(Utf32CodeUnits(5)).0, 7);
557 assert_eq!(offset_map.map(Utf32CodeUnits(100)).0, 7);
558
559 let map_substring = |offset: usize, length: usize| {
560 let start = offset_map
561 .map(Utf32CodeUnits(offset))
562 .to_utf8_code_units_in(final_string);
563 let end = offset_map
564 .map(Utf32CodeUnits(offset + length))
565 .to_utf8_code_units_in(final_string);
566 &final_string[start.0..end.0]
567 };
568 assert_eq!(map_substring(0, 1), "A");
569 assert_eq!(map_substring(0, 2), "ASS");
570 assert_eq!(map_substring(0, 3), "ASS\u{3a5}\u{308}\u{301}");
571 assert_eq!(map_substring(0, 4), "ASS\u{3a5}\u{308}\u{301}B");
572 assert_eq!(map_substring(1, 1), "SS");
573}
574
575#[test]
576fn test_offsetmap_basic_collapse() {
577 let _original_string = " aaa b \nc";
578 let final_string = "aaa b\nc";
579
580 let mut offset_map = OffsetMap::default();
581 offset_map.push_iteration(&CharacterTransformIteration::collapse(2, None));
582 offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
583 offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
584 offset_map.push_iteration(&CharacterTransformIteration::one_to_one('a'));
585 assert_eq!(
586 offset_map.known_positions.len(),
587 2,
588 "Consecutive one-to-one mappings are merged"
589 );
590
591 offset_map.push_iteration(&CharacterTransformIteration::collapse(2, Some(' ')));
592 offset_map.push_iteration(&CharacterTransformIteration::one_to_one('b'));
593 offset_map.push_iteration(&CharacterTransformIteration::collapse(2, Some('\n')));
594 offset_map.push_iteration(&CharacterTransformIteration::one_to_one('c'));
595
596 assert_eq!(offset_map.map(Utf32CodeUnits(0)).0, 0);
597 assert_eq!(offset_map.map(Utf32CodeUnits(1)).0, 0);
598 assert_eq!(offset_map.map(Utf32CodeUnits(2)).0, 0);
599 assert_eq!(offset_map.map(Utf32CodeUnits(3)).0, 1);
600 assert_eq!(offset_map.map(Utf32CodeUnits(4)).0, 2);
601 assert_eq!(offset_map.map(Utf32CodeUnits(5)).0, 3);
602 assert_eq!(offset_map.map(Utf32CodeUnits(6)).0, 4);
604 assert_eq!(offset_map.map(Utf32CodeUnits(7)).0, 4);
605 assert_eq!(offset_map.map(Utf32CodeUnits(8)).0, 5);
606 assert_eq!(offset_map.map(Utf32CodeUnits(9)).0, 6);
608 assert_eq!(offset_map.map(Utf32CodeUnits(10)).0, 6);
609 assert_eq!(offset_map.map(Utf32CodeUnits(11)).0, 7);
610
611 assert_eq!(offset_map.map(Utf32CodeUnits(12)).0, 7);
614 assert_eq!(offset_map.map(Utf32CodeUnits(100)).0, 7);
615
616 let map_substring = |offset: usize, length: usize| {
617 let start = offset_map.map(Utf32CodeUnits(offset)).0;
618 let end = offset_map.map(Utf32CodeUnits(offset + length)).0;
619 &final_string[start..end]
620 };
621 assert_eq!(map_substring(0, 1), "");
622 assert_eq!(map_substring(0, 3), "a");
623 assert_eq!(map_substring(0, 5), "aaa");
624 assert_eq!(map_substring(0, 6), "aaa ");
625 assert_eq!(map_substring(0, 7), "aaa ");
626 assert_eq!(map_substring(0, 8), "aaa b");
627 assert_eq!(map_substring(0, 11), "aaa b\nc");
628}