Bug 1890689 remove DynamicResampler::mSetBufferDuration r=pehrsons
[gecko.git] / intl / lwbrk / LineBreaker.cpp
blob6f73035f42cbb729f26a752d83349415257f113e
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 #include "mozilla/intl/LineBreaker.h"
8 #include "jisx4051class.h"
9 #include "nsComplexBreaker.h"
10 #include "nsTArray.h"
11 #include "nsUnicodeProperties.h"
12 #include "mozilla/ArrayUtils.h"
13 #include "mozilla/intl/Segmenter.h"
14 #include "mozilla/intl/UnicodeProperties.h"
16 #if defined(MOZ_ICU4X) && defined(JS_HAS_INTL_API)
17 # include "ICU4XDataProvider.h"
18 # include "ICU4XLineBreakIteratorLatin1.hpp"
19 # include "ICU4XLineBreakIteratorUtf16.hpp"
20 # include "ICU4XLineSegmenter.h"
21 # include "mozilla/CheckedInt.h"
22 # include "mozilla/ClearOnShutdown.h"
23 # include "mozilla/intl/ICU4XGeckoDataProvider.h"
24 # include "mozilla/StaticPrefs_intl.h"
25 # include "nsThreadUtils.h"
27 # include <mutex>
28 #endif
30 using namespace mozilla::unicode;
31 using namespace mozilla::intl;
35 Simplification of Pair Table in JIS X 4051
37 1. The Origion Table - in 4.1.3
39 In JIS x 4051. The pair table is defined as below
41 Class of
42 Leading Class of Trailing Char Class
43 Char
45 1 2 3 4 5 6 7 8 9 10 11 12 13 13 14 14 15 16 17 18 19 20
46 * # * #
47 1 X X X X X X X X X X X X X X X X X X X X X E
48 2 X X X X X X
49 3 X X X X X X
50 4 X X X X X X
51 5 X X X X X X
52 6 X X X X X X
53 7 X X X X X X X
54 8 X X X X X X E
55 9 X X X X X X
56 10 X X X X X X
57 11 X X X X X X
58 12 X X X X X X
59 13 X X X X X X X
60 14 X X X X X X X
61 15 X X X X X X X X X
62 16 X X X X X X X X
63 17 X X X X X E
64 18 X X X X X X X X X
65 19 X E E E E E X X X X X X X X X X X X E X E E
66 20 X X X X X E
68 * Same Char
69 # Other Char
71 X Cannot Break
73 The classes mean:
74 1: Open parenthesis
75 2: Close parenthesis
76 3: Prohibit a line break before
77 4: Punctuation for sentence end (except Full stop, e.g., "!" and "?")
78 5: Middle dot (e.g., U+30FB KATAKANA MIDDLE DOT)
79 6: Full stop
80 7: Non-breakable between same characters
81 8: Prefix (e.g., "$", "NO.")
82 9: Postfix (e.g., "%")
83 10: Ideographic space
84 11: Hiragana
85 12: Japanese characters (except class 11)
86 13: Subscript
87 14: Ruby
88 15: Numeric
89 16: Alphabet
90 17: Space for Western language
91 18: Western characters (except class 17)
92 19: Split line note (Warichu) begin quote
93 20: Split line note (Warichu) end quote
95 2. Simplified by remove the class which we do not care
97 However, since we do not care about class 13(Subscript), 14(Ruby),
98 16 (Aphabet), 19(split line note begin quote), and 20(split line note end
99 quote) we can simplify this par table into the following
101 Class of
102 Leading Class of Trailing Char Class
103 Char
105 1 2 3 4 5 6 7 8 9 10 11 12 15 17 18
107 1 X X X X X X X X X X X X X X X
108 2 X X X X X
109 3 X X X X X
110 4 X X X X X
111 5 X X X X X
112 6 X X X X X
113 7 X X X X X X
114 8 X X X X X X
115 9 X X X X X
116 10 X X X X X
117 11 X X X X X
118 12 X X X X X
119 15 X X X X X X X X
120 17 X X X X X
121 18 X X X X X X X
123 3. Simplified by merged classes
125 After the 2 simplification, the pair table have some duplication
126 a. class 2, 3, 4, 5, 6, are the same- we can merged them
127 b. class 10, 11, 12, 17 are the same- we can merged them
129 We introduce an extra non-breaking pair at [b]/7 to better match
130 the expectations of CSS line-breaking as tested by WPT tests.
131 This added entry is marked as * in the tables below.
133 Class of
134 Leading Class of Trailing Char Class
135 Char
137 1 [a] 7 8 9 [b]15 18
139 1 X X X X X X X X
140 [a] X
141 7 X X
142 8 X X
144 [b] X *
145 15 X X X X
146 18 X X X
149 4. We add COMPLEX characters and make it breakable w/ all ther class
150 except after class 1 and before class [a]
152 Class of
153 Leading Class of Trailing Char Class
154 Char
156 1 [a] 7 8 9 [b]15 18 COMPLEX
158 1 X X X X X X X X X
159 [a] X
160 7 X X
161 8 X X
163 [b] X *
164 15 X X X X
165 18 X X X
166 COMPLEX X T
168 T : need special handling
171 5. However, we need two special class for some punctuations/parentheses,
172 theirs breaking rules like character class (18), see bug 389056.
173 And also we need character like punctuation that is same behavior with 18,
174 but the characters are not letters of all languages. (e.g., '_')
175 [c]. Based on open parenthesis class (1), but it is not breakable after
176 character class (18) or numeric class (15).
177 [d]. Based on close parenthesis (or punctuation) class (2), but it is not
178 breakable before character class (18) or numeric class (15).
180 Class of
181 Leading Class of Trailing Char Class
182 Char
184 1 [a] 7 8 9 [b]15 18 COMPLEX [c] [d]
186 1 X X X X X X X X X X X
187 [a] X X X
188 7 X X
189 8 X X
191 [b] X * X
192 15 X X X X X X
193 18 X X X X X
194 COMPLEX X T
195 [c] X X X X X X X X X X X
196 [d] X X X X
199 6. And Unicode has "NON-BREAK" characters. The lines should be broken around
200 them. But in JIS X 4051, such class is not, therefore, we create [e].
202 Class of
203 Leading Class of Trailing Char Class
204 Char
206 1 [a] 7 8 9 [b]15 18 COMPLEX [c] [d] [e]
208 1 X X X X X X X X X X X X
209 [a] X X X
210 7 X X X
211 8 X X X
212 9 X X
213 [b] X * X X
214 15 X X X X X X X
215 18 X X X X X X
216 COMPLEX X T X
217 [c] X X X X X X X X X X X X
218 [d] X X X X X
219 [e] X X X X X X X X X X X X
222 7. Now we use one bit to encode whether it is breakable, and use 2 bytes
223 for one row, then the bit table will look like:
225 18 <- 1
227 1 0000 1111 1111 1111 = 0x0FFF
228 [a] 0000 1100 0000 0010 = 0x0C02
229 7 0000 1000 0000 0110 = 0x0806
230 8 0000 1000 0100 0010 = 0x0842
231 9 0000 1000 0000 0010 = 0x0802
232 [b] 0000 1100 0000 0110 = 0x0C06
233 15 0000 1110 1101 0010 = 0x0ED2
234 18 0000 1110 1100 0010 = 0x0EC2
235 COMPLEX 0000 1001 0000 0010 = 0x0902
236 [c] 0000 1111 1111 1111 = 0x0FFF
237 [d] 0000 1100 1100 0010 = 0x0CC2
238 [e] 0000 1111 1111 1111 = 0x0FFF
241 #define MAX_CLASSES 12
243 static const uint16_t gPair[MAX_CLASSES] = {0x0FFF, 0x0C02, 0x0806, 0x0842,
244 0x0802, 0x0C06, 0x0ED2, 0x0EC2,
245 0x0902, 0x0FFF, 0x0CC2, 0x0FFF};
249 8. And if the character is not enough far from word start, word end and
250 another break point, we should not break in non-CJK languages.
251 I.e., Don't break around 15, 18, [c] and [d], but don't change
252 that if they are related to [b].
254 Class of
255 Leading Class of Trailing Char Class
256 Char
258 1 [a] 7 8 9 [b]15 18 COMPLEX [c] [d] [e]
260 1 X X X X X X X X X X X X
261 [a] X X X X X X
262 7 X X X X X X X
263 8 X X X X X X
264 9 X X X X X X
265 [b] X * X X
266 15 X X X X X X X X X X X
267 18 X X X X X X X X X X X
268 COMPLEX X X X T X X X
269 [c] X X X X X X X X X X X X
270 [d] X X X X X X X X X X X
271 [e] X X X X X X X X X X X X
273 18 <- 1
275 1 0000 1111 1111 1111 = 0x0FFF
276 [a] 0000 1110 1100 0010 = 0x0EC2
277 7 0000 1110 1100 0110 = 0x0EC6
278 8 0000 1110 1100 0010 = 0x0EC2
279 9 0000 1110 1100 0010 = 0x0EC2
280 [b] 0000 1100 0000 0110 = 0x0C06
281 15 0000 1111 1101 1111 = 0x0FDF
282 18 0000 1111 1101 1111 = 0x0FDF
283 COMPLEX 0000 1111 1100 0010 = 0x0FC2
284 [c] 0000 1111 1111 1111 = 0x0FFF
285 [d] 0000 1111 1101 1111 = 0x0FDF
286 [e] 0000 1111 1111 1111 = 0x0FFF
289 static const uint16_t gPairConservative[MAX_CLASSES] = {
290 0x0FFF, 0x0EC2, 0x0EC6, 0x0EC2, 0x0EC2, 0x0C06,
291 0x0FDF, 0x0FDF, 0x0FC2, 0x0FFF, 0x0FDF, 0x0FFF};
295 9. Now we map the class to number
297 0: 1
298 1: [a]- 2, 3, 4, 5, 6
299 2: 7
300 3: 8
301 4: 9
302 5: [b]- 10, 11, 12, 17
303 6: 15
304 7: 18
305 8: COMPLEX
306 9: [c]
307 A: [d]
308 B: [e]
310 and they mean:
311 0: Open parenthesis
312 1: Punctuation that prohibits break before
313 2: Non-breakable between same classes
314 3: Prefix
315 4: Postfix
316 5: Breakable character (Spaces and Most Japanese characters)
317 6: Numeric
318 7: Characters
319 8: Need special handling characters (E.g., Thai)
320 9: Open parentheses like Character (See bug 389056)
321 A: Close parenthese (or punctuations) like Character (See bug 389056)
322 B: Non breakable (See bug 390920)
326 #define CLASS_NONE INT8_MAX
328 #define CLASS_OPEN 0x00
329 #define CLASS_CLOSE 0x01
330 #define CLASS_NON_BREAKABLE_BETWEEN_SAME_CLASS 0x02
331 #define CLASS_PREFIX 0x03
332 #define CLASS_POSTFFIX 0x04
333 #define CLASS_BREAKABLE 0x05
334 #define CLASS_NUMERIC 0x06
335 #define CLASS_CHARACTER 0x07
336 #define CLASS_COMPLEX 0x08
337 #define CLASS_OPEN_LIKE_CHARACTER 0x09
338 #define CLASS_CLOSE_LIKE_CHARACTER 0x0A
339 #define CLASS_NON_BREAKABLE 0x0B
341 #define U_NULL char16_t(0x0000)
342 #define U_SLASH char16_t('/')
343 #define U_SPACE char16_t(' ')
344 #define U_HYPHEN char16_t('-')
345 #define U_EQUAL char16_t('=')
346 #define U_PERCENT char16_t('%')
347 #define U_AMPERSAND char16_t('&')
348 #define U_SEMICOLON char16_t(';')
349 #define U_BACKSLASH char16_t('\\')
350 #define U_OPEN_SINGLE_QUOTE char16_t(0x2018)
351 #define U_OPEN_DOUBLE_QUOTE char16_t(0x201C)
352 #define U_OPEN_GUILLEMET char16_t(0x00AB)
354 #define NEED_CONTEXTUAL_ANALYSIS(c) \
355 (IS_HYPHEN(c) || (c) == U_SLASH || (c) == U_PERCENT || (c) == U_AMPERSAND || \
356 (c) == U_SEMICOLON || (c) == U_BACKSLASH || (c) == U_OPEN_SINGLE_QUOTE || \
357 (c) == U_OPEN_DOUBLE_QUOTE || (c) == U_OPEN_GUILLEMET)
359 #define IS_ASCII_DIGIT(u) (0x0030 <= (u) && (u) <= 0x0039)
361 static inline int GETCLASSFROMTABLE(const uint32_t* t, uint16_t l) {
362 return ((((t)[(l >> 3)]) >> ((l & 0x0007) << 2)) & 0x000f);
365 static inline int IS_HALFWIDTH_IN_JISx4051_CLASS3(char16_t u) {
366 return ((0xff66 <= (u)) && ((u) <= 0xff70));
369 static inline int IS_CJK_CHAR(char32_t u) {
370 return (
371 (0x1100 <= (u) && (u) <= 0x11ff) || (0x2e80 <= (u) && (u) <= 0xd7ff) ||
372 (0xf900 <= (u) && (u) <= 0xfaff) || (0xff00 <= (u) && (u) <= 0xffef) ||
373 (0x20000 <= (u) && (u) <= 0x2fffd));
376 static inline bool IS_NONBREAKABLE_SPACE(char16_t u) {
377 return u == 0x00A0 || u == 0x2007; // NO-BREAK SPACE, FIGURE SPACE
380 static inline bool IS_HYPHEN(char16_t u) {
381 return (u == U_HYPHEN || u == 0x2010 || // HYPHEN
382 u == 0x2012 || // FIGURE DASH
383 u == 0x2013 || // EN DASH
384 #if ANDROID || XP_WIN
385 /* Bug 1647377: On Android and Windows, we don't have a "platform"
386 * backend that supports Tibetan (nsRuleBreaker.cpp only knows about
387 * Thai, and ScriptBreak doesn't handle Tibetan well either), so
388 * instead we just treat the TSHEG like a hyphen to provide basic
389 * line-breaking possibilities.
391 u == 0x0F0B || // TIBETAN MARK INTERSYLLABIC TSHEG
392 #endif
393 u == 0x058A); // ARMENIAN HYPHEN
396 static int8_t GetClass(uint32_t u, LineBreakRule aLevel,
397 bool aIsChineseOrJapanese) {
398 // Mapping for Unicode LineBreak.txt classes to the (simplified) set of
399 // character classes used here.
400 // XXX The mappings here were derived by comparing the Unicode LineBreak
401 // values of BMP characters to the classes our existing GetClass returns
402 // for the same codepoints; in cases where characters with the same
403 // LineBreak class mapped to various classes here, I picked what seemed
404 // the most prevalent equivalence.
405 // Some of these are unclear to me, but currently they are ONLY used
406 // for characters not handled by the old code below, so all the JISx405
407 // special cases should already be accounted for.
408 static const int8_t sUnicodeLineBreakToClass[] = {
409 /* UNKNOWN = 0, [XX] */ CLASS_CHARACTER,
410 /* AMBIGUOUS = 1, [AI] */ CLASS_CHARACTER,
411 /* ALPHABETIC = 2, [AL] */ CLASS_CHARACTER,
412 /* BREAK_BOTH = 3, [B2] */ CLASS_CHARACTER,
413 /* BREAK_AFTER = 4, [BA] */ CLASS_BREAKABLE,
414 /* BREAK_BEFORE = 5, [BB] */ CLASS_OPEN_LIKE_CHARACTER,
415 /* MANDATORY_BREAK = 6, [BK] */ CLASS_CHARACTER,
416 /* CONTINGENT_BREAK = 7, [CB] */ CLASS_CHARACTER,
417 /* CLOSE_PUNCTUATION = 8, [CL] */ CLASS_CLOSE_LIKE_CHARACTER,
418 /* COMBINING_MARK = 9, [CM] */ CLASS_CHARACTER,
419 /* CARRIAGE_RETURN = 10, [CR] */ CLASS_BREAKABLE,
420 /* EXCLAMATION = 11, [EX] */ CLASS_CLOSE_LIKE_CHARACTER,
421 /* GLUE = 12, [GL] */ CLASS_NON_BREAKABLE,
422 /* HYPHEN = 13, [HY] */ CLASS_CHARACTER,
423 /* IDEOGRAPHIC = 14, [ID] */ CLASS_BREAKABLE,
424 /* INSEPARABLE = 15, [IN] */ CLASS_CLOSE_LIKE_CHARACTER,
425 /* INFIX_NUMERIC = 16, [IS] */ CLASS_CHARACTER,
426 /* LINE_FEED = 17, [LF] */ CLASS_BREAKABLE,
427 /* NONSTARTER = 18, [NS] */ CLASS_CLOSE_LIKE_CHARACTER,
428 /* NUMERIC = 19, [NU] */ CLASS_NUMERIC,
429 /* OPEN_PUNCTUATION = 20, [OP] */ CLASS_OPEN_LIKE_CHARACTER,
430 /* POSTFIX_NUMERIC = 21, [PO] */ CLASS_CLOSE_LIKE_CHARACTER,
431 /* PREFIX_NUMERIC = 22, [PR] */ CLASS_CHARACTER,
432 /* QUOTATION = 23, [QU] */ CLASS_CHARACTER,
433 /* COMPLEX_CONTEXT = 24, [SA] */ CLASS_CHARACTER,
434 /* SURROGATE = 25, [SG] */ CLASS_CHARACTER,
435 /* SPACE = 26, [SP] */ CLASS_BREAKABLE,
436 /* BREAK_SYMBOLS = 27, [SY] */ CLASS_CHARACTER,
437 /* ZWSPACE = 28, [ZW] */ CLASS_BREAKABLE,
438 /* NEXT_LINE = 29, [NL] */ CLASS_CHARACTER,
439 /* WORD_JOINER = 30, [WJ] */ CLASS_NON_BREAKABLE,
440 /* H2 = 31, [H2] */ CLASS_BREAKABLE,
441 /* H3 = 32, [H3] */ CLASS_BREAKABLE,
442 /* JL = 33, [JL] */ CLASS_CHARACTER,
443 /* JT = 34, [JT] */ CLASS_CHARACTER,
444 /* JV = 35, [JV] */ CLASS_CHARACTER,
445 /* CLOSE_PARENTHESIS = 36, [CP] */ CLASS_CLOSE_LIKE_CHARACTER,
446 /* CONDITIONAL_JAPANESE_STARTER = 37, [CJ] */ CLASS_CLOSE,
447 /* HEBREW_LETTER = 38, [HL] */ CLASS_CHARACTER,
448 /* REGIONAL_INDICATOR = 39, [RI] */ CLASS_CHARACTER,
449 /* E_BASE = 40, [EB] */ CLASS_BREAKABLE,
450 /* E_MODIFIER = 41, [EM] */ CLASS_CHARACTER,
451 /* ZWJ = 42, [ZWJ]*/ CLASS_CHARACTER};
453 static_assert(U_LB_COUNT == mozilla::ArrayLength(sUnicodeLineBreakToClass),
454 "Gecko vs ICU LineBreak class mismatch");
456 auto cls = GetLineBreakClass(u);
457 MOZ_ASSERT(cls < mozilla::ArrayLength(sUnicodeLineBreakToClass));
459 // Overrides based on rules for the different line-break values given in
460 // https://drafts.csswg.org/css-text-3/#line-break-property
461 switch (aLevel) {
462 case LineBreakRule::Auto:
463 // For now, just use legacy Gecko behavior.
464 // XXX Possible enhancement - vary strictness according to line width
465 // or other criteria.
466 break;
467 case LineBreakRule::Strict:
468 if (cls == U_LB_CONDITIONAL_JAPANESE_STARTER ||
469 (u == 0x3095 || u == 0x3096 || u == 0x30f5 || u == 0x30f6)) {
470 return CLASS_CLOSE;
472 if (cls == U_LB_INSEPARABLE) {
473 return CLASS_NON_BREAKABLE_BETWEEN_SAME_CLASS;
475 if (u == 0x3005 || u == 0x303B || u == 0x309D || u == 0x309E ||
476 u == 0x30FD || u == 0x30FE) {
477 return CLASS_CLOSE_LIKE_CHARACTER;
479 if (aIsChineseOrJapanese) {
480 if (cls == U_LB_POSTFIX_NUMERIC &&
481 UnicodeProperties::IsEastAsianWidthAFW(u)) {
482 return CLASS_CLOSE_LIKE_CHARACTER;
484 if (cls == U_LB_PREFIX_NUMERIC &&
485 UnicodeProperties::IsEastAsianWidthAFW(u)) {
486 return CLASS_OPEN_LIKE_CHARACTER;
488 if (u == 0x2010 || u == 0x2013 || u == 0x301C || u == 0x30A0) {
489 return CLASS_CLOSE_LIKE_CHARACTER;
492 break;
493 case LineBreakRule::Normal:
494 if (cls == U_LB_CONDITIONAL_JAPANESE_STARTER) {
495 return CLASS_BREAKABLE;
497 if (cls == U_LB_INSEPARABLE) {
498 return CLASS_NON_BREAKABLE_BETWEEN_SAME_CLASS;
500 if (u == 0x3005 || u == 0x303B || u == 0x309D || u == 0x309E ||
501 u == 0x30FD || u == 0x30FE) {
502 return CLASS_CLOSE_LIKE_CHARACTER;
504 if (aIsChineseOrJapanese) {
505 if (cls == U_LB_POSTFIX_NUMERIC &&
506 UnicodeProperties::IsEastAsianWidthAFW(u)) {
507 return CLASS_CLOSE_LIKE_CHARACTER;
509 if (cls == U_LB_PREFIX_NUMERIC &&
510 UnicodeProperties::IsEastAsianWidthAFW(u)) {
511 return CLASS_OPEN_LIKE_CHARACTER;
513 if (u == 0x2010 || u == 0x2013 || u == 0x301C || u == 0x30A0) {
514 return CLASS_BREAKABLE;
517 break;
518 case LineBreakRule::Loose:
519 if (cls == U_LB_CONDITIONAL_JAPANESE_STARTER) {
520 return CLASS_BREAKABLE;
522 if (u == 0x3005 || u == 0x303B || u == 0x309D || u == 0x309E ||
523 u == 0x30FD || u == 0x30FE) {
524 return CLASS_BREAKABLE;
526 if (cls == U_LB_INSEPARABLE) {
527 return CLASS_BREAKABLE;
529 if (aIsChineseOrJapanese) {
530 if (u == 0x30FB || u == 0xFF1A || u == 0xFF1B || u == 0xFF65 ||
531 u == 0x203C || u == 0x2047 || u == 0x2048 || u == 0x2049 ||
532 u == 0xFF01 || u == 0xFF1F) {
533 return CLASS_BREAKABLE;
535 if (cls == U_LB_POSTFIX_NUMERIC &&
536 UnicodeProperties::IsEastAsianWidthAFW(u)) {
537 return CLASS_BREAKABLE;
539 if (cls == U_LB_PREFIX_NUMERIC &&
540 UnicodeProperties::IsEastAsianWidthAFW(u)) {
541 return CLASS_BREAKABLE;
543 if (u == 0x2010 || u == 0x2013 || u == 0x301C || u == 0x30A0) {
544 return CLASS_BREAKABLE;
547 break;
548 case LineBreakRule::Anywhere:
549 MOZ_ASSERT_UNREACHABLE("should have been handled already");
550 break;
553 if (u < 0x10000) {
554 uint16_t h = u & 0xFF00;
555 uint16_t l = u & 0x00ff;
557 // Handle 3 range table first
558 if (0x0000 == h) {
559 return GETCLASSFROMTABLE(gLBClass00, l);
561 if (0x1700 == h) {
562 return GETCLASSFROMTABLE(gLBClass17, l);
564 if (NS_NeedsPlatformNativeHandling(u)) {
565 return CLASS_COMPLEX;
567 if (0x0E00 == h) {
568 return GETCLASSFROMTABLE(gLBClass0E, l);
570 if (0x2000 == h) {
571 return GETCLASSFROMTABLE(gLBClass20, l);
573 if (0x2100 == h) {
574 return GETCLASSFROMTABLE(gLBClass21, l);
576 if (0x3000 == h) {
577 return GETCLASSFROMTABLE(gLBClass30, l);
579 if (0xff00 == h) {
580 if (l <= 0x0060) { // Fullwidth ASCII variant
581 // Previously, we treated Fullwidth chars the same as their ASCII
582 // counterparts, but UAX#14 (LineBreak.txt) disagrees with this and
583 // treats many of them as ideograph-like.
584 return sUnicodeLineBreakToClass[cls];
586 if (l < 0x00a0) { // Halfwidth Katakana variants
587 switch (l) {
588 case 0x61:
589 return GetClass(0x3002, aLevel, aIsChineseOrJapanese);
590 case 0x62:
591 return GetClass(0x300c, aLevel, aIsChineseOrJapanese);
592 case 0x63:
593 return GetClass(0x300d, aLevel, aIsChineseOrJapanese);
594 case 0x64:
595 return GetClass(0x3001, aLevel, aIsChineseOrJapanese);
596 case 0x65:
597 return GetClass(0x30fb, aLevel, aIsChineseOrJapanese);
598 case 0x9e:
599 return GetClass(0x309b, aLevel, aIsChineseOrJapanese);
600 case 0x9f:
601 return GetClass(0x309c, aLevel, aIsChineseOrJapanese);
602 default:
603 if (IS_HALFWIDTH_IN_JISx4051_CLASS3(u)) {
604 return CLASS_CLOSE; // jis x4051 class 3
606 return CLASS_BREAKABLE; // jis x4051 class 11
609 if (l < 0x00e0) {
610 return CLASS_CHARACTER; // Halfwidth Hangul variants
612 if (l < 0x00f0) {
613 static char16_t NarrowFFEx[16] = {
614 0x00A2, 0x00A3, 0x00AC, 0x00AF, 0x00A6, 0x00A5, 0x20A9, 0x0000,
615 0x2502, 0x2190, 0x2191, 0x2192, 0x2193, 0x25A0, 0x25CB, 0x0000};
616 return GetClass(NarrowFFEx[l - 0x00e0], aLevel, aIsChineseOrJapanese);
618 } else if (0x3100 == h) {
619 if (l <= 0xbf) { // Hangul Compatibility Jamo, Bopomofo, Kanbun
620 // XXX: This is per UAX #14, but UAX #14 may change
621 // the line breaking rules about Kanbun and Bopomofo.
622 return CLASS_BREAKABLE;
624 if (l >= 0xf0) { // Katakana small letters for Ainu
625 return CLASS_CLOSE;
627 } else if (0x0300 == h) {
628 if (0x4F == l || (0x5C <= l && l <= 0x62)) {
629 return CLASS_NON_BREAKABLE;
631 } else if (0x0500 == h) {
632 // ARMENIAN HYPHEN (for "Breaking Hyphens" of UAX#14)
633 if (l == 0x8A) {
634 return GETCLASSFROMTABLE(gLBClass00, uint16_t(U_HYPHEN));
636 } else if (0x0F00 == h) {
637 // We treat Tibetan TSHEG as a hyphen (when not using platform breaker);
638 // other Tibetan chars with LineBreak class=BA will be handled by the
639 // default sUnicodeLineBreakToClass mapping below.
640 if (l == 0x0B) {
641 return GETCLASSFROMTABLE(gLBClass00, uint16_t(U_HYPHEN));
643 } else if (0x1800 == h) {
644 if (0x0E == l) {
645 return CLASS_NON_BREAKABLE;
647 } else if (0x1600 == h) {
648 if (0x80 == l) { // U+1680 OGHAM SPACE MARK
649 return CLASS_BREAKABLE;
651 } else if (u == 0xfeff) {
652 return CLASS_NON_BREAKABLE;
656 return sUnicodeLineBreakToClass[cls];
659 static bool GetPair(int8_t c1, int8_t c2) {
660 NS_ASSERTION(c1 < MAX_CLASSES, "illegal classes 1");
661 NS_ASSERTION(c2 < MAX_CLASSES, "illegal classes 2");
663 return (0 == ((gPair[c1] >> c2) & 0x0001));
666 static bool GetPairConservative(int8_t c1, int8_t c2) {
667 NS_ASSERTION(c1 < MAX_CLASSES, "illegal classes 1");
668 NS_ASSERTION(c2 < MAX_CLASSES, "illegal classes 2");
670 return (0 == ((gPairConservative[c1] >> c2) & 0x0001));
673 class ContextState {
674 public:
675 ContextState(const char16_t* aText, uint32_t aLength)
676 : mUniText(aText), mText(nullptr), mLength(aLength) {
677 Init();
680 ContextState(const uint8_t* aText, uint32_t aLength)
681 : mUniText(nullptr), mText(aText), mLength(aLength) {
682 Init();
685 uint32_t Length() const { return mLength; }
686 uint32_t Index() const { return mIndex; }
688 // This gets a single code unit of the text, without checking for surrogates
689 // (in the case of a 16-bit text buffer). That's OK if we're only checking for
690 // specific characters that are known to be BMP values.
691 char16_t GetCodeUnitAt(uint32_t aIndex) const {
692 MOZ_ASSERT(aIndex < mLength, "Out of range!");
693 return mUniText ? mUniText[aIndex] : char16_t(mText[aIndex]);
696 // This gets a 32-bit Unicode character (codepoint), handling surrogate pairs
697 // as necessary. It must ONLY be called for 16-bit text, not 8-bit.
698 char32_t GetUnicodeCharAt(uint32_t aIndex) const {
699 MOZ_ASSERT(mUniText, "Only for 16-bit text!");
700 MOZ_ASSERT(aIndex < mLength, "Out of range!");
701 char32_t c = mUniText[aIndex];
702 if (aIndex + 1 < mLength && NS_IS_SURROGATE_PAIR(c, mUniText[aIndex + 1])) {
703 c = SURROGATE_TO_UCS4(c, mUniText[aIndex + 1]);
705 return c;
708 void AdvanceIndex() { ++mIndex; }
710 void NotifyBreakBefore() { mLastBreakIndex = mIndex; }
712 // A word of western language should not be broken. But even if the word has
713 // only ASCII characters, non-natural context words should be broken, e.g.,
714 // URL and file path. For protecting the natural words, we should use
715 // conservative breaking rules at following conditions:
716 // 1. at near the start of word
717 // 2. at near the end of word
718 // 3. at near the latest broken point
719 // CONSERVATIVE_RANGE_{LETTER,OTHER} define the 'near' in characters,
720 // which varies depending whether we are looking at a letter or a non-letter
721 // character: for non-letters, we use an extended "conservative" range.
723 #define CONSERVATIVE_RANGE_LETTER 2
724 #define CONSERVATIVE_RANGE_OTHER 6
726 bool UseConservativeBreaking(uint32_t aOffset = 0) const {
727 if (mHasCJKChar) return false;
728 uint32_t index = mIndex + aOffset;
730 // If the character at index is a letter (rather than various punctuation
731 // characters, etc) then we want a shorter "conservative" range
732 uint32_t conservativeRangeStart, conservativeRangeEnd;
733 if (index < mLength &&
734 nsUGenCategory::kLetter ==
735 (mText ? GetGenCategory(mText[index])
736 : GetGenCategory(GetUnicodeCharAt(index)))) {
737 // Primarily for hyphenated word prefixes/suffixes; we add 1 to Start
738 // to get more balanced behavior (if we break off a 2-letter prefix,
739 // that means the break will actually be three letters from start of
740 // word, to include the hyphen; whereas a 2-letter suffix will be
741 // broken only two letters from end of word).
742 conservativeRangeEnd = CONSERVATIVE_RANGE_LETTER;
743 conservativeRangeStart = CONSERVATIVE_RANGE_LETTER + 1;
744 } else {
745 conservativeRangeEnd = conservativeRangeStart = CONSERVATIVE_RANGE_OTHER;
748 bool result = (index < conservativeRangeStart ||
749 mLength - index < conservativeRangeEnd ||
750 index - mLastBreakIndex < conservativeRangeStart);
751 if (result || !mHasNonbreakableSpace) return result;
753 // This text has no-breakable space, we need to check whether the index
754 // is near it.
756 // Note that index is always larger than conservativeRange here.
757 for (uint32_t i = index; index - conservativeRangeStart < i; --i) {
758 if (IS_NONBREAKABLE_SPACE(GetCodeUnitAt(i - 1))) return true;
760 // Note that index is always less than mLength - conservativeRange.
761 for (uint32_t i = index + 1; i < index + conservativeRangeEnd; ++i) {
762 if (IS_NONBREAKABLE_SPACE(GetCodeUnitAt(i))) return true;
764 return false;
767 bool HasPreviousEqualsSign() const { return mHasPreviousEqualsSign; }
768 void NotifySeenEqualsSign() { mHasPreviousEqualsSign = true; }
770 bool HasPreviousSlash() const { return mHasPreviousSlash; }
771 void NotifySeenSlash() { mHasPreviousSlash = true; }
773 bool HasPreviousBackslash() const { return mHasPreviousBackslash; }
774 void NotifySeenBackslash() { mHasPreviousBackslash = true; }
776 uint32_t GetPreviousNonHyphenCharacter() const {
777 return mPreviousNonHyphenCharacter;
779 void NotifyNonHyphenCharacter(uint32_t ch) {
780 mPreviousNonHyphenCharacter = ch;
783 private:
784 void Init() {
785 mIndex = 0;
786 mLastBreakIndex = 0;
787 mPreviousNonHyphenCharacter = U_NULL;
788 mHasCJKChar = false;
789 mHasNonbreakableSpace = false;
790 mHasPreviousEqualsSign = false;
791 mHasPreviousSlash = false;
792 mHasPreviousBackslash = false;
794 if (mText) {
795 // 8-bit text: we only need to check for &nbsp;
796 for (uint32_t i = 0; i < mLength; ++i) {
797 if (IS_NONBREAKABLE_SPACE(mText[i])) {
798 mHasNonbreakableSpace = true;
799 break;
802 } else {
803 // 16-bit text: handle surrogates and check for CJK as well as &nbsp;
804 for (uint32_t i = 0; i < mLength; ++i) {
805 char32_t u = GetUnicodeCharAt(i);
806 if (!mHasNonbreakableSpace && IS_NONBREAKABLE_SPACE(u)) {
807 mHasNonbreakableSpace = true;
808 if (mHasCJKChar) {
809 break;
811 } else if (!mHasCJKChar && IS_CJK_CHAR(u)) {
812 mHasCJKChar = true;
813 if (mHasNonbreakableSpace) {
814 break;
817 if (u > 0xFFFFu) {
818 ++i; // step over trailing low surrogate
824 const char16_t* const mUniText;
825 const uint8_t* const mText;
827 uint32_t mIndex;
828 const uint32_t mLength; // length of text
829 uint32_t mLastBreakIndex;
830 char32_t mPreviousNonHyphenCharacter; // The last character we have seen
831 // which is not U_HYPHEN
832 bool mHasCJKChar; // if the text has CJK character, this is true.
833 bool mHasNonbreakableSpace; // if the text has no-breakable space,
834 // this is true.
835 bool mHasPreviousEqualsSign; // True if we have seen a U_EQUAL
836 bool mHasPreviousSlash; // True if we have seen a U_SLASH
837 bool mHasPreviousBackslash; // True if we have seen a U_BACKSLASH
840 static int8_t ContextualAnalysis(char32_t prev, char32_t cur, char32_t next,
841 ContextState& aState, LineBreakRule aLevel,
842 bool aIsChineseOrJapanese) {
843 // Don't return CLASS_OPEN/CLASS_CLOSE if aState.UseJISX4051 is FALSE.
845 if (IS_HYPHEN(cur)) {
846 // If next character is hyphen, we don't need to break between them.
847 if (IS_HYPHEN(next)) return CLASS_CHARACTER;
848 // If prev and next characters are numeric, it may be in Math context.
849 // So, we should not break here.
850 bool prevIsNum = IS_ASCII_DIGIT(prev);
851 bool nextIsNum = IS_ASCII_DIGIT(next);
852 if (prevIsNum && nextIsNum) return CLASS_NUMERIC;
853 // If one side is numeric and the other is a character, or if both sides are
854 // characters, the hyphen should be breakable.
855 if (!aState.UseConservativeBreaking(1)) {
856 char32_t prevOfHyphen = aState.GetPreviousNonHyphenCharacter();
857 if (prevOfHyphen && next) {
858 int8_t prevClass = GetClass(prevOfHyphen, aLevel, aIsChineseOrJapanese);
859 int8_t nextClass = GetClass(next, aLevel, aIsChineseOrJapanese);
860 bool prevIsNumOrCharOrClose =
861 prevIsNum ||
862 (prevClass == CLASS_CHARACTER &&
863 !NEED_CONTEXTUAL_ANALYSIS(prevOfHyphen)) ||
864 prevClass == CLASS_CLOSE || prevClass == CLASS_CLOSE_LIKE_CHARACTER;
865 bool nextIsNumOrCharOrOpen =
866 nextIsNum ||
867 (nextClass == CLASS_CHARACTER && !NEED_CONTEXTUAL_ANALYSIS(next)) ||
868 nextClass == CLASS_OPEN || nextClass == CLASS_OPEN_LIKE_CHARACTER ||
869 next == U_OPEN_SINGLE_QUOTE || next == U_OPEN_DOUBLE_QUOTE ||
870 next == U_OPEN_GUILLEMET;
871 if (prevIsNumOrCharOrClose && nextIsNumOrCharOrOpen) {
872 return CLASS_CLOSE;
876 } else {
877 aState.NotifyNonHyphenCharacter(cur);
878 if (cur == U_SLASH || cur == U_BACKSLASH) {
879 // If this is immediately after same char, we should not break here.
880 if (prev == cur) return CLASS_CHARACTER;
881 // If this text has two or more (BACK)SLASHs, this may be file path or
882 // URL. Make sure to compute shouldReturn before we notify on this slash.
883 bool shouldReturn = !aState.UseConservativeBreaking() &&
884 (cur == U_SLASH ? aState.HasPreviousSlash()
885 : aState.HasPreviousBackslash());
887 if (cur == U_SLASH) {
888 aState.NotifySeenSlash();
889 } else {
890 aState.NotifySeenBackslash();
893 if (shouldReturn) return CLASS_OPEN;
894 } else if (cur == U_PERCENT) {
895 // If this is a part of the param of URL, we should break before.
896 if (!aState.UseConservativeBreaking()) {
897 if (aState.Index() >= 3 &&
898 aState.GetCodeUnitAt(aState.Index() - 3) == U_PERCENT)
899 return CLASS_OPEN;
900 if (aState.Index() + 3 < aState.Length() &&
901 aState.GetCodeUnitAt(aState.Index() + 3) == U_PERCENT)
902 return CLASS_OPEN;
904 } else if (cur == U_AMPERSAND || cur == U_SEMICOLON) {
905 // If this may be a separator of params of URL, we should break after.
906 if (!aState.UseConservativeBreaking(1) && aState.HasPreviousEqualsSign())
907 return CLASS_CLOSE;
908 } else if (cur == U_OPEN_SINGLE_QUOTE || cur == U_OPEN_DOUBLE_QUOTE ||
909 cur == U_OPEN_GUILLEMET) {
910 // for CJK usage, we treat these as openers to allow a break before them,
911 // but otherwise treat them as normal characters because quote mark usage
912 // in various Western languages varies too much; see bug #450088
913 // discussion.
914 if (!aState.UseConservativeBreaking() && IS_CJK_CHAR(next))
915 return CLASS_OPEN;
916 } else {
917 NS_ERROR("Forgot to handle the current character!");
920 return GetClass(cur, aLevel, aIsChineseOrJapanese);
923 int32_t LineBreaker::Next(const char16_t* aText, uint32_t aLen, uint32_t aPos) {
924 MOZ_ASSERT(aText);
926 if (aPos >= aLen) {
927 return NS_LINEBREAKER_NEED_MORE_TEXT;
930 bool textNeedsComplexLineBreak = false;
931 int32_t begin, end;
933 for (begin = aPos; begin > 0 && !NS_IsSpace(aText[begin - 1]); --begin) {
934 if (IS_CJK_CHAR(aText[begin]) ||
935 NS_NeedsPlatformNativeHandling(aText[begin])) {
936 textNeedsComplexLineBreak = true;
939 for (end = aPos + 1; end < int32_t(aLen) && !NS_IsSpace(aText[end]); ++end) {
940 if (IS_CJK_CHAR(aText[end]) || NS_NeedsPlatformNativeHandling(aText[end])) {
941 textNeedsComplexLineBreak = true;
945 int32_t ret;
946 if (!textNeedsComplexLineBreak) {
947 // No complex text character, do not try to do complex line break.
948 // (This is required for serializers. See Bug #344816.)
949 ret = end;
950 } else {
951 AutoTArray<uint8_t, 2000> breakState;
952 // XXX(Bug 1631371) Check if this should use a fallible operation as it
953 // pretended earlier.
954 breakState.AppendElements(end - begin);
955 ComputeBreakPositions(aText + begin, end - begin, WordBreakRule::Normal,
956 LineBreakRule::Auto, false, breakState.Elements());
958 ret = aPos;
959 do {
960 ++ret;
961 } while (begin < ret && ret < end && !breakState[ret - begin]);
964 return ret;
967 static bool SuppressBreakForKeepAll(uint32_t aPrev, uint32_t aCh) {
968 auto affectedByKeepAll = [](uint8_t aLBClass) {
969 switch (aLBClass) {
970 // Per https://drafts.csswg.org/css-text-3/#valdef-word-break-keep-all:
971 // "implicit soft wrap opportunities between typographic letter units
972 // (or other typographic character units belonging to the NU, AL, AI,
973 // or ID Unicode line breaking classes [UAX14]) are suppressed..."
974 case U_LB_ALPHABETIC:
975 case U_LB_AMBIGUOUS:
976 case U_LB_NUMERIC:
977 case U_LB_IDEOGRAPHIC:
978 // Additional classes that should be treated similarly, but have been
979 // broken out as separate classes in newer Unicode versions:
980 case U_LB_H2:
981 case U_LB_H3:
982 case U_LB_JL:
983 case U_LB_JV:
984 case U_LB_JT:
985 case U_LB_CONDITIONAL_JAPANESE_STARTER:
986 return true;
987 default:
988 return false;
991 return affectedByKeepAll(GetLineBreakClass(aPrev)) &&
992 affectedByKeepAll(GetLineBreakClass(aCh));
995 #if defined(MOZ_ICU4X) && defined(JS_HAS_INTL_API)
996 static capi::ICU4XLineBreakStrictness ConvertLineBreakRuleToICU4X(
997 LineBreakRule aLevel) {
998 switch (aLevel) {
999 case LineBreakRule::Auto:
1000 return capi::ICU4XLineBreakStrictness_Strict;
1001 case LineBreakRule::Strict:
1002 return capi::ICU4XLineBreakStrictness_Strict;
1003 case LineBreakRule::Loose:
1004 return capi::ICU4XLineBreakStrictness_Loose;
1005 case LineBreakRule::Normal:
1006 return capi::ICU4XLineBreakStrictness_Normal;
1007 case LineBreakRule::Anywhere:
1008 return capi::ICU4XLineBreakStrictness_Anywhere;
1010 MOZ_ASSERT_UNREACHABLE("should have been handled already");
1011 return capi::ICU4XLineBreakStrictness_Normal;
1014 static capi::ICU4XLineBreakWordOption ConvertWordBreakRuleToICU4X(
1015 WordBreakRule aWordBreak) {
1016 switch (aWordBreak) {
1017 case WordBreakRule::Normal:
1018 return capi::ICU4XLineBreakWordOption_Normal;
1019 case WordBreakRule::BreakAll:
1020 return capi::ICU4XLineBreakWordOption_BreakAll;
1021 case WordBreakRule::KeepAll:
1022 return capi::ICU4XLineBreakWordOption_KeepAll;
1024 MOZ_ASSERT_UNREACHABLE("should have been handled already");
1025 return capi::ICU4XLineBreakWordOption_Normal;
1028 static capi::ICU4XLineSegmenter* sLineSegmenter = nullptr;
1030 static capi::ICU4XLineSegmenter* GetDefaultLineSegmenter() {
1031 static std::once_flag sOnce;
1033 std::call_once(sOnce, [] {
1034 auto result = capi::ICU4XLineSegmenter_create_auto(GetDataProvider());
1035 MOZ_ASSERT(result.is_ok);
1036 sLineSegmenter = result.ok;
1038 if (NS_IsMainThread()) {
1039 mozilla::RunOnShutdown([] {
1040 if (sLineSegmenter) {
1041 capi::ICU4XLineSegmenter_destroy(sLineSegmenter);
1043 sLineSegmenter = nullptr;
1045 return;
1047 NS_DispatchToMainThread(
1048 NS_NewRunnableFunction("GetDefaultLineSegmenter", [] {
1049 mozilla::RunOnShutdown([] {
1050 if (sLineSegmenter) {
1051 capi::ICU4XLineSegmenter_destroy(sLineSegmenter);
1053 sLineSegmenter = nullptr;
1055 }));
1058 return sLineSegmenter;
1061 static bool UseDefaultLineSegmenter(WordBreakRule aWordBreak,
1062 LineBreakRule aLevel,
1063 bool aIsChineseOrJapanese) {
1064 return aWordBreak == WordBreakRule::Normal &&
1065 (aLevel == LineBreakRule::Strict || aLevel == LineBreakRule::Auto) &&
1066 !aIsChineseOrJapanese;
1069 static capi::ICU4XLineSegmenter* GetLineSegmenter(bool aUseDefault,
1070 WordBreakRule aWordBreak,
1071 LineBreakRule aLevel,
1072 bool aIsChineseOrJapanese) {
1073 if (aUseDefault) {
1074 MOZ_ASSERT(
1075 UseDefaultLineSegmenter(aWordBreak, aLevel, aIsChineseOrJapanese));
1076 return GetDefaultLineSegmenter();
1079 capi::ICU4XLineBreakOptionsV1 options;
1080 options.word_option = ConvertWordBreakRuleToICU4X(aWordBreak);
1081 options.strictness = ConvertLineBreakRuleToICU4X(aLevel);
1082 options.ja_zh = aIsChineseOrJapanese;
1084 auto result = capi::ICU4XLineSegmenter_create_lstm_with_options_v1(
1085 GetDataProvider(), options);
1086 MOZ_ASSERT(result.is_ok);
1087 return result.ok;
1089 #endif
1091 void LineBreaker::ComputeBreakPositions(
1092 const char16_t* aChars, uint32_t aLength, WordBreakRule aWordBreak,
1093 LineBreakRule aLevel, bool aIsChineseOrJapanese, uint8_t* aBreakBefore) {
1094 #if defined(MOZ_ICU4X) && defined(JS_HAS_INTL_API)
1095 if (StaticPrefs::intl_icu4x_segmenter_enabled()) {
1096 if (aLength == 1) {
1097 // Although UAX#14 LB2 rule requires never breaking at the start of text
1098 // (SOT), ICU4X line segmenter API is designed to match other segmenter in
1099 // UAX#29 to always break at the start of text. Hence the optimization
1100 // here to avoid calling into ICU4X line segmenter.
1101 aBreakBefore[0] = 1;
1102 return;
1105 memset(aBreakBefore, 0, aLength);
1107 CheckedInt<int32_t> length = aLength;
1108 if (!length.isValid()) {
1109 return;
1112 const bool useDefault =
1113 UseDefaultLineSegmenter(aWordBreak, aLevel, aIsChineseOrJapanese);
1114 capi::ICU4XLineSegmenter* lineSegmenter =
1115 GetLineSegmenter(useDefault, aWordBreak, aLevel, aIsChineseOrJapanese);
1116 ICU4XLineBreakIteratorUtf16 iterator(capi::ICU4XLineSegmenter_segment_utf16(
1117 lineSegmenter, (const uint16_t*)aChars, aLength));
1119 while (true) {
1120 const int32_t nextPos = iterator.next();
1121 if (nextPos < 0 || nextPos >= length.value()) {
1122 break;
1124 aBreakBefore[nextPos] = 1;
1127 if (!useDefault) {
1128 capi::ICU4XLineSegmenter_destroy(lineSegmenter);
1130 return;
1132 #endif
1134 uint32_t cur;
1135 int8_t lastClass = CLASS_NONE;
1136 ContextState state(aChars, aLength);
1138 for (cur = 0; cur < aLength; ++cur, state.AdvanceIndex()) {
1139 char32_t ch = state.GetUnicodeCharAt(cur);
1140 uint32_t chLen = ch > 0xFFFFu ? 2 : 1;
1141 int8_t cl;
1143 auto prev = [=]() -> char32_t {
1144 if (!cur) {
1145 return 0;
1147 char32_t c = aChars[cur - 1];
1148 if (cur > 1 && NS_IS_SURROGATE_PAIR(aChars[cur - 2], c)) {
1149 c = SURROGATE_TO_UCS4(aChars[cur - 2], c);
1151 return c;
1154 if (NEED_CONTEXTUAL_ANALYSIS(ch)) {
1155 char32_t next;
1156 if (cur + chLen < aLength) {
1157 next = state.GetUnicodeCharAt(cur + chLen);
1158 } else {
1159 next = 0;
1161 cl = ContextualAnalysis(prev(), ch, next, state, aLevel,
1162 aIsChineseOrJapanese);
1163 } else {
1164 if (ch == U_EQUAL) state.NotifySeenEqualsSign();
1165 state.NotifyNonHyphenCharacter(ch);
1166 cl = GetClass(ch, aLevel, aIsChineseOrJapanese);
1169 // To implement word-break:break-all, we overwrite the line-break class of
1170 // alphanumeric characters so they are treated the same as ideographic.
1171 // The relevant characters will have been assigned CLASS_CHARACTER, _CLOSE,
1172 // _CLOSE_LIKE_CHARACTER, or _NUMERIC by GetClass(), but those classes also
1173 // include others that we don't want to touch here, so we re-check the
1174 // Unicode line-break class to determine which ones to modify.
1175 if (aWordBreak == WordBreakRule::BreakAll &&
1176 (cl == CLASS_CHARACTER || cl == CLASS_CLOSE ||
1177 cl == CLASS_CLOSE_LIKE_CHARACTER || cl == CLASS_NUMERIC)) {
1178 auto cls = GetLineBreakClass(ch);
1179 if (cls == U_LB_ALPHABETIC || cls == U_LB_NUMERIC ||
1180 cls == U_LB_AMBIGUOUS || cls == U_LB_COMPLEX_CONTEXT ||
1181 /* Additional Japanese and Korean LB classes; CSS Text spec doesn't
1182 explicitly mention these, but this appears to give expected
1183 behavior (spec issue?) */
1184 cls == U_LB_CONDITIONAL_JAPANESE_STARTER ||
1185 (cls >= U_LB_H2 && cls <= U_LB_JV)) {
1186 cl = CLASS_BREAKABLE;
1190 bool allowBreak = false;
1191 if (cur > 0) {
1192 NS_ASSERTION(CLASS_COMPLEX != lastClass || CLASS_COMPLEX != cl,
1193 "Loop should have prevented adjacent complex chars here");
1194 allowBreak =
1195 (state.UseConservativeBreaking() ? GetPairConservative(lastClass, cl)
1196 : GetPair(lastClass, cl));
1197 // Special cases where a normally-allowed break is suppressed:
1198 if (allowBreak) {
1199 // word-break:keep-all suppresses breaks between certain line-break
1200 // classes.
1201 if (aWordBreak == WordBreakRule::KeepAll &&
1202 SuppressBreakForKeepAll(prev(), ch)) {
1203 allowBreak = false;
1205 // We also don't allow a break within a run of U+3000 chars unless
1206 // word-break:break-all is in effect.
1207 if (ch == 0x3000 && prev() == 0x3000 &&
1208 aWordBreak != WordBreakRule::BreakAll) {
1209 allowBreak = false;
1213 aBreakBefore[cur] = allowBreak;
1214 if (allowBreak) state.NotifyBreakBefore();
1215 lastClass = cl;
1216 if (CLASS_COMPLEX == cl) {
1217 uint32_t end = cur + chLen;
1219 while (end < aLength) {
1220 char32_t c = state.GetUnicodeCharAt(end);
1221 if (CLASS_COMPLEX != GetClass(c, aLevel, false)) {
1222 break;
1224 ++end;
1225 if (c > 0xFFFFU) { // it was a surrogate pair
1226 ++end;
1230 if (aWordBreak == WordBreakRule::BreakAll) {
1231 // For break-all, we don't need to run a dictionary-based breaking
1232 // algorithm, we just allow breaks between all grapheme clusters.
1233 GraphemeClusterBreakIteratorUtf16 ci(
1234 Span<const char16_t>(aChars + cur, end - cur));
1235 while (Maybe<uint32_t> pos = ci.Next()) {
1236 aBreakBefore[cur + *pos] = true;
1238 } else {
1239 ComplexBreaker::GetBreaks(aChars + cur, end - cur, aBreakBefore + cur);
1240 // restore breakability at chunk begin, which was always set to false
1241 // by the complex line breaker
1242 aBreakBefore[cur] = allowBreak;
1245 cur = end - 1;
1248 if (chLen == 2) {
1249 // Supplementary-plane character: mark that we cannot break before the
1250 // trailing low surrogate, and advance past it.
1251 ++cur;
1252 aBreakBefore[cur] = false;
1253 state.AdvanceIndex();
1258 void LineBreaker::ComputeBreakPositions(const uint8_t* aChars, uint32_t aLength,
1259 WordBreakRule aWordBreak,
1260 LineBreakRule aLevel,
1261 bool aIsChineseOrJapanese,
1262 uint8_t* aBreakBefore) {
1263 #if defined(MOZ_ICU4X) && defined(JS_HAS_INTL_API)
1264 if (StaticPrefs::intl_icu4x_segmenter_enabled()) {
1265 if (aLength == 1) {
1266 // Although UAX#14 LB2 rule requires never breaking at the start of text
1267 // (SOT), ICU4X line segmenter API is designed to match other segmenter in
1268 // UAX#29 to always break at the start of text. Hence the optimization
1269 // here to avoid calling into ICU4X line segmenter.
1270 aBreakBefore[0] = 1;
1271 return;
1274 memset(aBreakBefore, 0, aLength);
1276 CheckedInt<int32_t> length = aLength;
1277 if (!length.isValid()) {
1278 return;
1281 const bool useDefault =
1282 UseDefaultLineSegmenter(aWordBreak, aLevel, aIsChineseOrJapanese);
1283 capi::ICU4XLineSegmenter* lineSegmenter =
1284 GetLineSegmenter(useDefault, aWordBreak, aLevel, aIsChineseOrJapanese);
1285 ICU4XLineBreakIteratorLatin1 iterator(
1286 capi::ICU4XLineSegmenter_segment_latin1(
1287 lineSegmenter, (const uint8_t*)aChars, aLength));
1289 while (true) {
1290 const int32_t nextPos = iterator.next();
1291 if (nextPos < 0 || nextPos >= length.value()) {
1292 break;
1294 aBreakBefore[nextPos] = 1;
1297 if (!useDefault) {
1298 capi::ICU4XLineSegmenter_destroy(lineSegmenter);
1300 return;
1302 #endif
1304 uint32_t cur;
1305 int8_t lastClass = CLASS_NONE;
1306 ContextState state(aChars, aLength);
1308 for (cur = 0; cur < aLength; ++cur, state.AdvanceIndex()) {
1309 char32_t ch = aChars[cur];
1310 int8_t cl;
1312 if (NEED_CONTEXTUAL_ANALYSIS(ch)) {
1313 cl = ContextualAnalysis(cur > 0 ? aChars[cur - 1] : U_NULL, ch,
1314 cur + 1 < aLength ? aChars[cur + 1] : U_NULL,
1315 state, aLevel, aIsChineseOrJapanese);
1316 } else {
1317 if (ch == U_EQUAL) state.NotifySeenEqualsSign();
1318 state.NotifyNonHyphenCharacter(ch);
1319 cl = GetClass(ch, aLevel, aIsChineseOrJapanese);
1321 if (aWordBreak == WordBreakRule::BreakAll &&
1322 (cl == CLASS_CHARACTER || cl == CLASS_CLOSE ||
1323 cl == CLASS_CLOSE_LIKE_CHARACTER || cl == CLASS_NUMERIC)) {
1324 auto cls = GetLineBreakClass(ch);
1325 // Don't need to check additional Japanese/Korean classes in 8-bit
1326 if (cls == U_LB_ALPHABETIC || cls == U_LB_NUMERIC ||
1327 cls == U_LB_COMPLEX_CONTEXT) {
1328 cl = CLASS_BREAKABLE;
1332 bool allowBreak = false;
1333 if (cur > 0) {
1334 allowBreak =
1335 (state.UseConservativeBreaking() ? GetPairConservative(lastClass, cl)
1336 : GetPair(lastClass, cl)) &&
1337 (aWordBreak != WordBreakRule::KeepAll ||
1338 !SuppressBreakForKeepAll(aChars[cur - 1], ch));
1340 aBreakBefore[cur] = allowBreak;
1341 if (allowBreak) state.NotifyBreakBefore();
1342 lastClass = cl;