1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.text;
18
19import android.annotation.Nullable;
20import android.view.View;
21
22import static android.text.TextDirectionHeuristics.FIRSTSTRONG_LTR;
23
24import java.util.Locale;
25
26/**
27 * Utility class for formatting text for display in a potentially opposite-directionality context
28 * without garbling. The directionality of the context is set at formatter creation and the
29 * directionality of the text can be either estimated or passed in when known.
30 *
31 * <p>To support versions lower than {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR2},
32 * you can use the support library's {@link android.support.v4.text.BidiFormatter} class.
33 *
34 * <p>These APIs provides the following functionality:
35 * <p>
36 * 1. Bidi Wrapping
37 * When text in one language is mixed into a document in another, opposite-directionality language,
38 * e.g. when an English business name is embedded in some Hebrew text, both the inserted string
39 * and the text surrounding it may be displayed incorrectly unless the inserted string is explicitly
40 * separated from the surrounding text in a "wrapper" that:
41 * <p>
42 * - Declares its directionality so that the string is displayed correctly. This can be done in
43 *   Unicode bidi formatting codes by {@link #unicodeWrap} and similar methods.
44 * <p>
45 * - Isolates the string's directionality, so it does not unduly affect the surrounding content.
46 *   Currently, this can only be done using invisible Unicode characters of the same direction as
47 *   the context (LRM or RLM) in addition to the directionality declaration above, thus "resetting"
48 *   the directionality to that of the context. The "reset" may need to be done at both ends of the
49 *   string. Without "reset" after the string, the string will "stick" to a number or logically
50 *   separate opposite-direction text that happens to follow it in-line (even if separated by
51 *   neutral content like spaces and punctuation). Without "reset" before the string, the same can
52 *   happen there, but only with more opposite-direction text, not a number. One approach is to
53 *   "reset" the direction only after each string, on the theory that if the preceding opposite-
54 *   direction text is itself bidi-wrapped, the "reset" after it will prevent the sticking. (Doing
55 *   the "reset" only before each string definitely does not work because we do not want to require
56 *   bidi-wrapping numbers, and a bidi-wrapped opposite-direction string could be followed by a
57 *   number.) Still, the safest policy is to do the "reset" on both ends of each string, since RTL
58 *   message translations often contain untranslated Latin-script brand names and technical terms,
59 *   and one of these can be followed by a bidi-wrapped inserted value. On the other hand, when one
60 *   has such a message, it is best to do the "reset" manually in the message translation itself,
61 *   since the message's opposite-direction text could be followed by an inserted number, which we
62 *   would not bidi-wrap anyway. Thus, "reset" only after the string is the current default. In an
63 *   alternative to "reset", recent additions to the HTML, CSS, and Unicode standards allow the
64 *   isolation to be part of the directionality declaration. This form of isolation is better than
65 *   "reset" because it takes less space, does not require knowing the context directionality, has a
66 *   gentler effect than "reset", and protects both ends of the string. However, we do not yet allow
67 *   using it because required platforms do not yet support it.
68 * <p>
69 * Providing these wrapping services is the basic purpose of the bidi formatter.
70 * <p>
71 * 2. Directionality estimation
72 * How does one know whether a string about to be inserted into surrounding text has the same
73 * directionality? Well, in many cases, one knows that this must be the case when writing the code
74 * doing the insertion, e.g. when a localized message is inserted into a localized page. In such
75 * cases there is no need to involve the bidi formatter at all. In some other cases, it need not be
76 * the same as the context, but is either constant (e.g. urls are always LTR) or otherwise known.
77 * In the remaining cases, e.g. when the string is user-entered or comes from a database, the
78 * language of the string (and thus its directionality) is not known a priori, and must be
79 * estimated at run-time. The bidi formatter can do this automatically using the default
80 * first-strong estimation algorithm. It can also be configured to use a custom directionality
81 * estimation object.
82 */
83public final class BidiFormatter {
84
85    /**
86     * The default text direction heuristic.
87     */
88    private static TextDirectionHeuristic DEFAULT_TEXT_DIRECTION_HEURISTIC = FIRSTSTRONG_LTR;
89
90    /**
91     * Unicode "Left-To-Right Embedding" (LRE) character.
92     */
93    private static final char LRE = '\u202A';
94
95    /**
96     * Unicode "Right-To-Left Embedding" (RLE) character.
97     */
98    private static final char RLE = '\u202B';
99
100    /**
101     * Unicode "Pop Directional Formatting" (PDF) character.
102     */
103    private static final char PDF = '\u202C';
104
105    /**
106     *  Unicode "Left-To-Right Mark" (LRM) character.
107     */
108    private static final char LRM = '\u200E';
109
110    /*
111     * Unicode "Right-To-Left Mark" (RLM) character.
112     */
113    private static final char RLM = '\u200F';
114
115    /*
116     * String representation of LRM
117     */
118    private static final String LRM_STRING = Character.toString(LRM);
119
120    /*
121     * String representation of RLM
122     */
123    private static final String RLM_STRING = Character.toString(RLM);
124
125    /**
126     * Empty string constant.
127     */
128    private static final String EMPTY_STRING = "";
129
130    /**
131     * A class for building a BidiFormatter with non-default options.
132     */
133    public static final class Builder {
134        private boolean mIsRtlContext;
135        private int mFlags;
136        private TextDirectionHeuristic mTextDirectionHeuristic;
137
138        /**
139         * Constructor.
140         *
141         */
142        public Builder() {
143            initialize(isRtlLocale(Locale.getDefault()));
144        }
145
146        /**
147         * Constructor.
148         *
149         * @param rtlContext Whether the context directionality is RTL.
150         */
151        public Builder(boolean rtlContext) {
152            initialize(rtlContext);
153        }
154
155        /**
156         * Constructor.
157         *
158         * @param locale The context locale.
159         */
160        public Builder(Locale locale) {
161            initialize(isRtlLocale(locale));
162        }
163
164        /**
165         * Initializes the builder with the given context directionality and default options.
166         *
167         * @param isRtlContext Whether the context is RTL or not.
168         */
169        private void initialize(boolean isRtlContext) {
170            mIsRtlContext = isRtlContext;
171            mTextDirectionHeuristic = DEFAULT_TEXT_DIRECTION_HEURISTIC;
172            mFlags = DEFAULT_FLAGS;
173        }
174
175        /**
176         * Specifies whether the BidiFormatter to be built should also "reset" directionality before
177         * a string being bidi-wrapped, not just after it. The default is true.
178         */
179        public Builder stereoReset(boolean stereoReset) {
180            if (stereoReset) {
181                mFlags |= FLAG_STEREO_RESET;
182            } else {
183                mFlags &= ~FLAG_STEREO_RESET;
184            }
185            return this;
186        }
187
188        /**
189         * Specifies the default directionality estimation algorithm to be used by the BidiFormatter.
190         * By default, uses the first-strong heuristic.
191         *
192         * @param heuristic the {@code TextDirectionHeuristic} to use.
193         * @return the builder itself.
194         */
195        public Builder setTextDirectionHeuristic(TextDirectionHeuristic heuristic) {
196            mTextDirectionHeuristic = heuristic;
197            return this;
198        }
199
200        /**
201         * @return A BidiFormatter with the specified options.
202         */
203        public BidiFormatter build() {
204            if (mFlags == DEFAULT_FLAGS &&
205                    mTextDirectionHeuristic == DEFAULT_TEXT_DIRECTION_HEURISTIC) {
206                return BidiFormatter.getDefaultInstanceFromContext(mIsRtlContext);
207            }
208            return new BidiFormatter(mIsRtlContext, mFlags, mTextDirectionHeuristic);
209        }
210    }
211
212    //
213    private static final int FLAG_STEREO_RESET = 2;
214    private static final int DEFAULT_FLAGS = FLAG_STEREO_RESET;
215
216    private static final BidiFormatter DEFAULT_LTR_INSTANCE = new BidiFormatter(
217            false /* LTR context */,
218            DEFAULT_FLAGS,
219            DEFAULT_TEXT_DIRECTION_HEURISTIC);
220
221    private static final BidiFormatter DEFAULT_RTL_INSTANCE = new BidiFormatter(
222            true /* RTL context */,
223            DEFAULT_FLAGS,
224            DEFAULT_TEXT_DIRECTION_HEURISTIC);
225
226    private final boolean mIsRtlContext;
227    private final int mFlags;
228    private final TextDirectionHeuristic mDefaultTextDirectionHeuristic;
229
230    /**
231     * Factory for creating an instance of BidiFormatter for the default locale directionality.
232     *
233     * This does not create any new objects, and returns already existing static instances.
234     *
235     */
236    public static BidiFormatter getInstance() {
237        return getDefaultInstanceFromContext(isRtlLocale(Locale.getDefault()));
238    }
239
240    /**
241     * Factory for creating an instance of BidiFormatter given the context directionality.
242     *
243     * This does not create any new objects, and returns already existing static instances.
244     *
245     * @param rtlContext Whether the context directionality is RTL.
246     */
247    public static BidiFormatter getInstance(boolean rtlContext) {
248        return getDefaultInstanceFromContext(rtlContext);
249    }
250
251    /**
252     * Factory for creating an instance of BidiFormatter given the context locale.
253     *
254     * This does not create any new objects, and returns already existing static instances.
255     *
256     * @param locale The context locale.
257     */
258    public static BidiFormatter getInstance(Locale locale) {
259        return getDefaultInstanceFromContext(isRtlLocale(locale));
260    }
261
262    /**
263     * @param isRtlContext Whether the context directionality is RTL or not.
264     * @param flags The option flags.
265     * @param heuristic The default text direction heuristic.
266     */
267    private BidiFormatter(boolean isRtlContext, int flags, TextDirectionHeuristic heuristic) {
268        mIsRtlContext = isRtlContext;
269        mFlags = flags;
270        mDefaultTextDirectionHeuristic = heuristic;
271    }
272
273    /**
274     * @return Whether the context directionality is RTL
275     */
276    public boolean isRtlContext() {
277        return mIsRtlContext;
278    }
279
280    /**
281     * @return Whether directionality "reset" should also be done before a string being
282     * bidi-wrapped, not just after it.
283     */
284    public boolean getStereoReset() {
285        return (mFlags & FLAG_STEREO_RESET) != 0;
286    }
287
288    /**
289     * Returns a Unicode bidi mark matching the context directionality (LRM or RLM) if either the
290     * overall or the exit directionality of a given string is opposite to the context directionality.
291     * Putting this after the string (including its directionality declaration wrapping) prevents it
292     * from "sticking" to other opposite-directionality text or a number appearing after it inline
293     * with only neutral content in between. Otherwise returns the empty string. While the exit
294     * directionality is determined by scanning the end of the string, the overall directionality is
295     * given explicitly by a heuristic to estimate the {@code str}'s directionality.
296     *
297     * @param str CharSequence after which the mark may need to appear.
298     * @param heuristic The text direction heuristic that will be used to estimate the {@code str}'s
299     *                  directionality.
300     * @return LRM for RTL text in LTR context; RLM for LTR text in RTL context;
301     *     else, the empty string.
302     *
303     * @hide
304     */
305    public String markAfter(CharSequence str, TextDirectionHeuristic heuristic) {
306        final boolean isRtl = heuristic.isRtl(str, 0, str.length());
307        // getExitDir() is called only if needed (short-circuit).
308        if (!mIsRtlContext && (isRtl || getExitDir(str) == DIR_RTL)) {
309            return LRM_STRING;
310        }
311        if (mIsRtlContext && (!isRtl || getExitDir(str) == DIR_LTR)) {
312            return RLM_STRING;
313        }
314        return EMPTY_STRING;
315    }
316
317    /**
318     * Returns a Unicode bidi mark matching the context directionality (LRM or RLM) if either the
319     * overall or the entry directionality of a given string is opposite to the context
320     * directionality. Putting this before the string (including its directionality declaration
321     * wrapping) prevents it from "sticking" to other opposite-directionality text appearing before
322     * it inline with only neutral content in between. Otherwise returns the empty string. While the
323     * entry directionality is determined by scanning the beginning of the string, the overall
324     * directionality is given explicitly by a heuristic to estimate the {@code str}'s directionality.
325     *
326     * @param str CharSequence before which the mark may need to appear.
327     * @param heuristic The text direction heuristic that will be used to estimate the {@code str}'s
328     *                  directionality.
329     * @return LRM for RTL text in LTR context; RLM for LTR text in RTL context;
330     *     else, the empty string.
331     *
332     * @hide
333     */
334    public String markBefore(CharSequence str, TextDirectionHeuristic heuristic) {
335        final boolean isRtl = heuristic.isRtl(str, 0, str.length());
336        // getEntryDir() is called only if needed (short-circuit).
337        if (!mIsRtlContext && (isRtl || getEntryDir(str) == DIR_RTL)) {
338            return LRM_STRING;
339        }
340        if (mIsRtlContext && (!isRtl || getEntryDir(str) == DIR_LTR)) {
341            return RLM_STRING;
342        }
343        return EMPTY_STRING;
344    }
345
346    /**
347     * Estimates the directionality of a string using the default text direction heuristic.
348     *
349     * @param str String whose directionality is to be estimated.
350     * @return true if {@code str}'s estimated overall directionality is RTL. Otherwise returns
351     *          false.
352     */
353    public boolean isRtl(String str) {
354        return isRtl((CharSequence) str);
355    }
356
357    /**
358     * @hide
359     */
360    public boolean isRtl(CharSequence str) {
361        return mDefaultTextDirectionHeuristic.isRtl(str, 0, str.length());
362    }
363
364    /**
365     * Formats a string of given directionality for use in plain-text output of the context
366     * directionality, so an opposite-directionality string is neither garbled nor garbles its
367     * surroundings. This makes use of Unicode bidi formatting characters.
368     * <p>
369     * The algorithm: In case the given directionality doesn't match the context directionality, wraps
370     * the string with Unicode bidi formatting characters: RLE+{@code str}+PDF for RTL text, or
371     * LRE+{@code str}+PDF for LTR text.
372     * <p>
373     * If {@code isolate}, directionally isolates the string so that it does not garble its
374     * surroundings. Currently, this is done by "resetting" the directionality after the string by
375     * appending a trailing Unicode bidi mark matching the context directionality (LRM or RLM) when
376     * either the overall directionality or the exit directionality of the string is opposite to
377     * that of the context. Unless the formatter was built using
378     * {@link Builder#stereoReset(boolean)} with a {@code false} argument, also prepends a Unicode
379     * bidi mark matching the context directionality when either the overall directionality or the
380     * entry directionality of the string is opposite to that of the context. Note that as opposed
381     * to the overall directionality, the entry and exit directionalities are determined from the
382     * string itself.
383     * <p>
384     * Does *not* do HTML-escaping.
385     *
386     * @param str The input string.
387     * @param heuristic The algorithm to be used to estimate the string's overall direction.
388     *        See {@link TextDirectionHeuristics} for pre-defined heuristics.
389     * @param isolate Whether to directionally isolate the string to prevent it from garbling the
390     *     content around it
391     * @return Input string after applying the above processing. {@code null} if {@code str} is
392     *     {@code null}.
393     */
394    public @Nullable String unicodeWrap(@Nullable String str, TextDirectionHeuristic heuristic,
395            boolean isolate) {
396        if (str == null) return null;
397        return unicodeWrap((CharSequence) str, heuristic, isolate).toString();
398    }
399
400    /**
401     * @hide
402     */
403    public @Nullable CharSequence unicodeWrap(@Nullable CharSequence str,
404            TextDirectionHeuristic heuristic, boolean isolate) {
405        if (str == null) return null;
406        final boolean isRtl = heuristic.isRtl(str, 0, str.length());
407        SpannableStringBuilder result = new SpannableStringBuilder();
408        if (getStereoReset() && isolate) {
409            result.append(markBefore(str,
410                    isRtl ? TextDirectionHeuristics.RTL : TextDirectionHeuristics.LTR));
411        }
412        if (isRtl != mIsRtlContext) {
413            result.append(isRtl ? RLE : LRE);
414            result.append(str);
415            result.append(PDF);
416        } else {
417            result.append(str);
418        }
419        if (isolate) {
420            result.append(markAfter(str,
421                    isRtl ? TextDirectionHeuristics.RTL : TextDirectionHeuristics.LTR));
422        }
423        return result;
424    }
425
426    /**
427     * Operates like {@link #unicodeWrap(String, TextDirectionHeuristic, boolean)}, but assumes
428     * {@code isolate} is true.
429     *
430     * @param str The input string.
431     * @param heuristic The algorithm to be used to estimate the string's overall direction.
432     *        See {@link TextDirectionHeuristics} for pre-defined heuristics.
433     * @return Input string after applying the above processing.
434     */
435    public String unicodeWrap(String str, TextDirectionHeuristic heuristic) {
436        return unicodeWrap(str, heuristic, true /* isolate */);
437    }
438
439    /**
440     * @hide
441     */
442    public CharSequence unicodeWrap(CharSequence str, TextDirectionHeuristic heuristic) {
443        return unicodeWrap(str, heuristic, true /* isolate */);
444    }
445
446
447    /**
448     * Operates like {@link #unicodeWrap(String, TextDirectionHeuristic, boolean)}, but uses the
449     * formatter's default direction estimation algorithm.
450     *
451     * @param str The input string.
452     * @param isolate Whether to directionally isolate the string to prevent it from garbling the
453     *     content around it
454     * @return Input string after applying the above processing.
455     */
456    public String unicodeWrap(String str, boolean isolate) {
457        return unicodeWrap(str, mDefaultTextDirectionHeuristic, isolate);
458    }
459
460    /**
461     * @hide
462     */
463    public CharSequence unicodeWrap(CharSequence str, boolean isolate) {
464        return unicodeWrap(str, mDefaultTextDirectionHeuristic, isolate);
465    }
466
467    /**
468     * Operates like {@link #unicodeWrap(String, TextDirectionHeuristic, boolean)}, but uses the
469     * formatter's default direction estimation algorithm and assumes {@code isolate} is true.
470     *
471     * @param str The input string.
472     * @return Input string after applying the above processing.
473     */
474    public String unicodeWrap(String str) {
475        return unicodeWrap(str, mDefaultTextDirectionHeuristic, true /* isolate */);
476    }
477
478    /**
479     * @hide
480     */
481    public CharSequence unicodeWrap(CharSequence str) {
482        return unicodeWrap(str, mDefaultTextDirectionHeuristic, true /* isolate */);
483    }
484
485    private static BidiFormatter getDefaultInstanceFromContext(boolean isRtlContext) {
486        return isRtlContext ? DEFAULT_RTL_INSTANCE : DEFAULT_LTR_INSTANCE;
487    }
488
489    /**
490     * Helper method to return true if the Locale directionality is RTL.
491     *
492     * @param locale The Locale whose directionality will be checked to be RTL or LTR
493     * @return true if the {@code locale} directionality is RTL. False otherwise.
494     */
495    private static boolean isRtlLocale(Locale locale) {
496        return (TextUtils.getLayoutDirectionFromLocale(locale) == View.LAYOUT_DIRECTION_RTL);
497    }
498
499    /**
500     * Enum for directionality type.
501     */
502    private static final int DIR_LTR = -1;
503    private static final int DIR_UNKNOWN = 0;
504    private static final int DIR_RTL = +1;
505
506    /**
507     * Returns the directionality of the last character with strong directionality in the string, or
508     * DIR_UNKNOWN if none was encountered. For efficiency, actually scans backwards from the end of
509     * the string. Treats a non-BN character between an LRE/RLE/LRO/RLO and its matching PDF as a
510     * strong character, LTR after LRE/LRO, and RTL after RLE/RLO. The results are undefined for a
511     * string containing unbalanced LRE/RLE/LRO/RLO/PDF characters. The intended use is to check
512     * whether a logically separate item that starts with a number or a character of the string's
513     * exit directionality and follows this string inline (not counting any neutral characters in
514     * between) would "stick" to it in an opposite-directionality context, thus being displayed in
515     * an incorrect position. An LRM or RLM character (the one of the context's directionality)
516     * between the two will prevent such sticking.
517     *
518     * @param str the string to check.
519     */
520    private static int getExitDir(CharSequence str) {
521        return new DirectionalityEstimator(str, false /* isHtml */).getExitDir();
522    }
523
524    /**
525     * Returns the directionality of the first character with strong directionality in the string,
526     * or DIR_UNKNOWN if none was encountered. Treats a non-BN character between an
527     * LRE/RLE/LRO/RLO and its matching PDF as a strong character, LTR after LRE/LRO, and RTL after
528     * RLE/RLO. The results are undefined for a string containing unbalanced LRE/RLE/LRO/RLO/PDF
529     * characters. The intended use is to check whether a logically separate item that ends with a
530     * character of the string's entry directionality and precedes the string inline (not counting
531     * any neutral characters in between) would "stick" to it in an opposite-directionality context,
532     * thus being displayed in an incorrect position. An LRM or RLM character (the one of the
533     * context's directionality) between the two will prevent such sticking.
534     *
535     * @param str the string to check.
536     */
537    private static int getEntryDir(CharSequence str) {
538        return new DirectionalityEstimator(str, false /* isHtml */).getEntryDir();
539    }
540
541    /**
542     * An object that estimates the directionality of a given string by various methods.
543     *
544     */
545    private static class DirectionalityEstimator {
546
547        // Internal static variables and constants.
548
549        /**
550         * Size of the bidi character class cache. The results of the Character.getDirectionality()
551         * calls on the lowest DIR_TYPE_CACHE_SIZE codepoints are kept in an array for speed.
552         * The 0x700 value is designed to leave all the European and Near Eastern languages in the
553         * cache. It can be reduced to 0x180, restricting the cache to the Western European
554         * languages.
555         */
556        private static final int DIR_TYPE_CACHE_SIZE = 0x700;
557
558        /**
559         * The bidi character class cache.
560         */
561        private static final byte DIR_TYPE_CACHE[];
562
563        static {
564            DIR_TYPE_CACHE = new byte[DIR_TYPE_CACHE_SIZE];
565            for (int i = 0; i < DIR_TYPE_CACHE_SIZE; i++) {
566                DIR_TYPE_CACHE[i] = Character.getDirectionality(i);
567            }
568        }
569
570        // Internal instance variables.
571
572        /**
573         * The text to be scanned.
574         */
575        private final CharSequence text;
576
577        /**
578         * Whether the text to be scanned is to be treated as HTML, i.e. skipping over tags and
579         * entities when looking for the next / preceding dir type.
580         */
581        private final boolean isHtml;
582
583        /**
584         * The length of the text in chars.
585         */
586        private final int length;
587
588        /**
589         * The current position in the text.
590         */
591        private int charIndex;
592
593        /**
594         * The char encountered by the last dirTypeForward or dirTypeBackward call. If it
595         * encountered a supplementary codepoint, this contains a char that is not a valid
596         * codepoint. This is ok, because this member is only used to detect some well-known ASCII
597         * syntax, e.g. "http://" and the beginning of an HTML tag or entity.
598         */
599        private char lastChar;
600
601        /**
602         * Constructor.
603         *
604         * @param text The string to scan.
605         * @param isHtml Whether the text to be scanned is to be treated as HTML, i.e. skipping over
606         *     tags and entities.
607         */
608        DirectionalityEstimator(CharSequence text, boolean isHtml) {
609            this.text = text;
610            this.isHtml = isHtml;
611            length = text.length();
612        }
613
614        /**
615         * Returns the directionality of the first character with strong directionality in the
616         * string, or DIR_UNKNOWN if none was encountered. Treats a non-BN character between an
617         * LRE/RLE/LRO/RLO and its matching PDF as a strong character, LTR after LRE/LRO, and RTL
618         * after RLE/RLO. The results are undefined for a string containing unbalanced
619         * LRE/RLE/LRO/RLO/PDF characters.
620         */
621        int getEntryDir() {
622            // The reason for this method name, as opposed to getFirstStrongDir(), is that
623            // "first strong" is a commonly used description of Unicode's estimation algorithm,
624            // but the two must treat formatting characters quite differently. Thus, we are staying
625            // away from both "first" and "last" in these method names to avoid confusion.
626            charIndex = 0;
627            int embeddingLevel = 0;
628            int embeddingLevelDir = DIR_UNKNOWN;
629            int firstNonEmptyEmbeddingLevel = 0;
630            while (charIndex < length && firstNonEmptyEmbeddingLevel == 0) {
631                switch (dirTypeForward()) {
632                    case Character.DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING:
633                    case Character.DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE:
634                        ++embeddingLevel;
635                        embeddingLevelDir = DIR_LTR;
636                        break;
637                    case Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING:
638                    case Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE:
639                        ++embeddingLevel;
640                        embeddingLevelDir = DIR_RTL;
641                        break;
642                    case Character.DIRECTIONALITY_POP_DIRECTIONAL_FORMAT:
643                        --embeddingLevel;
644                        // To restore embeddingLevelDir to its previous value, we would need a
645                        // stack, which we want to avoid. Thus, at this point we do not know the
646                        // current embedding's directionality.
647                        embeddingLevelDir = DIR_UNKNOWN;
648                        break;
649                    case Character.DIRECTIONALITY_BOUNDARY_NEUTRAL:
650                        break;
651                    case Character.DIRECTIONALITY_LEFT_TO_RIGHT:
652                        if (embeddingLevel == 0) {
653                            return DIR_LTR;
654                        }
655                        firstNonEmptyEmbeddingLevel = embeddingLevel;
656                        break;
657                    case Character.DIRECTIONALITY_RIGHT_TO_LEFT:
658                    case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC:
659                        if (embeddingLevel == 0) {
660                            return DIR_RTL;
661                        }
662                        firstNonEmptyEmbeddingLevel = embeddingLevel;
663                        break;
664                    default:
665                        firstNonEmptyEmbeddingLevel = embeddingLevel;
666                        break;
667                }
668            }
669
670            // We have either found a non-empty embedding or scanned the entire string finding
671            // neither a non-empty embedding nor a strong character outside of an embedding.
672            if (firstNonEmptyEmbeddingLevel == 0) {
673                // We have not found a non-empty embedding. Thus, the string contains neither a
674                // non-empty embedding nor a strong character outside of an embedding.
675                return DIR_UNKNOWN;
676            }
677
678            // We have found a non-empty embedding.
679            if (embeddingLevelDir != DIR_UNKNOWN) {
680                // We know the directionality of the non-empty embedding.
681                return embeddingLevelDir;
682            }
683
684            // We do not remember the directionality of the non-empty embedding we found. So, we go
685            // backwards to find the start of the non-empty embedding and get its directionality.
686            while (charIndex > 0) {
687                switch (dirTypeBackward()) {
688                    case Character.DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING:
689                    case Character.DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE:
690                        if (firstNonEmptyEmbeddingLevel == embeddingLevel) {
691                            return DIR_LTR;
692                        }
693                        --embeddingLevel;
694                        break;
695                    case Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING:
696                    case Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE:
697                        if (firstNonEmptyEmbeddingLevel == embeddingLevel) {
698                            return DIR_RTL;
699                        }
700                        --embeddingLevel;
701                        break;
702                    case Character.DIRECTIONALITY_POP_DIRECTIONAL_FORMAT:
703                        ++embeddingLevel;
704                        break;
705                }
706            }
707            // We should never get here.
708            return DIR_UNKNOWN;
709        }
710
711        /**
712         * Returns the directionality of the last character with strong directionality in the
713         * string, or DIR_UNKNOWN if none was encountered. For efficiency, actually scans backwards
714         * from the end of the string. Treats a non-BN character between an LRE/RLE/LRO/RLO and its
715         * matching PDF as a strong character, LTR after LRE/LRO, and RTL after RLE/RLO. The results
716         * are undefined for a string containing unbalanced LRE/RLE/LRO/RLO/PDF characters.
717         */
718        int getExitDir() {
719            // The reason for this method name, as opposed to getLastStrongDir(), is that "last
720            // strong" sounds like the exact opposite of "first strong", which is a commonly used
721            // description of Unicode's estimation algorithm (getUnicodeDir() above), but the two
722            // must treat formatting characters quite differently. Thus, we are staying away from
723            // both "first" and "last" in these method names to avoid confusion.
724            charIndex = length;
725            int embeddingLevel = 0;
726            int lastNonEmptyEmbeddingLevel = 0;
727            while (charIndex > 0) {
728                switch (dirTypeBackward()) {
729                    case Character.DIRECTIONALITY_LEFT_TO_RIGHT:
730                        if (embeddingLevel == 0) {
731                            return DIR_LTR;
732                        }
733                        if (lastNonEmptyEmbeddingLevel == 0) {
734                            lastNonEmptyEmbeddingLevel = embeddingLevel;
735                        }
736                        break;
737                    case Character.DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING:
738                    case Character.DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE:
739                        if (lastNonEmptyEmbeddingLevel == embeddingLevel) {
740                            return DIR_LTR;
741                        }
742                        --embeddingLevel;
743                        break;
744                    case Character.DIRECTIONALITY_RIGHT_TO_LEFT:
745                    case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC:
746                        if (embeddingLevel == 0) {
747                            return DIR_RTL;
748                        }
749                        if (lastNonEmptyEmbeddingLevel == 0) {
750                            lastNonEmptyEmbeddingLevel = embeddingLevel;
751                        }
752                        break;
753                    case Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING:
754                    case Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE:
755                        if (lastNonEmptyEmbeddingLevel == embeddingLevel) {
756                            return DIR_RTL;
757                        }
758                        --embeddingLevel;
759                        break;
760                    case Character.DIRECTIONALITY_POP_DIRECTIONAL_FORMAT:
761                        ++embeddingLevel;
762                        break;
763                    case Character.DIRECTIONALITY_BOUNDARY_NEUTRAL:
764                        break;
765                    default:
766                        if (lastNonEmptyEmbeddingLevel == 0) {
767                            lastNonEmptyEmbeddingLevel = embeddingLevel;
768                        }
769                        break;
770                }
771            }
772            return DIR_UNKNOWN;
773        }
774
775        // Internal methods
776
777        /**
778         * Gets the bidi character class, i.e. Character.getDirectionality(), of a given char, using
779         * a cache for speed. Not designed for supplementary codepoints, whose results we do not
780         * cache.
781         */
782        private static byte getCachedDirectionality(char c) {
783            return c < DIR_TYPE_CACHE_SIZE ? DIR_TYPE_CACHE[c] : Character.getDirectionality(c);
784        }
785
786        /**
787         * Returns the Character.DIRECTIONALITY_... value of the next codepoint and advances
788         * charIndex. If isHtml, and the codepoint is '<' or '&', advances through the tag/entity,
789         * and returns Character.DIRECTIONALITY_WHITESPACE. For an entity, it would be best to
790         * figure out the actual character, and return its dirtype, but treating it as whitespace is
791         * good enough for our purposes.
792         *
793         * @throws java.lang.IndexOutOfBoundsException if called when charIndex >= length or < 0.
794         */
795        byte dirTypeForward() {
796            lastChar = text.charAt(charIndex);
797            if (Character.isHighSurrogate(lastChar)) {
798                int codePoint = Character.codePointAt(text, charIndex);
799                charIndex += Character.charCount(codePoint);
800                return Character.getDirectionality(codePoint);
801            }
802            charIndex++;
803            byte dirType = getCachedDirectionality(lastChar);
804            if (isHtml) {
805                // Process tags and entities.
806                if (lastChar == '<') {
807                    dirType = skipTagForward();
808                } else if (lastChar == '&') {
809                    dirType = skipEntityForward();
810                }
811            }
812            return dirType;
813        }
814
815        /**
816         * Returns the Character.DIRECTIONALITY_... value of the preceding codepoint and advances
817         * charIndex backwards. If isHtml, and the codepoint is the end of a complete HTML tag or
818         * entity, advances over the whole tag/entity and returns
819         * Character.DIRECTIONALITY_WHITESPACE. For an entity, it would be best to figure out the
820         * actual character, and return its dirtype, but treating it as whitespace is good enough
821         * for our purposes.
822         *
823         * @throws java.lang.IndexOutOfBoundsException if called when charIndex > length or <= 0.
824         */
825        byte dirTypeBackward() {
826            lastChar = text.charAt(charIndex - 1);
827            if (Character.isLowSurrogate(lastChar)) {
828                int codePoint = Character.codePointBefore(text, charIndex);
829                charIndex -= Character.charCount(codePoint);
830                return Character.getDirectionality(codePoint);
831            }
832            charIndex--;
833            byte dirType = getCachedDirectionality(lastChar);
834            if (isHtml) {
835                // Process tags and entities.
836                if (lastChar == '>') {
837                    dirType = skipTagBackward();
838                } else if (lastChar == ';') {
839                    dirType = skipEntityBackward();
840                }
841            }
842            return dirType;
843        }
844
845        /**
846         * Advances charIndex forward through an HTML tag (after the opening &lt; has already been
847         * read) and returns Character.DIRECTIONALITY_WHITESPACE. If there is no matching &gt;,
848         * does not change charIndex and returns Character.DIRECTIONALITY_OTHER_NEUTRALS (for the
849         * &lt; that hadn't been part of a tag after all).
850         */
851        private byte skipTagForward() {
852            int initialCharIndex = charIndex;
853            while (charIndex < length) {
854                lastChar = text.charAt(charIndex++);
855                if (lastChar == '>') {
856                    // The end of the tag.
857                    return Character.DIRECTIONALITY_WHITESPACE;
858                }
859                if (lastChar == '"' || lastChar == '\'') {
860                    // Skip over a quoted attribute value inside the tag.
861                    char quote = lastChar;
862                    while (charIndex < length && (lastChar = text.charAt(charIndex++)) != quote) {}
863                }
864            }
865            // The original '<' wasn't the start of a tag after all.
866            charIndex = initialCharIndex;
867            lastChar = '<';
868            return Character.DIRECTIONALITY_OTHER_NEUTRALS;
869        }
870
871        /**
872         * Advances charIndex backward through an HTML tag (after the closing &gt; has already been
873         * read) and returns Character.DIRECTIONALITY_WHITESPACE. If there is no matching &lt;, does
874         * not change charIndex and returns Character.DIRECTIONALITY_OTHER_NEUTRALS (for the &gt;
875         * that hadn't been part of a tag after all). Nevertheless, the running time for calling
876         * skipTagBackward() in a loop remains linear in the size of the text, even for a text like
877         * "&gt;&gt;&gt;&gt;", because skipTagBackward() also stops looking for a matching &lt;
878         * when it encounters another &gt;.
879         */
880        private byte skipTagBackward() {
881            int initialCharIndex = charIndex;
882            while (charIndex > 0) {
883                lastChar = text.charAt(--charIndex);
884                if (lastChar == '<') {
885                    // The start of the tag.
886                    return Character.DIRECTIONALITY_WHITESPACE;
887                }
888                if (lastChar == '>') {
889                    break;
890                }
891                if (lastChar == '"' || lastChar == '\'') {
892                    // Skip over a quoted attribute value inside the tag.
893                    char quote = lastChar;
894                    while (charIndex > 0 && (lastChar = text.charAt(--charIndex)) != quote) {}
895                }
896            }
897            // The original '>' wasn't the end of a tag after all.
898            charIndex = initialCharIndex;
899            lastChar = '>';
900            return Character.DIRECTIONALITY_OTHER_NEUTRALS;
901        }
902
903        /**
904         * Advances charIndex forward through an HTML character entity tag (after the opening
905         * &amp; has already been read) and returns Character.DIRECTIONALITY_WHITESPACE. It would be
906         * best to figure out the actual character and return its dirtype, but this is good enough.
907         */
908        private byte skipEntityForward() {
909            while (charIndex < length && (lastChar = text.charAt(charIndex++)) != ';') {}
910            return Character.DIRECTIONALITY_WHITESPACE;
911        }
912
913        /**
914         * Advances charIndex backward through an HTML character entity tag (after the closing ;
915         * has already been read) and returns Character.DIRECTIONALITY_WHITESPACE. It would be best
916         * to figure out the actual character and return its dirtype, but this is good enough.
917         * If there is no matching &amp;, does not change charIndex and returns
918         * Character.DIRECTIONALITY_OTHER_NEUTRALS (for the ';' that did not start an entity after
919         * all). Nevertheless, the running time for calling skipEntityBackward() in a loop remains
920         * linear in the size of the text, even for a text like ";;;;;;;", because skipTagBackward()
921         * also stops looking for a matching &amp; when it encounters another ;.
922         */
923        private byte skipEntityBackward() {
924            int initialCharIndex = charIndex;
925            while (charIndex > 0) {
926                lastChar = text.charAt(--charIndex);
927                if (lastChar == '&') {
928                    return Character.DIRECTIONALITY_WHITESPACE;
929                }
930                if (lastChar == ';') {
931                    break;
932                }
933            }
934            charIndex = initialCharIndex;
935            lastChar = ';';
936            return Character.DIRECTIONALITY_OTHER_NEUTRALS;
937        }
938    }
939}
940