]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-4_4_2-src/main/classes/core/src/com/ibm/icu/text/Bidi.java
go
[Dictionary.git] / jars / icu4j-4_4_2-src / main / classes / core / src / com / ibm / icu / text / Bidi.java
1 /*\r
2 *******************************************************************************\r
3 *   Copyright (C) 2001-2009, International Business Machines\r
4 *   Corporation and others.  All Rights Reserved.\r
5 *******************************************************************************\r
6 */\r
7 \r
8 /* FOOD FOR THOUGHT: currently the reordering modes are a mixture of\r
9  * algorithm for direct BiDi, algorithm for inverse Bidi and the bizarre\r
10  * concept of RUNS_ONLY which is a double operation.\r
11  * It could be advantageous to divide this into 3 concepts:\r
12  * a) Operation: direct / inverse / RUNS_ONLY\r
13  * b) Direct algorithm: default / NUMBERS_SPECIAL / GROUP_NUMBERS_WITH_L\r
14  * c) Inverse algorithm: default / INVERSE_LIKE_DIRECT / NUMBERS_SPECIAL\r
15  * This would allow combinations not possible today like RUNS_ONLY with\r
16  * NUMBERS_SPECIAL.\r
17  * Also allow to set INSERT_MARKS for the direct step of RUNS_ONLY and\r
18  * REMOVE_CONTROLS for the inverse step.\r
19  * Not all combinations would be supported, and probably not all do make sense.\r
20  * This would need to document which ones are supported and what are the\r
21  * fallbacks for unsupported combinations.\r
22  */\r
23 \r
24 //TODO: make sample program do something simple but real and complete\r
25 \r
26 package com.ibm.icu.text;\r
27 \r
28 import java.awt.font.NumericShaper;\r
29 import java.awt.font.TextAttribute;\r
30 import java.io.IOException;\r
31 import java.lang.reflect.Array;\r
32 import java.text.AttributedCharacterIterator;\r
33 import java.util.Arrays;\r
34 import java.util.MissingResourceException;\r
35 \r
36 import com.ibm.icu.impl.UBiDiProps;\r
37 import com.ibm.icu.lang.UCharacter;\r
38 import com.ibm.icu.lang.UCharacterDirection;\r
39 \r
40 /**\r
41  *\r
42  * <h2>Bidi algorithm for ICU</h2>\r
43  *\r
44  * This is an implementation of the Unicode Bidirectional algorithm. The\r
45  * algorithm is defined in the <a\r
46  * href="http://www.unicode.org/unicode/reports/tr9/">Unicode Standard Annex #9</a>,\r
47  * version 13, also described in The Unicode Standard, Version 4.0 .\r
48  * <p>\r
49  *\r
50  * Note: Libraries that perform a bidirectional algorithm and reorder strings\r
51  * accordingly are sometimes called "Storage Layout Engines". ICU's Bidi and\r
52  * shaping (ArabicShaping) classes can be used at the core of such "Storage\r
53  * Layout Engines".\r
54  *\r
55  * <h3>General remarks about the API:</h3>\r
56  *\r
57  * The &quot;limit&quot; of a sequence of characters is the position just after\r
58  * their last character, i.e., one more than that position.\r
59  * <p>\r
60  *\r
61  * Some of the API methods provide access to &quot;runs&quot;. Such a\r
62  * &quot;run&quot; is defined as a sequence of characters that are at the same\r
63  * embedding level after performing the Bidi algorithm.\r
64  * <p>\r
65  *\r
66  * <h3>Basic concept: paragraph</h3>\r
67  * A piece of text can be divided into several paragraphs by characters\r
68  * with the Bidi class <code>Block Separator</code>. For handling of\r
69  * paragraphs, see:\r
70  * <ul>\r
71  * <li>{@link #countParagraphs}\r
72  * <li>{@link #getParaLevel}\r
73  * <li>{@link #getParagraph}\r
74  * <li>{@link #getParagraphByIndex}\r
75  * </ul>\r
76  *\r
77  * <h3>Basic concept: text direction</h3>\r
78  * The direction of a piece of text may be:\r
79  * <ul>\r
80  * <li>{@link #LTR}\r
81  * <li>{@link #RTL}\r
82  * <li>{@link #MIXED}\r
83  * </ul>\r
84  *\r
85  * <h3>Basic concept: levels</h3>\r
86  *\r
87  * Levels in this API represent embedding levels according to the Unicode\r
88  * Bidirectional Algorithm.\r
89  * Their low-order bit (even/odd value) indicates the visual direction.<p>\r
90  *\r
91  * Levels can be abstract values when used for the\r
92  * <code>paraLevel</code> and <code>embeddingLevels</code>\r
93  * arguments of <code>setPara()</code>; there:\r
94  * <ul>\r
95  * <li>the high-order bit of an <code>embeddingLevels[]</code>\r
96  * value indicates whether the using application is\r
97  * specifying the level of a character to <i>override</i> whatever the\r
98  * Bidi implementation would resolve it to.</li>\r
99  * <li><code>paraLevel</code> can be set to the\r
100  * pseudo-level values <code>LEVEL_DEFAULT_LTR</code>\r
101  * and <code>LEVEL_DEFAULT_RTL</code>.</li>\r
102  * </ul>\r
103  *\r
104  * <p>The related constants are not real, valid level values.\r
105  * <code>DEFAULT_XXX</code> can be used to specify\r
106  * a default for the paragraph level for\r
107  * when the <code>setPara()</code> method\r
108  * shall determine it but there is no\r
109  * strongly typed character in the input.<p>\r
110  *\r
111  * Note that the value for <code>LEVEL_DEFAULT_LTR</code> is even\r
112  * and the one for <code>LEVEL_DEFAULT_RTL</code> is odd,\r
113  * just like with normal LTR and RTL level values -\r
114  * these special values are designed that way. Also, the implementation\r
115  * assumes that MAX_EXPLICIT_LEVEL is odd.\r
116  *\r
117  * <ul><b>See Also:</b>\r
118  * <li>{@link #LEVEL_DEFAULT_LTR}\r
119  * <li>{@link #LEVEL_DEFAULT_RTL}\r
120  * <li>{@link #LEVEL_OVERRIDE}\r
121  * <li>{@link #MAX_EXPLICIT_LEVEL}\r
122  * <li>{@link #setPara}\r
123  * </ul>\r
124  *\r
125  * <h3>Basic concept: Reordering Mode</h3>\r
126  * Reordering mode values indicate which variant of the Bidi algorithm to\r
127  * use.\r
128  *\r
129  * <ul><b>See Also:</b>\r
130  * <li>{@link #setReorderingMode}\r
131  * <li>{@link #REORDER_DEFAULT}\r
132  * <li>{@link #REORDER_NUMBERS_SPECIAL}\r
133  * <li>{@link #REORDER_GROUP_NUMBERS_WITH_R}\r
134  * <li>{@link #REORDER_RUNS_ONLY}\r
135  * <li>{@link #REORDER_INVERSE_NUMBERS_AS_L}\r
136  * <li>{@link #REORDER_INVERSE_LIKE_DIRECT}\r
137  * <li>{@link #REORDER_INVERSE_FOR_NUMBERS_SPECIAL}\r
138  * </ul>\r
139  *\r
140  * <h3>Basic concept: Reordering Options</h3>\r
141  * Reordering options can be applied during Bidi text transformations.\r
142  * <ul><b>See Also:</b>\r
143  * <li>{@link #setReorderingOptions}\r
144  * <li>{@link #OPTION_DEFAULT}\r
145  * <li>{@link #OPTION_INSERT_MARKS}\r
146  * <li>{@link #OPTION_REMOVE_CONTROLS}\r
147  * <li>{@link #OPTION_STREAMING}\r
148  * </ul>\r
149  *\r
150  *\r
151  * @author Simon Montagu, Matitiahu Allouche (ported from C code written by Markus W. Scherer)\r
152  * @stable ICU 3.8\r
153  *\r
154  *\r
155  * <h4> Sample code for the ICU Bidi API </h4>\r
156  *\r
157  * <h5>Rendering a paragraph with the ICU Bidi API</h5>\r
158  *\r
159  * This is (hypothetical) sample code that illustrates how the ICU Bidi API\r
160  * could be used to render a paragraph of text. Rendering code depends highly on\r
161  * the graphics system, therefore this sample code must make a lot of\r
162  * assumptions, which may or may not match any existing graphics system's\r
163  * properties.\r
164  *\r
165  * <p>\r
166  * The basic assumptions are:\r
167  * </p>\r
168  * <ul>\r
169  * <li>Rendering is done from left to right on a horizontal line.</li>\r
170  * <li>A run of single-style, unidirectional text can be rendered at once.\r
171  * </li>\r
172  * <li>Such a run of text is passed to the graphics system with characters\r
173  * (code units) in logical order.</li>\r
174  * <li>The line-breaking algorithm is very complicated and Locale-dependent -\r
175  * and therefore its implementation omitted from this sample code.</li>\r
176  * </ul>\r
177  *\r
178  * <pre>\r
179  *\r
180  *  package com.ibm.icu.dev.test.bidi;\r
181  *\r
182  *  import com.ibm.icu.text.Bidi;\r
183  *  import com.ibm.icu.text.BidiRun;\r
184  *\r
185  *  public class Sample {\r
186  *\r
187  *      static final int styleNormal = 0;\r
188  *      static final int styleSelected = 1;\r
189  *      static final int styleBold = 2;\r
190  *      static final int styleItalics = 4;\r
191  *      static final int styleSuper=8;\r
192  *      static final int styleSub = 16;\r
193  *\r
194  *      static class StyleRun {\r
195  *          int limit;\r
196  *          int style;\r
197  *\r
198  *          public StyleRun(int limit, int style) {\r
199  *              this.limit = limit;\r
200  *              this.style = style;\r
201  *          }\r
202  *      }\r
203  *\r
204  *      static class Bounds {\r
205  *          int start;\r
206  *          int limit;\r
207  *\r
208  *          public Bounds(int start, int limit) {\r
209  *              this.start = start;\r
210  *              this.limit = limit;\r
211  *          }\r
212  *      }\r
213  *\r
214  *      static int getTextWidth(String text, int start, int limit,\r
215  *                              StyleRun[] styleRuns, int styleRunCount) {\r
216  *          // simplistic way to compute the width\r
217  *          return limit - start;\r
218  *      }\r
219  *\r
220  *      // set limit and StyleRun limit for a line\r
221  *      // from text[start] and from styleRuns[styleRunStart]\r
222  *      // using Bidi.getLogicalRun(...)\r
223  *      // returns line width\r
224  *      static int getLineBreak(String text, Bounds line, Bidi para,\r
225  *                              StyleRun styleRuns[], Bounds styleRun) {\r
226  *          // dummy return\r
227  *          return 0;\r
228  *      }\r
229  *\r
230  *      // render runs on a line sequentially, always from left to right\r
231  *\r
232  *      // prepare rendering a new line\r
233  *      static void startLine(byte textDirection, int lineWidth) {\r
234  *          System.out.println();\r
235  *      }\r
236  *\r
237  *      // render a run of text and advance to the right by the run width\r
238  *      // the text[start..limit-1] is always in logical order\r
239  *      static void renderRun(String text, int start, int limit,\r
240  *                            byte textDirection, int style) {\r
241  *      }\r
242  *\r
243  *      // We could compute a cross-product\r
244  *      // from the style runs with the directional runs\r
245  *      // and then reorder it.\r
246  *      // Instead, here we iterate over each run type\r
247  *      // and render the intersections -\r
248  *      // with shortcuts in simple (and common) cases.\r
249  *      // renderParagraph() is the main function.\r
250  *\r
251  *      // render a directional run with\r
252  *      // (possibly) multiple style runs intersecting with it\r
253  *      static void renderDirectionalRun(String text, int start, int limit,\r
254  *                                       byte direction, StyleRun styleRuns[],\r
255  *                                       int styleRunCount) {\r
256  *          int i;\r
257  *\r
258  *          // iterate over style runs\r
259  *          if (direction == Bidi.LTR) {\r
260  *              int styleLimit;\r
261  *              for (i = 0; i < styleRunCount; ++i) {\r
262  *                  styleLimit = styleRuns[i].limit;\r
263  *                  if (start < styleLimit) {\r
264  *                      if (styleLimit > limit) {\r
265  *                          styleLimit = limit;\r
266  *                      }\r
267  *                      renderRun(text, start, styleLimit,\r
268  *                                direction, styleRuns[i].style);\r
269  *                      if (styleLimit == limit) {\r
270  *                          break;\r
271  *                      }\r
272  *                      start = styleLimit;\r
273  *                  }\r
274  *              }\r
275  *          } else {\r
276  *              int styleStart;\r
277  *\r
278  *              for (i = styleRunCount-1; i >= 0; --i) {\r
279  *                  if (i > 0) {\r
280  *                      styleStart = styleRuns[i-1].limit;\r
281  *                  } else {\r
282  *                      styleStart = 0;\r
283  *                  }\r
284  *                  if (limit >= styleStart) {\r
285  *                      if (styleStart < start) {\r
286  *                          styleStart = start;\r
287  *                      }\r
288  *                      renderRun(text, styleStart, limit, direction,\r
289  *                                styleRuns[i].style);\r
290  *                      if (styleStart == start) {\r
291  *                          break;\r
292  *                      }\r
293  *                      limit = styleStart;\r
294  *                  }\r
295  *              }\r
296  *          }\r
297  *      }\r
298  *\r
299  *      // the line object represents text[start..limit-1]\r
300  *      static void renderLine(Bidi line, String text, int start, int limit,\r
301  *                             StyleRun styleRuns[], int styleRunCount) {\r
302  *          byte direction = line.getDirection();\r
303  *          if (direction != Bidi.MIXED) {\r
304  *              // unidirectional\r
305  *              if (styleRunCount <= 1) {\r
306  *                  renderRun(text, start, limit, direction, styleRuns[0].style);\r
307  *              } else {\r
308  *                  renderDirectionalRun(text, start, limit, direction,\r
309  *                                       styleRuns, styleRunCount);\r
310  *              }\r
311  *          } else {\r
312  *              // mixed-directional\r
313  *              int count, i;\r
314  *              BidiRun run;\r
315  *\r
316  *              try {\r
317  *                  count = line.countRuns();\r
318  *              } catch (IllegalStateException e) {\r
319  *                  e.printStackTrace();\r
320  *                  return;\r
321  *              }\r
322  *              if (styleRunCount <= 1) {\r
323  *                  int style = styleRuns[0].style;\r
324  *\r
325  *                  // iterate over directional runs\r
326  *                  for (i = 0; i < count; ++i) {\r
327  *                      run = line.getVisualRun(i);\r
328  *                      renderRun(text, run.getStart(), run.getLimit(),\r
329  *                                run.getDirection(), style);\r
330  *                  }\r
331  *              } else {\r
332  *                  // iterate over both directional and style runs\r
333  *                  for (i = 0; i < count; ++i) {\r
334  *                      run = line.getVisualRun(i);\r
335  *                      renderDirectionalRun(text, run.getStart(),\r
336  *                                           run.getLimit(), run.getDirection(),\r
337  *                                           styleRuns, styleRunCount);\r
338  *                  }\r
339  *              }\r
340  *          }\r
341  *      }\r
342  *\r
343  *      static void renderParagraph(String text, byte textDirection,\r
344  *                                  StyleRun styleRuns[], int styleRunCount,\r
345  *                                  int lineWidth) {\r
346  *          int length = text.length();\r
347  *          Bidi para = new Bidi();\r
348  *          try {\r
349  *              para.setPara(text,\r
350  *                           textDirection != 0 ? Bidi.LEVEL_DEFAULT_RTL\r
351  *                                              : Bidi.LEVEL_DEFAULT_LTR,\r
352  *                           null);\r
353  *          } catch (Exception e) {\r
354  *              e.printStackTrace();\r
355  *              return;\r
356  *          }\r
357  *          byte paraLevel = (byte)(1 & para.getParaLevel());\r
358  *          StyleRun styleRun = new StyleRun(length, styleNormal);\r
359  *\r
360  *          if (styleRuns == null || styleRunCount <= 0) {\r
361  *              styleRuns = new StyleRun[1];\r
362  *              styleRunCount = 1;\r
363  *              styleRuns[0] = styleRun;\r
364  *          }\r
365  *          // assume styleRuns[styleRunCount-1].limit>=length\r
366  *\r
367  *          int width = getTextWidth(text, 0, length, styleRuns, styleRunCount);\r
368  *          if (width <= lineWidth) {\r
369  *              // everything fits onto one line\r
370  *\r
371  *              // prepare rendering a new line from either left or right\r
372  *              startLine(paraLevel, width);\r
373  *\r
374  *              renderLine(para, text, 0, length, styleRuns, styleRunCount);\r
375  *          } else {\r
376  *              // we need to render several lines\r
377  *              Bidi line = new Bidi(length, 0);\r
378  *              int start = 0, limit;\r
379  *              int styleRunStart = 0, styleRunLimit;\r
380  *\r
381  *              for (;;) {\r
382  *                  limit = length;\r
383  *                  styleRunLimit = styleRunCount;\r
384  *                  width = getLineBreak(text, new Bounds(start, limit),\r
385  *                                       para, styleRuns,\r
386  *                                       new Bounds(styleRunStart, styleRunLimit));\r
387  *                  try {\r
388  *                      line = para.setLine(start, limit);\r
389  *                  } catch (Exception e) {\r
390  *                      e.printStackTrace();\r
391  *                      return;\r
392  *                  }\r
393  *                  // prepare rendering a new line\r
394  *                  // from either left or right\r
395  *                  startLine(paraLevel, width);\r
396  *\r
397  *                  if (styleRunStart > 0) {\r
398  *                      int newRunCount = styleRuns.length - styleRunStart;\r
399  *                      StyleRun[] newRuns = new StyleRun[newRunCount];\r
400  *                      System.arraycopy(styleRuns, styleRunStart, newRuns, 0,\r
401  *                                       newRunCount);\r
402  *                      renderLine(line, text, start, limit, newRuns,\r
403  *                                 styleRunLimit - styleRunStart);\r
404  *                  } else {\r
405  *                      renderLine(line, text, start, limit, styleRuns,\r
406  *                                 styleRunLimit - styleRunStart);\r
407  *                  }\r
408  *                  if (limit == length) {\r
409  *                      break;\r
410  *                  }\r
411  *                  start = limit;\r
412  *                  styleRunStart = styleRunLimit - 1;\r
413  *                  if (start >= styleRuns[styleRunStart].limit) {\r
414  *                      ++styleRunStart;\r
415  *                  }\r
416  *              }\r
417  *          }\r
418  *      }\r
419  *\r
420  *      public static void main(String[] args)\r
421  *      {\r
422  *          renderParagraph("Some Latin text...", Bidi.LTR, null, 0, 80);\r
423  *          renderParagraph("Some Hebrew text...", Bidi.RTL, null, 0, 60);\r
424  *      }\r
425  *  }\r
426  *\r
427  * </pre>\r
428  */\r
429 \r
430 public class Bidi {\r
431 \r
432     class Point {\r
433         int pos;    /* position in text */\r
434         int flag;   /* flag for LRM/RLM, before/after */\r
435     }\r
436 \r
437     class InsertPoints {\r
438         int size;\r
439         int confirmed;\r
440         Point[] points = new Point[0];\r
441     }\r
442 \r
443     /** Paragraph level setting<p>\r
444      *\r
445      * Constant indicating that the base direction depends on the first strong\r
446      * directional character in the text according to the Unicode Bidirectional\r
447      * Algorithm. If no strong directional character is present,\r
448      * then set the paragraph level to 0 (left-to-right).<p>\r
449      *\r
450      * If this value is used in conjunction with reordering modes\r
451      * <code>REORDER_INVERSE_LIKE_DIRECT</code> or\r
452      * <code>REORDER_INVERSE_FOR_NUMBERS_SPECIAL</code>, the text to reorder\r
453      * is assumed to be visual LTR, and the text after reordering is required\r
454      * to be the corresponding logical string with appropriate contextual\r
455      * direction. The direction of the result string will be RTL if either\r
456      * the righmost or leftmost strong character of the source text is RTL\r
457      * or Arabic Letter, the direction will be LTR otherwise.<p>\r
458      *\r
459      * If reordering option <code>OPTION_INSERT_MARKS</code> is set, an RLM may\r
460      * be added at the beginning of the result string to ensure round trip\r
461      * (that the result string, when reordered back to visual, will produce\r
462      * the original source text).\r
463      * @see #REORDER_INVERSE_LIKE_DIRECT\r
464      * @see #REORDER_INVERSE_FOR_NUMBERS_SPECIAL\r
465      * @stable ICU 3.8\r
466      */\r
467     public static final byte LEVEL_DEFAULT_LTR = (byte)0x7e;\r
468 \r
469     /** Paragraph level setting<p>\r
470      *\r
471      * Constant indicating that the base direction depends on the first strong\r
472      * directional character in the text according to the Unicode Bidirectional\r
473      * Algorithm. If no strong directional character is present,\r
474      * then set the paragraph level to 1 (right-to-left).<p>\r
475      *\r
476      * If this value is used in conjunction with reordering modes\r
477      * <code>REORDER_INVERSE_LIKE_DIRECT</code> or\r
478      * <code>REORDER_INVERSE_FOR_NUMBERS_SPECIAL</code>, the text to reorder\r
479      * is assumed to be visual LTR, and the text after reordering is required\r
480      * to be the corresponding logical string with appropriate contextual\r
481      * direction. The direction of the result string will be RTL if either\r
482      * the righmost or leftmost strong character of the source text is RTL\r
483      * or Arabic Letter, or if the text contains no strong character;\r
484      * the direction will be LTR otherwise.<p>\r
485      *\r
486      * If reordering option <code>OPTION_INSERT_MARKS</code> is set, an RLM may\r
487      * be added at the beginning of the result string to ensure round trip\r
488      * (that the result string, when reordered back to visual, will produce\r
489      * the original source text).\r
490      * @see #REORDER_INVERSE_LIKE_DIRECT\r
491      * @see #REORDER_INVERSE_FOR_NUMBERS_SPECIAL\r
492      * @stable ICU 3.8\r
493      */\r
494     public static final byte LEVEL_DEFAULT_RTL = (byte)0x7f;\r
495 \r
496     /**\r
497      * Maximum explicit embedding level.\r
498      * (The maximum resolved level can be up to <code>MAX_EXPLICIT_LEVEL+1</code>).\r
499      * @stable ICU 3.8\r
500      */\r
501     public static final byte MAX_EXPLICIT_LEVEL = 61;\r
502 \r
503     /**\r
504      * Bit flag for level input.\r
505      * Overrides directional properties.\r
506      * @stable ICU 3.8\r
507      */\r
508     public static final byte LEVEL_OVERRIDE = (byte)0x80;\r
509 \r
510     /**\r
511      * Special value which can be returned by the mapping methods when a\r
512      * logical index has no corresponding visual index or vice-versa. This may\r
513      * happen for the logical-to-visual mapping of a Bidi control when option\r
514      * <code>OPTION_REMOVE_CONTROLS</code> is\r
515      * specified. This can also happen for the visual-to-logical mapping of a\r
516      * Bidi mark (LRM or RLM) inserted by option\r
517      * <code>OPTION_INSERT_MARKS</code>.\r
518      * @see #getVisualIndex\r
519      * @see #getVisualMap\r
520      * @see #getLogicalIndex\r
521      * @see #getLogicalMap\r
522      * @see #OPTION_INSERT_MARKS\r
523      * @see #OPTION_REMOVE_CONTROLS\r
524      * @stable ICU 3.8\r
525      */\r
526     public static final int MAP_NOWHERE = -1;\r
527 \r
528     /**\r
529      * All left-to-right text.\r
530      * @stable ICU 3.8\r
531      */\r
532     public static final byte LTR = 0;\r
533 \r
534     /**\r
535      * All right-to-left text.\r
536      * @stable ICU 3.8\r
537      */\r
538     public static final byte RTL = 1;\r
539 \r
540     /**\r
541      * Mixed-directional text.\r
542      * @stable ICU 3.8\r
543      */\r
544     public static final byte MIXED = 2;\r
545 \r
546     /**\r
547      * option bit for writeReordered():\r
548      * keep combining characters after their base characters in RTL runs\r
549      *\r
550      * @see #writeReordered\r
551      * @stable ICU 3.8\r
552      */\r
553     public static final short KEEP_BASE_COMBINING = 1;\r
554 \r
555     /**\r
556      * option bit for writeReordered():\r
557      * replace characters with the "mirrored" property in RTL runs\r
558      * by their mirror-image mappings\r
559      *\r
560      * @see #writeReordered\r
561      * @stable ICU 3.8\r
562      */\r
563     public static final short DO_MIRRORING = 2;\r
564 \r
565     /**\r
566      * option bit for writeReordered():\r
567      * surround the run with LRMs if necessary;\r
568      * this is part of the approximate "inverse Bidi" algorithm\r
569      *\r
570      * <p>This option does not imply corresponding adjustment of the index\r
571      * mappings.</p>\r
572      *\r
573      * @see #setInverse\r
574      * @see #writeReordered\r
575      * @stable ICU 3.8\r
576      */\r
577     public static final short INSERT_LRM_FOR_NUMERIC = 4;\r
578 \r
579     /**\r
580      * option bit for writeReordered():\r
581      * remove Bidi control characters\r
582      * (this does not affect INSERT_LRM_FOR_NUMERIC)\r
583      *\r
584      * <p>This option does not imply corresponding adjustment of the index\r
585      * mappings.</p>\r
586      *\r
587      * @see #writeReordered\r
588      * @see #INSERT_LRM_FOR_NUMERIC\r
589      * @stable ICU 3.8\r
590      */\r
591     public static final short REMOVE_BIDI_CONTROLS = 8;\r
592 \r
593     /**\r
594      * option bit for writeReordered():\r
595      * write the output in reverse order\r
596      *\r
597      * <p>This has the same effect as calling <code>writeReordered()</code>\r
598      * first without this option, and then calling\r
599      * <code>writeReverse()</code> without mirroring.\r
600      * Doing this in the same step is faster and avoids a temporary buffer.\r
601      * An example for using this option is output to a character terminal that\r
602      * is designed for RTL scripts and stores text in reverse order.</p>\r
603      *\r
604      * @see #writeReordered\r
605      * @stable ICU 3.8\r
606      */\r
607     public static final short OUTPUT_REVERSE = 16;\r
608 \r
609     /** Reordering mode: Regular Logical to Visual Bidi algorithm according to Unicode.\r
610      * @see #setReorderingMode\r
611      * @stable ICU 3.8\r
612      */\r
613     public static final short REORDER_DEFAULT = 0;\r
614 \r
615     /** Reordering mode: Logical to Visual algorithm which handles numbers in\r
616      * a way which mimicks the behavior of Windows XP.\r
617      * @see #setReorderingMode\r
618      * @stable ICU 3.8\r
619      */\r
620     public static final short REORDER_NUMBERS_SPECIAL = 1;\r
621 \r
622     /** Reordering mode: Logical to Visual algorithm grouping numbers with\r
623      * adjacent R characters (reversible algorithm).\r
624      * @see #setReorderingMode\r
625      * @stable ICU 3.8\r
626      */\r
627     public static final short REORDER_GROUP_NUMBERS_WITH_R = 2;\r
628 \r
629     /** Reordering mode: Reorder runs only to transform a Logical LTR string\r
630      * to the logical RTL string with the same display, or vice-versa.<br>\r
631      * If this mode is set together with option\r
632      * <code>OPTION_INSERT_MARKS</code>, some Bidi controls in the source\r
633      * text may be removed and other controls may be added to produce the\r
634      * minimum combination which has the required display.\r
635      * @see #OPTION_INSERT_MARKS\r
636      * @see #setReorderingMode\r
637      * @stable ICU 3.8\r
638      */\r
639     public static final short REORDER_RUNS_ONLY = 3;\r
640 \r
641     /** Reordering mode: Visual to Logical algorithm which handles numbers\r
642      * like L (same algorithm as selected by <code>setInverse(true)</code>.\r
643      * @see #setInverse\r
644      * @see #setReorderingMode\r
645      * @stable ICU 3.8\r
646      */\r
647     public static final short REORDER_INVERSE_NUMBERS_AS_L = 4;\r
648 \r
649     /** Reordering mode: Visual to Logical algorithm equivalent to the regular\r
650      * Logical to Visual algorithm.\r
651      * @see #setReorderingMode\r
652      * @stable ICU 3.8\r
653      */\r
654     public static final short REORDER_INVERSE_LIKE_DIRECT = 5;\r
655 \r
656     /** Reordering mode: Inverse Bidi (Visual to Logical) algorithm for the\r
657      * <code>REORDER_NUMBERS_SPECIAL</code> Bidi algorithm.\r
658      * @see #setReorderingMode\r
659      * @stable ICU 3.8\r
660      */\r
661     public static final short REORDER_INVERSE_FOR_NUMBERS_SPECIAL = 6;\r
662 \r
663     /*  Number of values for reordering mode. */\r
664     static final short REORDER_COUNT = 7;\r
665 \r
666     /* Reordering mode values must be ordered so that all the regular logical to\r
667      * visual modes come first, and all inverse Bidi modes come last.\r
668      */\r
669     static final short REORDER_LAST_LOGICAL_TO_VISUAL =\r
670             REORDER_NUMBERS_SPECIAL;\r
671 \r
672     /**\r
673      * Option value for <code>setReorderingOptions</code>:\r
674      * disable all the options which can be set with this method\r
675      * @see #setReorderingOptions\r
676      * @stable ICU 3.8\r
677      */\r
678     public static final int OPTION_DEFAULT = 0;\r
679 \r
680     /**\r
681      * Option bit for <code>setReorderingOptions</code>:\r
682      * insert Bidi marks (LRM or RLM) when needed to ensure correct result of\r
683      * a reordering to a Logical order\r
684      *\r
685      * <p>This option must be set or reset before calling\r
686      * <code>setPara</code>.</p>\r
687      *\r
688      * <p>This option is significant only with reordering modes which generate\r
689      * a result with Logical order, specifically.</p>\r
690      * <ul>\r
691      *   <li><code>REORDER_RUNS_ONLY</code></li>\r
692      *   <li><code>REORDER_INVERSE_NUMBERS_AS_L</code></li>\r
693      *   <li><code>REORDER_INVERSE_LIKE_DIRECT</code></li>\r
694      *   <li><code>REORDER_INVERSE_FOR_NUMBERS_SPECIAL</code></li>\r
695      * </ul>\r
696      *\r
697      * <p>If this option is set in conjunction with reordering mode\r
698      * <code>REORDER_INVERSE_NUMBERS_AS_L</code> or with calling\r
699      * <code>setInverse(true)</code>, it implies option\r
700      * <code>INSERT_LRM_FOR_NUMERIC</code> in calls to method\r
701      * <code>writeReordered()</code>.</p>\r
702      *\r
703      * <p>For other reordering modes, a minimum number of LRM or RLM characters\r
704      * will be added to the source text after reordering it so as to ensure\r
705      * round trip, i.e. when applying the inverse reordering mode on the\r
706      * resulting logical text with removal of Bidi marks\r
707      * (option <code>OPTION_REMOVE_CONTROLS</code> set before calling\r
708      * <code>setPara()</code> or option\r
709      * <code>REMOVE_BIDI_CONTROLS</code> in\r
710      * <code>writeReordered</code>), the result will be identical to the\r
711      * source text in the first transformation.\r
712      *\r
713      * <p>This option will be ignored if specified together with option\r
714      * <code>OPTION_REMOVE_CONTROLS</code>. It inhibits option\r
715      * <code>REMOVE_BIDI_CONTROLS</code> in calls to method\r
716      * <code>writeReordered()</code> and it implies option\r
717      * <code>INSERT_LRM_FOR_NUMERIC</code> in calls to method\r
718      * <code>writeReordered()</code> if the reordering mode is\r
719      * <code>REORDER_INVERSE_NUMBERS_AS_L</code>.</p>\r
720      *\r
721      * @see #setReorderingMode\r
722      * @see #setReorderingOptions\r
723      * @see #INSERT_LRM_FOR_NUMERIC\r
724      * @see #REMOVE_BIDI_CONTROLS\r
725      * @see #OPTION_REMOVE_CONTROLS\r
726      * @see #REORDER_RUNS_ONLY\r
727      * @see #REORDER_INVERSE_NUMBERS_AS_L\r
728      * @see #REORDER_INVERSE_LIKE_DIRECT\r
729      * @see #REORDER_INVERSE_FOR_NUMBERS_SPECIAL\r
730      * @stable ICU 3.8\r
731      */\r
732     public static final int OPTION_INSERT_MARKS = 1;\r
733 \r
734     /**\r
735      * Option bit for <code>setReorderingOptions</code>:\r
736      * remove Bidi control characters\r
737      *\r
738      * <p>This option must be set or reset before calling\r
739      * <code>setPara</code>.</p>\r
740      *\r
741      * <p>This option nullifies option\r
742      * <code>OPTION_INSERT_MARKS</code>. It inhibits option\r
743      * <code>INSERT_LRM_FOR_NUMERIC</code> in calls to method\r
744      * <code>writeReordered()</code> and it implies option\r
745      * <code>REMOVE_BIDI_CONTROLS</code> in calls to that method.</p>\r
746      *\r
747      * @see #setReorderingMode\r
748      * @see #setReorderingOptions\r
749      * @see #OPTION_INSERT_MARKS\r
750      * @see #INSERT_LRM_FOR_NUMERIC\r
751      * @see #REMOVE_BIDI_CONTROLS\r
752      * @stable ICU 3.8\r
753      */\r
754     public static final int OPTION_REMOVE_CONTROLS = 2;\r
755 \r
756     /**\r
757      * Option bit for <code>setReorderingOptions</code>:\r
758      * process the output as part of a stream to be continued\r
759      *\r
760      * <p>This option must be set or reset before calling\r
761      * <code>setPara</code>.</p>\r
762      *\r
763      * <p>This option specifies that the caller is interested in processing\r
764      * large text object in parts. The results of the successive calls are\r
765      * expected to be concatenated by the caller. Only the call for the last\r
766      * part will have this option bit off.</p>\r
767      *\r
768      * <p>When this option bit is on, <code>setPara()</code> may process\r
769      * less than the full source text in order to truncate the text at a\r
770      * meaningful boundary. The caller should call\r
771      * <code>getProcessedLength()</code> immediately after calling\r
772      * <code>setPara()</code> in order to determine how much of the source\r
773      * text has been processed. Source text beyond that length should be\r
774      * resubmitted in following calls to <code>setPara</code>. The\r
775      * processed length may be less than the length of the source text if a\r
776      * character preceding the last character of the source text constitutes a\r
777      * reasonable boundary (like a block separator) for text to be continued.<br>\r
778      * If the last character of the source text constitutes a reasonable\r
779      * boundary, the whole text will be processed at once.<br>\r
780      * If nowhere in the source text there exists\r
781      * such a reasonable boundary, the processed length will be zero.<br>\r
782      * The caller should check for such an occurrence and do one of the following:\r
783      * <ul><li>submit a larger amount of text with a better chance to include\r
784      *         a reasonable boundary.</li>\r
785      *     <li>resubmit the same text after turning off option\r
786      *         <code>OPTION_STREAMING</code>.</li></ul>\r
787      * In all cases, this option should be turned off before processing the last\r
788      * part of the text.</p>\r
789      *\r
790      * <p>When the <code>OPTION_STREAMING</code> option is used, it is\r
791      * recommended to call <code>orderParagraphsLTR(true)</code> before calling\r
792      * <code>setPara()</code> so that later paragraphs may be concatenated to\r
793      * previous paragraphs on the right.\r
794      * </p>\r
795      *\r
796      * @see #setReorderingMode\r
797      * @see #setReorderingOptions\r
798      * @see #getProcessedLength\r
799      * @stable ICU 3.8\r
800      */\r
801     public static final int OPTION_STREAMING = 4;\r
802 \r
803     /*\r
804      *   Comparing the description of the Bidi algorithm with this implementation\r
805      *   is easier with the same names for the Bidi types in the code as there.\r
806      *   See UCharacterDirection\r
807      */\r
808     static final byte L   = UCharacterDirection.LEFT_TO_RIGHT;\r
809     static final byte R   = UCharacterDirection.RIGHT_TO_LEFT;\r
810     static final byte EN  = UCharacterDirection.EUROPEAN_NUMBER;\r
811     static final byte ES  = UCharacterDirection.EUROPEAN_NUMBER_SEPARATOR;\r
812     static final byte ET  = UCharacterDirection.EUROPEAN_NUMBER_TERMINATOR;\r
813     static final byte AN  = UCharacterDirection.ARABIC_NUMBER;\r
814     static final byte CS  = UCharacterDirection.COMMON_NUMBER_SEPARATOR;\r
815     static final byte B   = UCharacterDirection.BLOCK_SEPARATOR;\r
816     static final byte S   = UCharacterDirection.SEGMENT_SEPARATOR;\r
817     static final byte WS  = UCharacterDirection.WHITE_SPACE_NEUTRAL;\r
818     static final byte ON  = UCharacterDirection.OTHER_NEUTRAL;\r
819     static final byte LRE = UCharacterDirection.LEFT_TO_RIGHT_EMBEDDING;\r
820     static final byte LRO = UCharacterDirection.LEFT_TO_RIGHT_OVERRIDE;\r
821     static final byte AL  = UCharacterDirection.RIGHT_TO_LEFT_ARABIC;\r
822     static final byte RLE = UCharacterDirection.RIGHT_TO_LEFT_EMBEDDING;\r
823     static final byte RLO = UCharacterDirection.RIGHT_TO_LEFT_OVERRIDE;\r
824     static final byte PDF = UCharacterDirection.POP_DIRECTIONAL_FORMAT;\r
825     static final byte NSM = UCharacterDirection.DIR_NON_SPACING_MARK;\r
826     static final byte BN  = UCharacterDirection.BOUNDARY_NEUTRAL;\r
827 \r
828     static final int MASK_R_AL = (1 << R | 1 << AL);\r
829 \r
830     /**\r
831      * Value returned by <code>BidiClassifier</code> when there is no need to\r
832      * override the standard Bidi class for a given code point.\r
833      * @see BidiClassifier\r
834      * @stable ICU 3.8\r
835      */\r
836     public static final int CLASS_DEFAULT = UCharacterDirection\r
837                                             .CHAR_DIRECTION_COUNT;\r
838 \r
839     private static final char CR = '\r';\r
840     private static final char LF = '\n';\r
841 \r
842     static final int LRM_BEFORE = 1;\r
843     static final int LRM_AFTER = 2;\r
844     static final int RLM_BEFORE = 4;\r
845     static final int RLM_AFTER = 8;\r
846 \r
847     /*\r
848      * reference to parent paragraph object (reference to self if this object is\r
849      * a paragraph object); set to null in a newly opened object; set to a\r
850      * real value after a successful execution of setPara or setLine\r
851      */\r
852     Bidi                paraBidi;\r
853 \r
854     final UBiDiProps    bdp;\r
855 \r
856     /* character array representing the current text */\r
857     char[]              text;\r
858 \r
859     /* length of the current text */\r
860     int                 originalLength;\r
861 \r
862     /* if the option OPTION_STREAMING is set, this is the length of\r
863      * text actually processed by <code>setPara</code>, which may be shorter\r
864      * than the original length. Otherwise, it is identical to the original\r
865      * length.\r
866      */\r
867     int                 length;\r
868 \r
869     /* if option OPTION_REMOVE_CONTROLS is set, and/or Bidi\r
870      * marks are allowed to be inserted in one of the reordering modes, the\r
871      * length of the result string may be different from the processed length.\r
872      */\r
873     int                 resultLength;\r
874 \r
875     /* indicators for whether memory may be allocated after construction */\r
876     boolean             mayAllocateText;\r
877     boolean             mayAllocateRuns;\r
878 \r
879     /* arrays with one value per text-character */\r
880     byte[]              dirPropsMemory = new byte[1];\r
881     byte[]              levelsMemory = new byte[1];\r
882     byte[]              dirProps;\r
883     byte[]              levels;\r
884 \r
885     /* are we performing an approximation of the "inverse Bidi" algorithm? */\r
886     boolean             isInverse;\r
887 \r
888     /* are we using the basic algorithm or its variation? */\r
889     int                 reorderingMode;\r
890 \r
891     /* bitmask for reordering options */\r
892     int                 reorderingOptions;\r
893 \r
894     /* must block separators receive level 0? */\r
895     boolean             orderParagraphsLTR;\r
896 \r
897     /* the paragraph level */\r
898     byte                paraLevel;\r
899     /* original paraLevel when contextual */\r
900     /* must be one of DEFAULT_xxx or 0 if not contextual */\r
901     byte                defaultParaLevel;\r
902 \r
903     /* the following is set in setPara, used in processPropertySeq */\r
904 \r
905     ImpTabPair          impTabPair;  /* reference to levels state table pair */\r
906     /* the overall paragraph or line directionality*/\r
907     byte                direction;\r
908 \r
909     /* flags is a bit set for which directional properties are in the text */\r
910     int                 flags;\r
911 \r
912     /* lastArabicPos is index to the last AL in the text, -1 if none */\r
913     int                 lastArabicPos;\r
914 \r
915     /* characters after trailingWSStart are WS and are */\r
916     /* implicitly at the paraLevel (rule (L1)) - levels may not reflect that */\r
917     int                 trailingWSStart;\r
918 \r
919     /* fields for paragraph handling */\r
920     int                 paraCount;       /* set in getDirProps() */\r
921     int[]               parasMemory = new int[1];\r
922     int[]               paras;           /* limits of paragraphs, filled in\r
923                                           ResolveExplicitLevels() or CheckExplicitLevels() */\r
924 \r
925     /* for single paragraph text, we only need a tiny array of paras (no allocation) */\r
926     int[]               simpleParas = {0};\r
927 \r
928     /* fields for line reordering */\r
929     int                 runCount;     /* ==-1: runs not set up yet */\r
930     BidiRun[]           runsMemory = new BidiRun[0];\r
931     BidiRun[]           runs;\r
932 \r
933     /* for non-mixed text, we only need a tiny array of runs (no allocation) */\r
934     BidiRun[]           simpleRuns = {new BidiRun()};\r
935 \r
936     /* mapping of runs in logical order to visual order */\r
937     int[]               logicalToVisualRunsMap;\r
938     /* flag to indicate that the map has been updated */\r
939     boolean             isGoodLogicalToVisualRunsMap;\r
940 \r
941     /* customized class provider */\r
942     BidiClassifier      customClassifier = null;\r
943 \r
944     /* for inverse Bidi with insertion of directional marks */\r
945     InsertPoints        insertPoints = new InsertPoints();\r
946 \r
947     /* for option OPTION_REMOVE_CONTROLS */\r
948     int                 controlCount;\r
949 \r
950     /*\r
951      * Sometimes, bit values are more appropriate\r
952      * to deal with directionality properties.\r
953      * Abbreviations in these method names refer to names\r
954      * used in the Bidi algorithm.\r
955      */\r
956     static int DirPropFlag(byte dir) {\r
957         return (1 << dir);\r
958     }\r
959 \r
960     boolean testDirPropFlagAt(int flag, int index) {\r
961         return ((DirPropFlag((byte)(dirProps[index]&~CONTEXT_RTL)) & flag) != 0);\r
962     }\r
963 \r
964     /*\r
965      * The following bit is ORed to the property of characters in paragraphs\r
966      * with contextual RTL direction when paraLevel is contextual.\r
967      */\r
968     static final byte CONTEXT_RTL_SHIFT = 6;\r
969     static final byte CONTEXT_RTL = (byte)(1<<CONTEXT_RTL_SHIFT);   // 0x40\r
970     static byte NoContextRTL(byte dir)\r
971     {\r
972         return (byte)(dir & ~CONTEXT_RTL);\r
973     }\r
974 \r
975     /*\r
976      * The following is a variant of DirProp.DirPropFlag() which ignores the\r
977      * CONTEXT_RTL bit.\r
978      */\r
979     static int DirPropFlagNC(byte dir) {\r
980         return (1<<(dir & ~CONTEXT_RTL));\r
981     }\r
982 \r
983     static final int DirPropFlagMultiRuns = DirPropFlag((byte)31);\r
984 \r
985     /* to avoid some conditional statements, use tiny constant arrays */\r
986     static final int DirPropFlagLR[] = { DirPropFlag(L), DirPropFlag(R) };\r
987     static final int DirPropFlagE[] = { DirPropFlag(LRE), DirPropFlag(RLE) };\r
988     static final int DirPropFlagO[] = { DirPropFlag(LRO), DirPropFlag(RLO) };\r
989 \r
990     static final int DirPropFlagLR(byte level) { return DirPropFlagLR[level & 1]; }\r
991     static final int DirPropFlagE(byte level)  { return DirPropFlagE[level & 1]; }\r
992     static final int DirPropFlagO(byte level)  { return DirPropFlagO[level & 1]; }\r
993 \r
994     /*\r
995      *  are there any characters that are LTR?\r
996      */\r
997     static final int MASK_LTR =\r
998         DirPropFlag(L)|DirPropFlag(EN)|DirPropFlag(AN)|DirPropFlag(LRE)|DirPropFlag(LRO);\r
999 \r
1000     /*\r
1001      *  are there any characters that are RTL?\r
1002      */\r
1003     static final int MASK_RTL = DirPropFlag(R)|DirPropFlag(AL)|DirPropFlag(RLE)|DirPropFlag(RLO);\r
1004 \r
1005     /* explicit embedding codes */\r
1006     static final int MASK_LRX = DirPropFlag(LRE)|DirPropFlag(LRO);\r
1007     static final int MASK_RLX = DirPropFlag(RLE)|DirPropFlag(RLO);\r
1008     static final int MASK_OVERRIDE = DirPropFlag(LRO)|DirPropFlag(RLO);\r
1009     static final int MASK_EXPLICIT = MASK_LRX|MASK_RLX|DirPropFlag(PDF);\r
1010     static final int MASK_BN_EXPLICIT = DirPropFlag(BN)|MASK_EXPLICIT;\r
1011 \r
1012     /* paragraph and segment separators */\r
1013     static final int MASK_B_S = DirPropFlag(B)|DirPropFlag(S);\r
1014 \r
1015     /* all types that are counted as White Space or Neutral in some steps */\r
1016     static final int MASK_WS = MASK_B_S|DirPropFlag(WS)|MASK_BN_EXPLICIT;\r
1017     static final int MASK_N = DirPropFlag(ON)|MASK_WS;\r
1018 \r
1019     /* all types that are included in a sequence of\r
1020      * European Terminators for (W5) */\r
1021     static final int MASK_ET_NSM_BN = DirPropFlag(ET)|DirPropFlag(NSM)|MASK_BN_EXPLICIT;\r
1022 \r
1023     /* types that are neutrals or could becomes neutrals in (Wn) */\r
1024     static final int MASK_POSSIBLE_N = DirPropFlag(CS)|DirPropFlag(ES)|DirPropFlag(ET)|MASK_N;\r
1025 \r
1026     /*\r
1027      * These types may be changed to "e",\r
1028      * the embedding type (L or R) of the run,\r
1029      * in the Bidi algorithm (N2)\r
1030      */\r
1031     static final int MASK_EMBEDDING = DirPropFlag(NSM)|MASK_POSSIBLE_N;\r
1032 \r
1033     /*\r
1034      *  the dirProp's L and R are defined to 0 and 1 values in UCharacterDirection.java\r
1035      */\r
1036     static byte GetLRFromLevel(byte level)\r
1037     {\r
1038         return (byte)(level & 1);\r
1039     }\r
1040 \r
1041     static boolean IsDefaultLevel(byte level)\r
1042     {\r
1043         return ((level & LEVEL_DEFAULT_LTR) == LEVEL_DEFAULT_LTR);\r
1044     }\r
1045 \r
1046     byte GetParaLevelAt(int index)\r
1047     {\r
1048         return (defaultParaLevel != 0) ?\r
1049                 (byte)(dirProps[index]>>CONTEXT_RTL_SHIFT) : paraLevel;\r
1050     }\r
1051 \r
1052     static boolean IsBidiControlChar(int c)\r
1053     {\r
1054         /* check for range 0x200c to 0x200f (ZWNJ, ZWJ, LRM, RLM) or\r
1055                            0x202a to 0x202e (LRE, RLE, PDF, LRO, RLO) */\r
1056         return (((c & 0xfffffffc) == 0x200c) || ((c >= 0x202a) && (c <= 0x202e)));\r
1057     }\r
1058 \r
1059     void verifyValidPara()\r
1060     {\r
1061         if (!(this == this.paraBidi)) {\r
1062             throw new IllegalStateException();\r
1063         }\r
1064     }\r
1065 \r
1066     void verifyValidParaOrLine()\r
1067     {\r
1068         Bidi para = this.paraBidi;\r
1069         /* verify Para */\r
1070         if (this == para) {\r
1071             return;\r
1072         }\r
1073         /* verify Line */\r
1074         if ((para == null) || (para != para.paraBidi)) {\r
1075             throw new IllegalStateException();\r
1076         }\r
1077     }\r
1078 \r
1079     void verifyRange(int index, int start, int limit)\r
1080     {\r
1081         if (index < start || index >= limit) {\r
1082             throw new IllegalArgumentException("Value " + index +\r
1083                       " is out of range " + start + " to " + limit);\r
1084         }\r
1085     }\r
1086 \r
1087     /**\r
1088      * Allocate a <code>Bidi</code> object.\r
1089      * Such an object is initially empty. It is assigned\r
1090      * the Bidi properties of a piece of text containing one or more paragraphs\r
1091      * by <code>setPara()</code>\r
1092      * or the Bidi properties of a line within a paragraph by\r
1093      * <code>setLine()</code>.<p>\r
1094      * This object can be reused.<p>\r
1095      * <code>setPara()</code> and <code>setLine()</code> will allocate\r
1096      * additional memory for internal structures as necessary.\r
1097      *\r
1098      * @stable ICU 3.8\r
1099      */\r
1100     public Bidi()\r
1101     {\r
1102         this(0, 0);\r
1103     }\r
1104 \r
1105     /**\r
1106      * Allocate a <code>Bidi</code> object with preallocated memory\r
1107      * for internal structures.\r
1108      * This method provides a <code>Bidi</code> object like the default constructor\r
1109      * but it also preallocates memory for internal structures\r
1110      * according to the sizings supplied by the caller.<p>\r
1111      * The preallocation can be limited to some of the internal memory\r
1112      * by setting some values to 0 here. That means that if, e.g.,\r
1113      * <code>maxRunCount</code> cannot be reasonably predetermined and should not\r
1114      * be set to <code>maxLength</code> (the only failproof value) to avoid\r
1115      * wasting  memory, then <code>maxRunCount</code> could be set to 0 here\r
1116      * and the internal structures that are associated with it will be allocated\r
1117      * on demand, just like with the default constructor.\r
1118      *\r
1119      * @param maxLength is the maximum text or line length that internal memory\r
1120      *        will be preallocated for. An attempt to associate this object with a\r
1121      *        longer text will fail, unless this value is 0, which leaves the allocation\r
1122      *        up to the implementation.\r
1123      *\r
1124      * @param maxRunCount is the maximum anticipated number of same-level runs\r
1125      *        that internal memory will be preallocated for. An attempt to access\r
1126      *        visual runs on an object that was not preallocated for as many runs\r
1127      *        as the text was actually resolved to will fail,\r
1128      *        unless this value is 0, which leaves the allocation up to the implementation.<br><br>\r
1129      *        The number of runs depends on the actual text and maybe anywhere between\r
1130      *        1 and <code>maxLength</code>. It is typically small.\r
1131      *\r
1132      * @throws IllegalArgumentException if maxLength or maxRunCount is less than 0\r
1133      * @stable ICU 3.8\r
1134      */\r
1135     public Bidi(int maxLength, int maxRunCount)\r
1136     {\r
1137         /* check the argument values */\r
1138         if (maxLength < 0 || maxRunCount < 0) {\r
1139             throw new IllegalArgumentException();\r
1140         }\r
1141 \r
1142         /* reset the object, all reference variables null, all flags false,\r
1143            all sizes 0.\r
1144            In fact, we don't need to do anything, since class members are\r
1145            initialized as zero when an instance is created.\r
1146          */\r
1147         /*\r
1148         mayAllocateText = false;\r
1149         mayAllocateRuns = false;\r
1150         orderParagraphsLTR = false;\r
1151         paraCount = 0;\r
1152         runCount = 0;\r
1153         trailingWSStart = 0;\r
1154         flags = 0;\r
1155         paraLevel = 0;\r
1156         defaultParaLevel = 0;\r
1157         direction = 0;\r
1158         */\r
1159         /* get Bidi properties */\r
1160         try {\r
1161             bdp = UBiDiProps.getSingleton();\r
1162         }\r
1163         catch (IOException e) {\r
1164             ///CLOVER:OFF\r
1165             throw new MissingResourceException(e.getMessage(), "(BidiProps)", "");\r
1166             ///CLOVER:ON\r
1167         }\r
1168 \r
1169         /* allocate memory for arrays as requested */\r
1170         if (maxLength > 0) {\r
1171             getInitialDirPropsMemory(maxLength);\r
1172             getInitialLevelsMemory(maxLength);\r
1173         } else {\r
1174             mayAllocateText = true;\r
1175         }\r
1176 \r
1177         if (maxRunCount > 0) {\r
1178             // if maxRunCount == 1, use simpleRuns[]\r
1179             if (maxRunCount > 1) {\r
1180                 getInitialRunsMemory(maxRunCount);\r
1181             }\r
1182         } else {\r
1183             mayAllocateRuns = true;\r
1184         }\r
1185     }\r
1186 \r
1187     /*\r
1188      * We are allowed to allocate memory if object==null or\r
1189      * mayAllocate==true for each array that we need.\r
1190      *\r
1191      * Assume sizeNeeded>0.\r
1192      * If object != null, then assume size > 0.\r
1193      */\r
1194     private Object getMemory(String label, Object array, Class<?> arrayClass,\r
1195             boolean mayAllocate, int sizeNeeded)\r
1196     {\r
1197         int len = Array.getLength(array);\r
1198 \r
1199         /* we have at least enough memory and must not allocate */\r
1200         if (sizeNeeded == len) {\r
1201             return array;\r
1202         }\r
1203         if (!mayAllocate) {\r
1204             /* we must not allocate */\r
1205             if (sizeNeeded <= len) {\r
1206                 return array;\r
1207             }\r
1208             throw new OutOfMemoryError("Failed to allocate memory for "\r
1209                                        + label);\r
1210         }\r
1211         /* we may try to grow or shrink */\r
1212         /* FOOD FOR THOUGHT: when shrinking it should be possible to avoid\r
1213            the allocation altogether and rely on this.length */\r
1214         try {\r
1215             return Array.newInstance(arrayClass, sizeNeeded);\r
1216         } catch (Exception e) {\r
1217             throw new OutOfMemoryError("Failed to allocate memory for "\r
1218                                        + label);\r
1219         }\r
1220     }\r
1221 \r
1222     /* helper methods for each allocated array */\r
1223     private void getDirPropsMemory(boolean mayAllocate, int len)\r
1224     {\r
1225         Object array = getMemory("DirProps", dirPropsMemory, Byte.TYPE, mayAllocate, len);\r
1226         dirPropsMemory = (byte[]) array;\r
1227     }\r
1228 \r
1229     void getDirPropsMemory(int len)\r
1230     {\r
1231         getDirPropsMemory(mayAllocateText, len);\r
1232     }\r
1233 \r
1234     private void getLevelsMemory(boolean mayAllocate, int len)\r
1235     {\r
1236         Object array = getMemory("Levels", levelsMemory, Byte.TYPE, mayAllocate, len);\r
1237         levelsMemory = (byte[]) array;\r
1238     }\r
1239 \r
1240     void getLevelsMemory(int len)\r
1241     {\r
1242         getLevelsMemory(mayAllocateText, len);\r
1243     }\r
1244 \r
1245     private void getRunsMemory(boolean mayAllocate, int len)\r
1246     {\r
1247         Object array = getMemory("Runs", runsMemory, BidiRun.class, mayAllocate, len);\r
1248         runsMemory = (BidiRun[]) array;\r
1249     }\r
1250 \r
1251     void getRunsMemory(int len)\r
1252     {\r
1253         getRunsMemory(mayAllocateRuns, len);\r
1254     }\r
1255 \r
1256     /* additional methods used by constructor - always allow allocation */\r
1257     private void getInitialDirPropsMemory(int len)\r
1258     {\r
1259         getDirPropsMemory(true, len);\r
1260     }\r
1261 \r
1262     private void getInitialLevelsMemory(int len)\r
1263     {\r
1264         getLevelsMemory(true, len);\r
1265     }\r
1266 \r
1267     private void getInitialParasMemory(int len)\r
1268     {\r
1269         Object array = getMemory("Paras", parasMemory, Integer.TYPE, true, len);\r
1270         parasMemory = (int[]) array;\r
1271     }\r
1272 \r
1273     private void getInitialRunsMemory(int len)\r
1274     {\r
1275         getRunsMemory(true, len);\r
1276     }\r
1277 \r
1278     /**\r
1279      * Modify the operation of the Bidi algorithm such that it\r
1280      * approximates an "inverse Bidi" algorithm. This method\r
1281      * must be called before <code>setPara()</code>.\r
1282      *\r
1283      * <p>The normal operation of the Bidi algorithm as described\r
1284      * in the Unicode Technical Report is to take text stored in logical\r
1285      * (keyboard, typing) order and to determine the reordering of it for visual\r
1286      * rendering.\r
1287      * Some legacy systems store text in visual order, and for operations\r
1288      * with standard, Unicode-based algorithms, the text needs to be transformed\r
1289      * to logical order. This is effectively the inverse algorithm of the\r
1290      * described Bidi algorithm. Note that there is no standard algorithm for\r
1291      * this "inverse Bidi" and that the current implementation provides only an\r
1292      * approximation of "inverse Bidi".</p>\r
1293      *\r
1294      * <p>With <code>isInversed</code> set to <code>true</code>,\r
1295      * this method changes the behavior of some of the subsequent methods\r
1296      * in a way that they can be used for the inverse Bidi algorithm.\r
1297      * Specifically, runs of text with numeric characters will be treated in a\r
1298      * special way and may need to be surrounded with LRM characters when they are\r
1299      * written in reordered sequence.</p>\r
1300      *\r
1301      * <p>Output runs should be retrieved using <code>getVisualRun()</code>.\r
1302      * Since the actual input for "inverse Bidi" is visually ordered text and\r
1303      * <code>getVisualRun()</code> gets the reordered runs, these are actually\r
1304      * the runs of the logically ordered output.</p>\r
1305      *\r
1306      * <p>Calling this method with argument <code>isInverse</code> set to\r
1307      * <code>true</code> is equivalent to calling <code>setReorderingMode</code>\r
1308      * with argument <code>reorderingMode</code>\r
1309      * set to <code>REORDER_INVERSE_NUMBERS_AS_L</code>.<br>\r
1310      * Calling this method with argument <code>isInverse</code> set to\r
1311      * <code>false</code> is equivalent to calling <code>setReorderingMode</code>\r
1312      * with argument <code>reorderingMode</code>\r
1313      * set to <code>REORDER_DEFAULT</code>.\r
1314      *\r
1315      * @param isInverse specifies "forward" or "inverse" Bidi operation.\r
1316      *\r
1317      * @see #setPara\r
1318      * @see #writeReordered\r
1319      * @see #setReorderingMode\r
1320      * @see #REORDER_INVERSE_NUMBERS_AS_L\r
1321      * @see #REORDER_DEFAULT\r
1322      * @stable ICU 3.8\r
1323      */\r
1324     public void setInverse(boolean isInverse) {\r
1325         this.isInverse = (isInverse);\r
1326         this.reorderingMode = isInverse ? REORDER_INVERSE_NUMBERS_AS_L\r
1327                 : REORDER_DEFAULT;\r
1328     }\r
1329 \r
1330     /**\r
1331      * Is this <code>Bidi</code> object set to perform the inverse Bidi\r
1332      * algorithm?\r
1333      * <p>Note: calling this method after setting the reordering mode with\r
1334      * <code>setReorderingMode</code> will return <code>true</code> if the\r
1335      * reordering mode was set to\r
1336      * <code>REORDER_INVERSE_NUMBERS_AS_L<code>, <code>false</code>\r
1337      * for all other values.</p>\r
1338      *\r
1339      * @return <code>true</code> if the <code>Bidi</code> object is set to\r
1340      * perform the inverse Bidi algorithm by handling numbers as L.\r
1341      *\r
1342      * @see #setInverse\r
1343      * @see #setReorderingMode\r
1344      * @see #REORDER_INVERSE_NUMBERS_AS_L\r
1345      * @stable ICU 3.8\r
1346      */\r
1347     public boolean isInverse() {\r
1348         return isInverse;\r
1349     }\r
1350 \r
1351     /**\r
1352      * Modify the operation of the Bidi algorithm such that it implements some\r
1353      * variant to the basic Bidi algorithm or approximates an "inverse Bidi"\r
1354      * algorithm, depending on different values of the "reordering mode".\r
1355      * This method must be called before <code>setPara()</code>, and stays in\r
1356      * effect until called again with a different argument.\r
1357      *\r
1358      * <p>The normal operation of the Bidi algorithm as described in the Unicode\r
1359      * Standard Annex #9 is to take text stored in logical (keyboard, typing)\r
1360      * order and to determine how to reorder it for visual rendering.</p>\r
1361      *\r
1362      * <p>With the reordering mode set to a value other than\r
1363      * <code>REORDER_DEFAULT</code>, this method changes the behavior of some of\r
1364      * the subsequent methods in a way such that they implement an inverse Bidi\r
1365      * algorithm or some other algorithm variants.</p>\r
1366      *\r
1367      * <p>Some legacy systems store text in visual order, and for operations\r
1368      * with standard, Unicode-based algorithms, the text needs to be transformed\r
1369      * into logical order. This is effectively the inverse algorithm of the\r
1370      * described Bidi algorithm. Note that there is no standard algorithm for\r
1371      * this "inverse Bidi", so a number of variants are implemented here.</p>\r
1372      *\r
1373      * <p>In other cases, it may be desirable to emulate some variant of the\r
1374      * Logical to Visual algorithm (e.g. one used in MS Windows), or perform a\r
1375      * Logical to Logical transformation.</p>\r
1376      *\r
1377      * <ul>\r
1378      * <li>When the Reordering Mode is set to\r
1379      * <code>REORDER_DEFAULT</code>,\r
1380      * the standard Bidi Logical to Visual algorithm is applied.</li>\r
1381      *\r
1382      * <li>When the reordering mode is set to\r
1383      * <code>REORDER_NUMBERS_SPECIAL</code>,\r
1384      * the algorithm used to perform Bidi transformations when calling\r
1385      * <code>setPara</code> should approximate the algorithm used in Microsoft\r
1386      * Windows XP rather than strictly conform to the Unicode Bidi algorithm.\r
1387      * <br>\r
1388      * The differences between the basic algorithm and the algorithm addressed\r
1389      * by this option are as follows:\r
1390      * <ul>\r
1391      *   <li>Within text at an even embedding level, the sequence "123AB"\r
1392      *   (where AB represent R or AL letters) is transformed to "123BA" by the\r
1393      *   Unicode algorithm and to "BA123" by the Windows algorithm.</li>\r
1394      *\r
1395      *   <li>Arabic-Indic numbers (AN) are handled by the Windows algorithm just\r
1396      *   like regular numbers (EN).</li>\r
1397      * </ul></li>\r
1398      *\r
1399      * <li>When the reordering mode is set to\r
1400      * <code>REORDER_GROUP_NUMBERS_WITH_R</code>,\r
1401      * numbers located between LTR text and RTL text are associated with the RTL\r
1402      * text. For instance, an LTR paragraph with content "abc 123 DEF" (where\r
1403      * upper case letters represent RTL characters) will be transformed to\r
1404      * "abc FED 123" (and not "abc 123 FED"), "DEF 123 abc" will be transformed\r
1405      * to "123 FED abc" and "123 FED abc" will be transformed to "DEF 123 abc".\r
1406      * This makes the algorithm reversible and makes it useful when round trip\r
1407      * (from visual to logical and back to visual) must be achieved without\r
1408      * adding LRM characters. However, this is a variation from the standard\r
1409      * Unicode Bidi algorithm.<br>\r
1410      * The source text should not contain Bidi control characters other than LRM\r
1411      * or RLM.</li>\r
1412      *\r
1413      * <li>When the reordering mode is set to\r
1414      * <code>REORDER_RUNS_ONLY</code>,\r
1415      * a "Logical to Logical" transformation must be performed:\r
1416      * <ul>\r
1417      * <li>If the default text level of the source text (argument\r
1418      * <code>paraLevel</code> in <code>setPara</code>) is even, the source text\r
1419      * will be handled as LTR logical text and will be transformed to the RTL\r
1420      * logical text which has the same LTR visual display.</li>\r
1421      * <li>If the default level of the source text is odd, the source text\r
1422      * will be handled as RTL logical text and will be transformed to the\r
1423      * LTR logical text which has the same LTR visual display.</li>\r
1424      * </ul>\r
1425      * This mode may be needed when logical text which is basically Arabic or\r
1426      * Hebrew, with possible included numbers or phrases in English, has to be\r
1427      * displayed as if it had an even embedding level (this can happen if the\r
1428      * displaying application treats all text as if it was basically LTR).\r
1429      * <br>\r
1430      * This mode may also be needed in the reverse case, when logical text which\r
1431      * is basically English, with possible included phrases in Arabic or Hebrew,\r
1432      * has to be displayed as if it had an odd embedding level.\r
1433      * <br>\r
1434      * Both cases could be handled by adding LRE or RLE at the head of the\r
1435      * text, if the display subsystem supports these formatting controls. If it\r
1436      * does not, the problem may be handled by transforming the source text in\r
1437      * this mode before displaying it, so that it will be displayed properly.\r
1438      * <br>\r
1439      * The source text should not contain Bidi control characters other than LRM\r
1440      * or RLM.</li>\r
1441      *\r
1442      * <li>When the reordering mode is set to\r
1443      * <code>REORDER_INVERSE_NUMBERS_AS_L</code>, an "inverse Bidi"\r
1444      * algorithm is applied.\r
1445      * Runs of text with numeric characters will be treated like LTR letters and\r
1446      * may need to be surrounded with LRM characters when they are written in\r
1447      * reordered sequence (the option <code>INSERT_LRM_FOR_NUMERIC</code> can\r
1448      * be used with method <code>writeReordered</code> to this end. This mode\r
1449      * is equivalent to calling <code>setInverse()</code> with\r
1450      * argument <code>isInverse</code> set to <code>true</code>.</li>\r
1451      *\r
1452      * <li>When the reordering mode is set to\r
1453      * <code>REORDER_INVERSE_LIKE_DIRECT</code>, the "direct" Logical to\r
1454      * Visual Bidi algorithm is used as an approximation of an "inverse Bidi"\r
1455      * algorithm. This mode is similar to mode\r
1456      * <code>REORDER_INVERSE_NUMBERS_AS_L</code> but is closer to the\r
1457      * regular Bidi algorithm.\r
1458      * <br>\r
1459      * For example, an LTR paragraph with the content "FED 123 456 CBA" (where\r
1460      * upper case represents RTL characters) will be transformed to\r
1461      * "ABC 456 123 DEF", as opposed to "DEF 123 456 ABC"\r
1462      * with mode <code>REORDER_INVERSE_NUMBERS_AS_L</code>.<br>\r
1463      * When used in conjunction with option\r
1464      * <code>OPTION_INSERT_MARKS</code>, this mode generally\r
1465      * adds Bidi marks to the output significantly more sparingly than mode\r
1466      * <code>REORDER_INVERSE_NUMBERS_AS_L</code>.<br> with option\r
1467      * <code>INSERT_LRM_FOR_NUMERIC</code> in calls to\r
1468      * <code>writeReordered</code>.</li>\r
1469      *\r
1470      * <li>When the reordering mode is set to\r
1471      * <code>REORDER_INVERSE_FOR_NUMBERS_SPECIAL</code>, the Logical to Visual\r
1472      * Bidi algorithm used in Windows XP is used as an approximation of an "inverse\r
1473      * Bidi" algorithm.\r
1474      * <br>\r
1475      * For example, an LTR paragraph with the content "abc FED123" (where\r
1476      * upper case represents RTL characters) will be transformed to\r
1477      * "abc 123DEF.</li>\r
1478      * </ul>\r
1479      *\r
1480      * <p>In all the reordering modes specifying an "inverse Bidi" algorithm\r
1481      * (i.e. those with a name starting with <code>REORDER_INVERSE</code>),\r
1482      * output runs should be retrieved using <code>getVisualRun()</code>, and\r
1483      * the output text with <code>writeReordered()</code>. The caller should\r
1484      * keep in mind that in "inverse Bidi" modes the input is actually visually\r
1485      * ordered text and reordered output returned by <code>getVisualRun()</code>\r
1486      * or <code>writeReordered()</code> are actually runs or character string\r
1487      * of logically ordered output.<br>\r
1488      * For all the "inverse Bidi" modes, the source text should not contain\r
1489      * Bidi control characters other than LRM or RLM.</p>\r
1490      *\r
1491      * <p>Note that option <code>OUTPUT_REVERSE</code> of\r
1492      * <code>writeReordered</code> has no useful meaning and should not be used\r
1493      * in conjunction with any value of the reordering mode specifying "inverse\r
1494      * Bidi" or with value <code>REORDER_RUNS_ONLY</code>.\r
1495      *\r
1496      * @param reorderingMode specifies the required variant of the Bidi\r
1497      *                       algorithm.\r
1498      *\r
1499      * @see #setInverse\r
1500      * @see #setPara\r
1501      * @see #writeReordered\r
1502      * @see #INSERT_LRM_FOR_NUMERIC\r
1503      * @see #OUTPUT_REVERSE\r
1504      * @see #REORDER_DEFAULT\r
1505      * @see #REORDER_NUMBERS_SPECIAL\r
1506      * @see #REORDER_GROUP_NUMBERS_WITH_R\r
1507      * @see #REORDER_RUNS_ONLY\r
1508      * @see #REORDER_INVERSE_NUMBERS_AS_L\r
1509      * @see #REORDER_INVERSE_LIKE_DIRECT\r
1510      * @see #REORDER_INVERSE_FOR_NUMBERS_SPECIAL\r
1511      * @stable ICU 3.8\r
1512      */\r
1513     public void setReorderingMode(int reorderingMode) {\r
1514         if ((reorderingMode < REORDER_DEFAULT) ||\r
1515             (reorderingMode >= REORDER_COUNT))\r
1516             return;                     /* don't accept a wrong value */\r
1517         this.reorderingMode = reorderingMode;\r
1518         this.isInverse =\r
1519             reorderingMode == REORDER_INVERSE_NUMBERS_AS_L;\r
1520     }\r
1521 \r
1522     /**\r
1523      * What is the requested reordering mode for a given Bidi object?\r
1524      *\r
1525      * @return the current reordering mode of the Bidi object\r
1526      *\r
1527      * @see #setReorderingMode\r
1528      * @stable ICU 3.8\r
1529      */\r
1530     public int getReorderingMode() {\r
1531         return this.reorderingMode;\r
1532     }\r
1533 \r
1534     /**\r
1535      * Specify which of the reordering options should be applied during Bidi\r
1536      * transformations.\r
1537      *\r
1538      * @param options A combination of zero or more of the following\r
1539      * reordering options:\r
1540      * <code>OPTION_DEFAULT</code>, <code>OPTION_INSERT_MARKS</code>,\r
1541      * <code>OPTION_REMOVE_CONTROLS</code>, <code>OPTION_STREAMING</code>.\r
1542      *\r
1543      * @see #getReorderingOptions\r
1544      * @see #OPTION_DEFAULT\r
1545      * @see #OPTION_INSERT_MARKS\r
1546      * @see #OPTION_REMOVE_CONTROLS\r
1547      * @see #OPTION_STREAMING\r
1548      * @stable ICU 3.8\r
1549      */\r
1550     public void setReorderingOptions(int options) {\r
1551         if ((options & OPTION_REMOVE_CONTROLS) != 0) {\r
1552             this.reorderingOptions = options & ~OPTION_INSERT_MARKS;\r
1553         } else {\r
1554             this.reorderingOptions = options;\r
1555         }\r
1556     }\r
1557 \r
1558     /**\r
1559      * What are the reordering options applied to a given Bidi object?\r
1560      *\r
1561      * @return the current reordering options of the Bidi object\r
1562      *\r
1563      * @see #setReorderingOptions\r
1564      * @stable ICU 3.8\r
1565      */\r
1566     public int getReorderingOptions() {\r
1567         return this.reorderingOptions;\r
1568     }\r
1569 \r
1570 /* perform (P2)..(P3) ------------------------------------------------------- */\r
1571 \r
1572     private void getDirProps()\r
1573     {\r
1574         int i = 0, i0, i1;\r
1575         flags = 0;          /* collect all directionalities in the text */\r
1576         int uchar;\r
1577         byte dirProp;\r
1578         byte paraDirDefault = 0;   /* initialize to avoid compiler warnings */\r
1579         boolean isDefaultLevel = IsDefaultLevel(paraLevel);\r
1580         /* for inverse Bidi, the default para level is set to RTL if there is a\r
1581            strong R or AL character at either end of the text                */\r
1582         boolean isDefaultLevelInverse=isDefaultLevel &&\r
1583                 (reorderingMode==REORDER_INVERSE_LIKE_DIRECT ||\r
1584                  reorderingMode==REORDER_INVERSE_FOR_NUMBERS_SPECIAL);\r
1585         lastArabicPos = -1;\r
1586         controlCount = 0;\r
1587         boolean removeBidiControls = (reorderingOptions & OPTION_REMOVE_CONTROLS) != 0;\r
1588 \r
1589         final int NOT_CONTEXTUAL = 0;         /* 0: not contextual paraLevel */\r
1590         final int LOOKING_FOR_STRONG = 1;     /* 1: looking for first strong char */\r
1591         final int FOUND_STRONG_CHAR = 2;      /* 2: found first strong char       */\r
1592 \r
1593         int state;\r
1594         int paraStart = 0;                    /* index of first char in paragraph */\r
1595         byte paraDir;                         /* == CONTEXT_RTL within paragraphs\r
1596                                                  starting with strong R char      */\r
1597         byte lastStrongDir=0;                 /* for default level & inverse Bidi */\r
1598         int lastStrongLTR=0;                  /* for STREAMING option             */\r
1599 \r
1600         if ((reorderingOptions & OPTION_STREAMING) > 0) {\r
1601             length = 0;\r
1602             lastStrongLTR = 0;\r
1603         }\r
1604         if (isDefaultLevel) {\r
1605             paraDirDefault = ((paraLevel & 1) != 0) ? CONTEXT_RTL : 0;\r
1606             paraDir = paraDirDefault;\r
1607             lastStrongDir = paraDirDefault;\r
1608             state = LOOKING_FOR_STRONG;\r
1609         } else {\r
1610             state = NOT_CONTEXTUAL;\r
1611             paraDir = 0;\r
1612         }\r
1613         /* count paragraphs and determine the paragraph level (P2..P3) */\r
1614         /*\r
1615          * see comment on constant fields:\r
1616          * the LEVEL_DEFAULT_XXX values are designed so that\r
1617          * their low-order bit alone yields the intended default\r
1618          */\r
1619 \r
1620         for (i = 0; i < originalLength; /* i is incremented in the loop */) {\r
1621             i0 = i;                     /* index of first code unit */\r
1622             uchar = UTF16.charAt(text, 0, originalLength, i);\r
1623             i += UTF16.getCharCount(uchar);\r
1624             i1 = i - 1; /* index of last code unit, gets the directional property */\r
1625 \r
1626             dirProp = (byte)getCustomizedClass(uchar);\r
1627             flags |= DirPropFlag(dirProp);\r
1628             dirProps[i1] = (byte)(dirProp | paraDir);\r
1629             if (i1 > i0) {     /* set previous code units' properties to BN */\r
1630                 flags |= DirPropFlag(BN);\r
1631                 do {\r
1632                     dirProps[--i1] = (byte)(BN | paraDir);\r
1633                 } while (i1 > i0);\r
1634             }\r
1635             if (state == LOOKING_FOR_STRONG) {\r
1636                 if (dirProp == L) {\r
1637                     state = FOUND_STRONG_CHAR;\r
1638                     if (paraDir != 0) {\r
1639                         paraDir = 0;\r
1640                         for (i1 = paraStart; i1 < i; i1++) {\r
1641                             dirProps[i1] &= ~CONTEXT_RTL;\r
1642                         }\r
1643                     }\r
1644                     continue;\r
1645                 }\r
1646                 if (dirProp == R || dirProp == AL) {\r
1647                     state = FOUND_STRONG_CHAR;\r
1648                     if (paraDir == 0) {\r
1649                         paraDir = CONTEXT_RTL;\r
1650                         for (i1 = paraStart; i1 < i; i1++) {\r
1651                             dirProps[i1] |= CONTEXT_RTL;\r
1652                         }\r
1653                     }\r
1654                     continue;\r
1655                 }\r
1656             }\r
1657             if (dirProp == L) {\r
1658                 lastStrongDir = 0;\r
1659                 lastStrongLTR = i;      /* i is index to next character */\r
1660             }\r
1661             else if (dirProp == R) {\r
1662                 lastStrongDir = CONTEXT_RTL;\r
1663             }\r
1664             else if (dirProp == AL) {\r
1665                 lastStrongDir = CONTEXT_RTL;\r
1666                 lastArabicPos = i-1;\r
1667             }\r
1668             else if (dirProp == B) {\r
1669                 if ((reorderingOptions & OPTION_STREAMING) != 0) {\r
1670                     this.length = i;    /* i is index to next character */\r
1671                 }\r
1672                 if (isDefaultLevelInverse && (lastStrongDir==CONTEXT_RTL) &&(paraDir!=lastStrongDir)) {\r
1673                     for ( ; paraStart < i; paraStart++) {\r
1674                         dirProps[paraStart] |= CONTEXT_RTL;\r
1675                     }\r
1676                 }\r
1677                 if (i < originalLength) {   /* B not last char in text */\r
1678                     if (!((uchar == (int)CR) && (text[i] == (int)LF))) {\r
1679                         paraCount++;\r
1680                     }\r
1681                     if (isDefaultLevel) {\r
1682                         state=LOOKING_FOR_STRONG;\r
1683                         paraStart = i;        /* i is index to next character */\r
1684                         paraDir = paraDirDefault;\r
1685                         lastStrongDir = paraDirDefault;\r
1686                     }\r
1687                 }\r
1688             }\r
1689             if (removeBidiControls && IsBidiControlChar(uchar)) {\r
1690                 controlCount++;\r
1691             }\r
1692         }\r
1693         if (isDefaultLevelInverse && (lastStrongDir==CONTEXT_RTL) &&(paraDir!=lastStrongDir)) {\r
1694             for (i1 = paraStart; i1 < originalLength; i1++) {\r
1695                 dirProps[i1] |= CONTEXT_RTL;\r
1696             }\r
1697         }\r
1698         if (isDefaultLevel) {\r
1699             paraLevel = GetParaLevelAt(0);\r
1700         }\r
1701         if ((reorderingOptions & OPTION_STREAMING) > 0) {\r
1702             if ((lastStrongLTR > this.length) &&\r
1703                (GetParaLevelAt(lastStrongLTR) == 0)) {\r
1704                 this.length = lastStrongLTR;\r
1705             }\r
1706             if (this.length < originalLength) {\r
1707                 paraCount--;\r
1708             }\r
1709         }\r
1710         /* The following line does nothing new for contextual paraLevel, but is\r
1711            needed for absolute paraLevel.                               */\r
1712         flags |= DirPropFlagLR(paraLevel);\r
1713 \r
1714         if (orderParagraphsLTR && (flags & DirPropFlag(B)) != 0) {\r
1715             flags |= DirPropFlag(L);\r
1716         }\r
1717     }\r
1718 \r
1719     /* perform (X1)..(X9) ------------------------------------------------------- */\r
1720 \r
1721     /* determine if the text is mixed-directional or single-directional */\r
1722     private byte directionFromFlags() {\r
1723         /* if the text contains AN and neutrals, then some neutrals may become RTL */\r
1724         if (!((flags & MASK_RTL) != 0 ||\r
1725               ((flags & DirPropFlag(AN)) != 0 &&\r
1726                (flags & MASK_POSSIBLE_N) != 0))) {\r
1727             return LTR;\r
1728         } else if ((flags & MASK_LTR) == 0) {\r
1729             return RTL;\r
1730         } else {\r
1731             return MIXED;\r
1732         }\r
1733     }\r
1734 \r
1735     /*\r
1736      * Resolve the explicit levels as specified by explicit embedding codes.\r
1737      * Recalculate the flags to have them reflect the real properties\r
1738      * after taking the explicit embeddings into account.\r
1739      *\r
1740      * The Bidi algorithm is designed to result in the same behavior whether embedding\r
1741      * levels are externally specified (from "styled text", supposedly the preferred\r
1742      * method) or set by explicit embedding codes (LRx, RLx, PDF) in the plain text.\r
1743      * That is why (X9) instructs to remove all explicit codes (and BN).\r
1744      * However, in a real implementation, this removal of these codes and their index\r
1745      * positions in the plain text is undesirable since it would result in\r
1746      * reallocated, reindexed text.\r
1747      * Instead, this implementation leaves the codes in there and just ignores them\r
1748      * in the subsequent processing.\r
1749      * In order to get the same reordering behavior, positions with a BN or an\r
1750      * explicit embedding code just get the same level assigned as the last "real"\r
1751      * character.\r
1752      *\r
1753      * Some implementations, not this one, then overwrite some of these\r
1754      * directionality properties at "real" same-level-run boundaries by\r
1755      * L or R codes so that the resolution of weak types can be performed on the\r
1756      * entire paragraph at once instead of having to parse it once more and\r
1757      * perform that resolution on same-level-runs.\r
1758      * This limits the scope of the implicit rules in effectively\r
1759      * the same way as the run limits.\r
1760      *\r
1761      * Instead, this implementation does not modify these codes.\r
1762      * On one hand, the paragraph has to be scanned for same-level-runs, but\r
1763      * on the other hand, this saves another loop to reset these codes,\r
1764      * or saves making and modifying a copy of dirProps[].\r
1765      *\r
1766      *\r
1767      * Note that (Pn) and (Xn) changed significantly from version 4 of the Bidi algorithm.\r
1768      *\r
1769      *\r
1770      * Handling the stack of explicit levels (Xn):\r
1771      *\r
1772      * With the Bidi stack of explicit levels,\r
1773      * as pushed with each LRE, RLE, LRO, and RLO and popped with each PDF,\r
1774      * the explicit level must never exceed MAX_EXPLICIT_LEVEL==61.\r
1775      *\r
1776      * In order to have a correct push-pop semantics even in the case of overflows,\r
1777      * there are two overflow counters:\r
1778      * - countOver60 is incremented with each LRx at level 60\r
1779      * - from level 60, one RLx increases the level to 61\r
1780      * - countOver61 is incremented with each LRx and RLx at level 61\r
1781      *\r
1782      * Popping levels with PDF must work in the opposite order so that level 61\r
1783      * is correct at the correct point. Underflows (too many PDFs) must be checked.\r
1784      *\r
1785      * This implementation assumes that MAX_EXPLICIT_LEVEL is odd.\r
1786      */\r
1787     private byte resolveExplicitLevels() {\r
1788         int i = 0;\r
1789         byte dirProp;\r
1790         byte level = GetParaLevelAt(0);\r
1791 \r
1792         byte dirct;\r
1793         int paraIndex = 0;\r
1794 \r
1795         /* determine if the text is mixed-directional or single-directional */\r
1796         dirct = directionFromFlags();\r
1797 \r
1798         /* we may not need to resolve any explicit levels, but for multiple\r
1799            paragraphs we want to loop on all chars to set the para boundaries */\r
1800         if ((dirct != MIXED) && (paraCount == 1)) {\r
1801             /* not mixed directionality: levels don't matter - trailingWSStart will be 0 */\r
1802         } else if ((paraCount == 1) &&\r
1803                    ((flags & MASK_EXPLICIT) == 0 ||\r
1804                     reorderingMode > REORDER_LAST_LOGICAL_TO_VISUAL)) {\r
1805             /* mixed, but all characters are at the same embedding level */\r
1806             /* or we are in "inverse Bidi" */\r
1807             /* and we don't have contextual multiple paragraphs with some B char */\r
1808             /* set all levels to the paragraph level */\r
1809             for (i = 0; i < length; ++i) {\r
1810                 levels[i] = level;\r
1811             }\r
1812         } else {\r
1813             /* continue to perform (Xn) */\r
1814 \r
1815             /* (X1) level is set for all codes, embeddingLevel keeps track of the push/pop operations */\r
1816             /* both variables may carry the LEVEL_OVERRIDE flag to indicate the override status */\r
1817             byte embeddingLevel = level;\r
1818             byte newLevel;\r
1819             byte stackTop = 0;\r
1820 \r
1821             byte[] stack = new byte[MAX_EXPLICIT_LEVEL];    /* we never push anything >=MAX_EXPLICIT_LEVEL */\r
1822             int countOver60 = 0;\r
1823             int countOver61 = 0;  /* count overflows of explicit levels */\r
1824 \r
1825             /* recalculate the flags */\r
1826             flags = 0;\r
1827 \r
1828             for (i = 0; i < length; ++i) {\r
1829                 dirProp = NoContextRTL(dirProps[i]);\r
1830                 switch(dirProp) {\r
1831                 case LRE:\r
1832                 case LRO:\r
1833                     /* (X3, X5) */\r
1834                     newLevel = (byte)((embeddingLevel+2) & ~(LEVEL_OVERRIDE | 1)); /* least greater even level */\r
1835                     if (newLevel <= MAX_EXPLICIT_LEVEL) {\r
1836                         stack[stackTop] = embeddingLevel;\r
1837                         ++stackTop;\r
1838                         embeddingLevel = newLevel;\r
1839                         if (dirProp == LRO) {\r
1840                             embeddingLevel |= LEVEL_OVERRIDE;\r
1841                         }\r
1842                         /* we don't need to set LEVEL_OVERRIDE off for LRE\r
1843                            since this has already been done for newLevel which is\r
1844                            the source for embeddingLevel.\r
1845                          */\r
1846                     } else if ((embeddingLevel & ~LEVEL_OVERRIDE) == MAX_EXPLICIT_LEVEL) {\r
1847                         ++countOver61;\r
1848                     } else /* (embeddingLevel & ~LEVEL_OVERRIDE) == MAX_EXPLICIT_LEVEL-1 */ {\r
1849                         ++countOver60;\r
1850                     }\r
1851                     flags |= DirPropFlag(BN);\r
1852                     break;\r
1853                 case RLE:\r
1854                 case RLO:\r
1855                     /* (X2, X4) */\r
1856                     newLevel=(byte)(((embeddingLevel & ~LEVEL_OVERRIDE) + 1) | 1); /* least greater odd level */\r
1857                     if (newLevel<=MAX_EXPLICIT_LEVEL) {\r
1858                         stack[stackTop] = embeddingLevel;\r
1859                         ++stackTop;\r
1860                         embeddingLevel = newLevel;\r
1861                         if (dirProp == RLO) {\r
1862                             embeddingLevel |= LEVEL_OVERRIDE;\r
1863                         }\r
1864                         /* we don't need to set LEVEL_OVERRIDE off for RLE\r
1865                            since this has already been done for newLevel which is\r
1866                            the source for embeddingLevel.\r
1867                          */\r
1868                     } else {\r
1869                         ++countOver61;\r
1870                     }\r
1871                     flags |= DirPropFlag(BN);\r
1872                     break;\r
1873                 case PDF:\r
1874                     /* (X7) */\r
1875                     /* handle all the overflow cases first */\r
1876                     if (countOver61 > 0) {\r
1877                         --countOver61;\r
1878                     } else if (countOver60 > 0 && (embeddingLevel & ~LEVEL_OVERRIDE) != MAX_EXPLICIT_LEVEL) {\r
1879                         /* handle LRx overflows from level 60 */\r
1880                         --countOver60;\r
1881                     } else if (stackTop > 0) {\r
1882                         /* this is the pop operation; it also pops level 61 while countOver60>0 */\r
1883                         --stackTop;\r
1884                         embeddingLevel = stack[stackTop];\r
1885                     /* } else { (underflow) */\r
1886                     }\r
1887                     flags |= DirPropFlag(BN);\r
1888                     break;\r
1889                 case B:\r
1890                     stackTop = 0;\r
1891                     countOver60 = 0;\r
1892                     countOver61 = 0;\r
1893                     level = GetParaLevelAt(i);\r
1894                     if ((i + 1) < length) {\r
1895                         embeddingLevel = GetParaLevelAt(i+1);\r
1896                         if (!((text[i] == CR) && (text[i + 1] == LF))) {\r
1897                             paras[paraIndex++] = i+1;\r
1898                         }\r
1899                     }\r
1900                     flags |= DirPropFlag(B);\r
1901                     break;\r
1902                 case BN:\r
1903                     /* BN, LRE, RLE, and PDF are supposed to be removed (X9) */\r
1904                     /* they will get their levels set correctly in adjustWSLevels() */\r
1905                     flags |= DirPropFlag(BN);\r
1906                     break;\r
1907                 default:\r
1908                     /* all other types get the "real" level */\r
1909                     if (level != embeddingLevel) {\r
1910                         level = embeddingLevel;\r
1911                         if ((level & LEVEL_OVERRIDE) != 0) {\r
1912                             flags |= DirPropFlagO(level) | DirPropFlagMultiRuns;\r
1913                         } else {\r
1914                             flags |= DirPropFlagE(level) | DirPropFlagMultiRuns;\r
1915                         }\r
1916                     }\r
1917                     if ((level & LEVEL_OVERRIDE) == 0) {\r
1918                         flags |= DirPropFlag(dirProp);\r
1919                     }\r
1920                     break;\r
1921                 }\r
1922 \r
1923                 /*\r
1924                  * We need to set reasonable levels even on BN codes and\r
1925                  * explicit codes because we will later look at same-level runs (X10).\r
1926                  */\r
1927                 levels[i] = level;\r
1928             }\r
1929             if ((flags & MASK_EMBEDDING) != 0) {\r
1930                 flags |= DirPropFlagLR(paraLevel);\r
1931             }\r
1932             if (orderParagraphsLTR && (flags & DirPropFlag(B)) != 0) {\r
1933                 flags |= DirPropFlag(L);\r
1934             }\r
1935 \r
1936             /* subsequently, ignore the explicit codes and BN (X9) */\r
1937 \r
1938             /* again, determine if the text is mixed-directional or single-directional */\r
1939             dirct = directionFromFlags();\r
1940         }\r
1941 \r
1942         return dirct;\r
1943     }\r
1944 \r
1945     /*\r
1946      * Use a pre-specified embedding levels array:\r
1947      *\r
1948      * Adjust the directional properties for overrides (->LEVEL_OVERRIDE),\r
1949      * ignore all explicit codes (X9),\r
1950      * and check all the preset levels.\r
1951      *\r
1952      * Recalculate the flags to have them reflect the real properties\r
1953      * after taking the explicit embeddings into account.\r
1954      */\r
1955     private byte checkExplicitLevels() {\r
1956         byte dirProp;\r
1957         int i;\r
1958         this.flags = 0;     /* collect all directionalities in the text */\r
1959         byte level;\r
1960         int paraIndex = 0;\r
1961 \r
1962         for (i = 0; i < length; ++i) {\r
1963             level = levels[i];\r
1964             dirProp = NoContextRTL(dirProps[i]);\r
1965             if ((level & LEVEL_OVERRIDE) != 0) {\r
1966                 /* keep the override flag in levels[i] but adjust the flags */\r
1967                 level &= ~LEVEL_OVERRIDE;     /* make the range check below simpler */\r
1968                 flags |= DirPropFlagO(level);\r
1969             } else {\r
1970                 /* set the flags */\r
1971                 flags |= DirPropFlagE(level) | DirPropFlag(dirProp);\r
1972             }\r
1973             if ((level < GetParaLevelAt(i) &&\r
1974                     !((0 == level) && (dirProp == B))) ||\r
1975                     (MAX_EXPLICIT_LEVEL <level)) {\r
1976                 /* level out of bounds */\r
1977                 throw new IllegalArgumentException("level " + level +\r
1978                                                    " out of bounds at " + i);\r
1979             }\r
1980             if ((dirProp == B) && ((i + 1) < length)) {\r
1981                 if (!((text[i] == CR) && (text[i + 1] == LF))) {\r
1982                     paras[paraIndex++] = i + 1;\r
1983                 }\r
1984             }\r
1985         }\r
1986         if ((flags&MASK_EMBEDDING) != 0) {\r
1987             flags |= DirPropFlagLR(paraLevel);\r
1988         }\r
1989 \r
1990         /* determine if the text is mixed-directional or single-directional */\r
1991         return directionFromFlags();\r
1992     }\r
1993 \r
1994     /*********************************************************************/\r
1995     /* The Properties state machine table                                */\r
1996     /*********************************************************************/\r
1997     /*                                                                   */\r
1998     /* All table cells are 8 bits:                                       */\r
1999     /*      bits 0..4:  next state                                       */\r
2000     /*      bits 5..7:  action to perform (if > 0)                       */\r
2001     /*                                                                   */\r
2002     /* Cells may be of format "n" where n represents the next state      */\r
2003     /* (except for the rightmost column).                                */\r
2004     /* Cells may also be of format "_(x,y)" where x represents an action */\r
2005     /* to perform and y represents the next state.                       */\r
2006     /*                                                                   */\r
2007     /*********************************************************************/\r
2008     /* Definitions and type for properties state tables                  */\r
2009     /*********************************************************************/\r
2010     private static final int IMPTABPROPS_COLUMNS = 14;\r
2011     private static final int IMPTABPROPS_RES = IMPTABPROPS_COLUMNS - 1;\r
2012     private static short GetStateProps(short cell) {\r
2013         return (short)(cell & 0x1f);\r
2014     }\r
2015     private static short GetActionProps(short cell) {\r
2016         return (short)(cell >> 5);\r
2017     }\r
2018 \r
2019     private static final short groupProp[] =          /* dirProp regrouped */\r
2020     {\r
2021         /*  L   R   EN  ES  ET  AN  CS  B   S   WS  ON  LRE LRO AL  RLE RLO PDF NSM BN  */\r
2022         0,  1,  2,  7,  8,  3,  9,  6,  5,  4,  4,  10, 10, 12, 10, 10, 10, 11, 10\r
2023     };\r
2024     private static final short _L  = 0;\r
2025     private static final short _R  = 1;\r
2026     private static final short _EN = 2;\r
2027     private static final short _AN = 3;\r
2028     private static final short _ON = 4;\r
2029     private static final short _S  = 5;\r
2030     private static final short _B  = 6; /* reduced dirProp */\r
2031 \r
2032     /*********************************************************************/\r
2033     /*                                                                   */\r
2034     /*      PROPERTIES  STATE  TABLE                                     */\r
2035     /*                                                                   */\r
2036     /* In table impTabProps,                                             */\r
2037     /*      - the ON column regroups ON and WS                           */\r
2038     /*      - the BN column regroups BN, LRE, RLE, LRO, RLO, PDF         */\r
2039     /*      - the Res column is the reduced property assigned to a run   */\r
2040     /*                                                                   */\r
2041     /* Action 1: process current run1, init new run1                     */\r
2042     /*        2: init new run2                                           */\r
2043     /*        3: process run1, process run2, init new run1               */\r
2044     /*        4: process run1, set run1=run2, init new run2              */\r
2045     /*                                                                   */\r
2046     /* Notes:                                                            */\r
2047     /*  1) This table is used in resolveImplicitLevels().                */\r
2048     /*  2) This table triggers actions when there is a change in the Bidi*/\r
2049     /*     property of incoming characters (action 1).                   */\r
2050     /*  3) Most such property sequences are processed immediately (in    */\r
2051     /*     fact, passed to processPropertySeq().                         */\r
2052     /*  4) However, numbers are assembled as one sequence. This means    */\r
2053     /*     that undefined situations (like CS following digits, until    */\r
2054     /*     it is known if the next char will be a digit) are held until  */\r
2055     /*     following chars define them.                                  */\r
2056     /*     Example: digits followed by CS, then comes another CS or ON;  */\r
2057     /*              the digits will be processed, then the CS assigned   */\r
2058     /*              as the start of an ON sequence (action 3).           */\r
2059     /*  5) There are cases where more than one sequence must be          */\r
2060     /*     processed, for instance digits followed by CS followed by L:  */\r
2061     /*     the digits must be processed as one sequence, and the CS      */\r
2062     /*     must be processed as an ON sequence, all this before starting */\r
2063     /*     assembling chars for the opening L sequence.                  */\r
2064     /*                                                                   */\r
2065     /*                                                                   */\r
2066     private static final short impTabProps[][] =\r
2067     {\r
2068 /*                        L,     R,    EN,    AN,    ON,     S,     B,    ES,    ET,    CS,    BN,   NSM,    AL,  Res */\r
2069 /* 0 Init        */ {     1,     2,     4,     5,     7,    15,    17,     7,     9,     7,     0,     7,     3,  _ON },\r
2070 /* 1 L           */ {     1,  32+2,  32+4,  32+5,  32+7, 32+15, 32+17,  32+7,  32+9,  32+7,     1,     1,  32+3,   _L },\r
2071 /* 2 R           */ {  32+1,     2,  32+4,  32+5,  32+7, 32+15, 32+17,  32+7,  32+9,  32+7,     2,     2,  32+3,   _R },\r
2072 /* 3 AL          */ {  32+1,  32+2,  32+6,  32+6,  32+8, 32+16, 32+17,  32+8,  32+8,  32+8,     3,     3,     3,   _R },\r
2073 /* 4 EN          */ {  32+1,  32+2,     4,  32+5,  32+7, 32+15, 32+17, 64+10,    11, 64+10,     4,     4,  32+3,  _EN },\r
2074 /* 5 AN          */ {  32+1,  32+2,  32+4,     5,  32+7, 32+15, 32+17,  32+7,  32+9, 64+12,     5,     5,  32+3,  _AN },\r
2075 /* 6 AL:EN/AN    */ {  32+1,  32+2,     6,     6,  32+8, 32+16, 32+17,  32+8,  32+8, 64+13,     6,     6,  32+3,  _AN },\r
2076 /* 7 ON          */ {  32+1,  32+2,  32+4,  32+5,     7, 32+15, 32+17,     7, 64+14,     7,     7,     7,  32+3,  _ON },\r
2077 /* 8 AL:ON       */ {  32+1,  32+2,  32+6,  32+6,     8, 32+16, 32+17,     8,     8,     8,     8,     8,  32+3,  _ON },\r
2078 /* 9 ET          */ {  32+1,  32+2,     4,  32+5,     7, 32+15, 32+17,     7,     9,     7,     9,     9,  32+3,  _ON },\r
2079 /*10 EN+ES/CS    */ {  96+1,  96+2,     4,  96+5, 128+7, 96+15, 96+17, 128+7,128+14, 128+7,    10, 128+7,  96+3,  _EN },\r
2080 /*11 EN+ET       */ {  32+1,  32+2,     4,  32+5,  32+7, 32+15, 32+17,  32+7,    11,  32+7,    11,    11,  32+3,  _EN },\r
2081 /*12 AN+CS       */ {  96+1,  96+2,  96+4,     5, 128+7, 96+15, 96+17, 128+7,128+14, 128+7,    12, 128+7,  96+3,  _AN },\r
2082 /*13 AL:EN/AN+CS */ {  96+1,  96+2,     6,     6, 128+8, 96+16, 96+17, 128+8, 128+8, 128+8,    13, 128+8,  96+3,  _AN },\r
2083 /*14 ON+ET       */ {  32+1,  32+2, 128+4,  32+5,     7, 32+15, 32+17,     7,    14,     7,    14,    14,  32+3,  _ON },\r
2084 /*15 S           */ {  32+1,  32+2,  32+4,  32+5,  32+7,    15, 32+17,  32+7,  32+9,  32+7,    15,  32+7,  32+3,   _S },\r
2085 /*16 AL:S        */ {  32+1,  32+2,  32+6,  32+6,  32+8,    16, 32+17,  32+8,  32+8,  32+8,    16,  32+8,  32+3,   _S },\r
2086 /*17 B           */ {  32+1,  32+2,  32+4,  32+5,  32+7, 32+15,    17,  32+7,  32+9,  32+7,    17,  32+7,  32+3,   _B }\r
2087     };\r
2088 \r
2089     /*********************************************************************/\r
2090     /* The levels state machine tables                                   */\r
2091     /*********************************************************************/\r
2092     /*                                                                   */\r
2093     /* All table cells are 8 bits:                                       */\r
2094     /*      bits 0..3:  next state                                       */\r
2095     /*      bits 4..7:  action to perform (if > 0)                       */\r
2096     /*                                                                   */\r
2097     /* Cells may be of format "n" where n represents the next state      */\r
2098     /* (except for the rightmost column).                                */\r
2099     /* Cells may also be of format "_(x,y)" where x represents an action */\r
2100     /* to perform and y represents the next state.                       */\r
2101     /*                                                                   */\r
2102     /* This format limits each table to 16 states each and to 15 actions.*/\r
2103     /*                                                                   */\r
2104     /*********************************************************************/\r
2105     /* Definitions and type for levels state tables                      */\r
2106     /*********************************************************************/\r
2107     private static final int IMPTABLEVELS_COLUMNS = _B + 2;\r
2108     private static final int IMPTABLEVELS_RES = IMPTABLEVELS_COLUMNS - 1;\r
2109     private static short GetState(byte cell) { return (short)(cell & 0x0f); }\r
2110     private static short GetAction(byte cell) { return (short)(cell >> 4); }\r
2111 \r
2112     private static class ImpTabPair {\r
2113         byte[][][] imptab;\r
2114         short[][] impact;\r
2115 \r
2116         ImpTabPair(byte[][] table1, byte[][] table2,\r
2117                    short[] act1, short[] act2) {\r
2118             imptab = new byte[][][] {table1, table2};\r
2119             impact = new short[][] {act1, act2};\r
2120         }\r
2121     }\r
2122 \r
2123     /*********************************************************************/\r
2124     /*                                                                   */\r
2125     /*      LEVELS  STATE  TABLES                                        */\r
2126     /*                                                                   */\r
2127     /* In all levels state tables,                                       */\r
2128     /*      - state 0 is the initial state                               */\r
2129     /*      - the Res column is the increment to add to the text level   */\r
2130     /*        for this property sequence.                                */\r
2131     /*                                                                   */\r
2132     /* The impact arrays for each table of a pair map the local action   */\r
2133     /* numbers of the table to the total list of actions. For instance,  */\r
2134     /* action 2 in a given table corresponds to the action number which  */\r
2135     /* appears in entry [2] of the impact array for that table.          */\r
2136     /* The first entry of all impact arrays must be 0.                   */\r
2137     /*                                                                   */\r
2138     /* Action 1: init conditional sequence                               */\r
2139     /*        2: prepend conditional sequence to current sequence        */\r
2140     /*        3: set ON sequence to new level - 1                        */\r
2141     /*        4: init EN/AN/ON sequence                                  */\r
2142     /*        5: fix EN/AN/ON sequence followed by R                     */\r
2143     /*        6: set previous level sequence to level 2                  */\r
2144     /*                                                                   */\r
2145     /* Notes:                                                            */\r
2146     /*  1) These tables are used in processPropertySeq(). The input      */\r
2147     /*     is property sequences as determined by resolveImplicitLevels. */\r
2148     /*  2) Most such property sequences are processed immediately        */\r
2149     /*     (levels are assigned).                                        */\r
2150     /*  3) However, some sequences cannot be assigned a final level till */\r
2151     /*     one or more following sequences are received. For instance,   */\r
2152     /*     ON following an R sequence within an even-level paragraph.    */\r
2153     /*     If the following sequence is R, the ON sequence will be       */\r
2154     /*     assigned basic run level+1, and so will the R sequence.       */\r
2155     /*  4) S is generally handled like ON, since its level will be fixed */\r
2156     /*     to paragraph level in adjustWSLevels().                       */\r
2157     /*                                                                   */\r
2158 \r
2159     private static final byte impTabL_DEFAULT[][] = /* Even paragraph level */\r
2160         /*  In this table, conditional sequences receive the higher possible level\r
2161             until proven otherwise.\r
2162         */\r
2163     {\r
2164         /*                         L,     R,    EN,    AN,    ON,     S,     B, Res */\r
2165         /* 0 : init       */ {     0,     1,     0,     2,     0,     0,     0,  0 },\r
2166         /* 1 : R          */ {     0,     1,     3,     3,  0x14,  0x14,     0,  1 },\r
2167         /* 2 : AN         */ {     0,     1,     0,     2,  0x15,  0x15,     0,  2 },\r
2168         /* 3 : R+EN/AN    */ {     0,     1,     3,     3,  0x14,  0x14,     0,  2 },\r
2169         /* 4 : R+ON       */ {  0x20,     1,     3,     3,     4,     4,  0x20,  1 },\r
2170         /* 5 : AN+ON      */ {  0x20,     1,  0x20,     2,     5,     5,  0x20,  1 }\r
2171     };\r
2172 \r
2173     private static final byte impTabR_DEFAULT[][] = /* Odd  paragraph level */\r
2174         /*  In this table, conditional sequences receive the lower possible level\r
2175             until proven otherwise.\r
2176         */\r
2177     {\r
2178         /*                         L,     R,    EN,    AN,    ON,     S,     B, Res */\r
2179         /* 0 : init       */ {     1,     0,     2,     2,     0,     0,     0,  0 },\r
2180         /* 1 : L          */ {     1,     0,     1,     3,  0x14,  0x14,     0,  1 },\r
2181         /* 2 : EN/AN      */ {     1,     0,     2,     2,     0,     0,     0,  1 },\r
2182         /* 3 : L+AN       */ {     1,     0,     1,     3,     5,     5,     0,  1 },\r
2183         /* 4 : L+ON       */ {  0x21,     0,  0x21,     3,     4,     4,     0,  0 },\r
2184         /* 5 : L+AN+ON    */ {     1,     0,     1,     3,     5,     5,     0,  0 }\r
2185     };\r
2186 \r
2187     private static final short[] impAct0 = {0,1,2,3,4,5,6};\r
2188 \r
2189     private static final ImpTabPair impTab_DEFAULT = new ImpTabPair(\r
2190             impTabL_DEFAULT, impTabR_DEFAULT, impAct0, impAct0);\r
2191 \r
2192     private static final byte impTabL_NUMBERS_SPECIAL[][] = { /* Even paragraph level */\r
2193         /* In this table, conditional sequences receive the higher possible\r
2194            level until proven otherwise.\r
2195         */\r
2196         /*                         L,     R,    EN,    AN,    ON,     S,     B, Res */\r
2197         /* 0 : init       */ {     0,     2,     1,     1,     0,     0,     0,  0 },\r
2198         /* 1 : L+EN/AN    */ {     0,     2,     1,     1,     0,     0,     0,  2 },\r
2199         /* 2 : R          */ {     0,     2,     4,     4,  0x13,     0,     0,  1 },\r
2200         /* 3 : R+ON       */ {  0x20,     2,     4,     4,     3,     3,  0x20,  1 },\r
2201         /* 4 : R+EN/AN    */ {     0,     2,     4,     4,  0x13,  0x13,     0,  2 }\r
2202     };\r
2203     private static final ImpTabPair impTab_NUMBERS_SPECIAL = new ImpTabPair(\r
2204             impTabL_NUMBERS_SPECIAL, impTabR_DEFAULT, impAct0, impAct0);\r
2205 \r
2206     private static final byte impTabL_GROUP_NUMBERS_WITH_R[][] = {\r
2207         /* In this table, EN/AN+ON sequences receive levels as if associated with R\r
2208            until proven that there is L or sor/eor on both sides. AN is handled like EN.\r
2209         */\r
2210         /*                         L,     R,    EN,    AN,    ON,     S,     B, Res */\r
2211         /* 0 init         */ {     0,     3,  0x11,  0x11,     0,     0,     0,  0 },\r
2212         /* 1 EN/AN        */ {  0x20,     3,     1,     1,     2,  0x20,  0x20,  2 },\r
2213         /* 2 EN/AN+ON     */ {  0x20,     3,     1,     1,     2,  0x20,  0x20,  1 },\r
2214         /* 3 R            */ {     0,     3,     5,     5,  0x14,     0,     0,  1 },\r
2215         /* 4 R+ON         */ {  0x20,     3,     5,     5,     4,  0x20,  0x20,  1 },\r
2216         /* 5 R+EN/AN      */ {     0,     3,     5,     5,  0x14,     0,     0,  2 }\r
2217     };\r
2218     private static final byte impTabR_GROUP_NUMBERS_WITH_R[][] = {\r
2219         /*  In this table, EN/AN+ON sequences receive levels as if associated with R\r
2220             until proven that there is L on both sides. AN is handled like EN.\r
2221         */\r
2222         /*                         L,     R,    EN,    AN,    ON,     S,     B, Res */\r
2223         /* 0 init         */ {     2,     0,     1,     1,     0,     0,     0,  0 },\r
2224         /* 1 EN/AN        */ {     2,     0,     1,     1,     0,     0,     0,  1 },\r
2225         /* 2 L            */ {     2,     0,  0x14,  0x14,  0x13,     0,     0,  1 },\r
2226         /* 3 L+ON         */ {  0x22,     0,     4,     4,     3,     0,     0,  0 },\r
2227         /* 4 L+EN/AN      */ {  0x22,     0,     4,     4,     3,     0,     0,  1 }\r
2228     };\r
2229     private static final ImpTabPair impTab_GROUP_NUMBERS_WITH_R = new\r
2230             ImpTabPair(impTabL_GROUP_NUMBERS_WITH_R,\r
2231                        impTabR_GROUP_NUMBERS_WITH_R, impAct0, impAct0);\r
2232 \r
2233     private static final byte impTabL_INVERSE_NUMBERS_AS_L[][] = {\r
2234         /* This table is identical to the Default LTR table except that EN and AN\r
2235            are handled like L.\r
2236         */\r
2237         /*                         L,     R,    EN,    AN,    ON,     S,     B, Res */\r
2238         /* 0 : init       */ {     0,     1,     0,     0,     0,     0,     0,  0 },\r
2239         /* 1 : R          */ {     0,     1,     0,     0,  0x14,  0x14,     0,  1 },\r
2240         /* 2 : AN         */ {     0,     1,     0,     0,  0x15,  0x15,     0,  2 },\r
2241         /* 3 : R+EN/AN    */ {     0,     1,     0,     0,  0x14,  0x14,     0,  2 },\r
2242         /* 4 : R+ON       */ {  0x20,     1,  0x20,  0x20,     4,     4,  0x20,  1 },\r
2243         /* 5 : AN+ON      */ {  0x20,     1,  0x20,  0x20,     5,     5,  0x20,  1 }\r
2244     };\r
2245     private static final byte impTabR_INVERSE_NUMBERS_AS_L[][] = {\r
2246         /* This table is identical to the Default RTL table except that EN and AN\r
2247            are handled like L.\r
2248         */\r
2249         /*                         L,     R,    EN,    AN,    ON,     S,     B, Res */\r
2250         /* 0 : init       */ {     1,     0,     1,     1,     0,     0,     0,  0 },\r
2251         /* 1 : L          */ {     1,     0,     1,     1,  0x14,  0x14,     0,  1 },\r
2252         /* 2 : EN/AN      */ {     1,     0,     1,     1,     0,     0,     0,  1 },\r
2253         /* 3 : L+AN       */ {     1,     0,     1,     1,     5,     5,     0,  1 },\r
2254         /* 4 : L+ON       */ {  0x21,     0,  0x21,  0x21,     4,     4,     0,  0 },\r
2255         /* 5 : L+AN+ON    */ {     1,     0,     1,     1,     5,     5,     0,  0 }\r
2256     };\r
2257     private static final ImpTabPair impTab_INVERSE_NUMBERS_AS_L = new ImpTabPair\r
2258             (impTabL_INVERSE_NUMBERS_AS_L, impTabR_INVERSE_NUMBERS_AS_L,\r
2259              impAct0, impAct0);\r
2260 \r
2261     private static final byte impTabR_INVERSE_LIKE_DIRECT[][] = {  /* Odd  paragraph level */\r
2262         /*  In this table, conditional sequences receive the lower possible level\r
2263             until proven otherwise.\r
2264         */\r
2265         /*                         L,     R,    EN,    AN,    ON,     S,     B, Res */\r
2266         /* 0 : init       */ {     1,     0,     2,     2,     0,     0,     0,  0 },\r
2267         /* 1 : L          */ {     1,     0,     1,     2,  0x13,  0x13,     0,  1 },\r
2268         /* 2 : EN/AN      */ {     1,     0,     2,     2,     0,     0,     0,  1 },\r
2269         /* 3 : L+ON       */ {  0x21,  0x30,     6,     4,     3,     3,  0x30,  0 },\r
2270         /* 4 : L+ON+AN    */ {  0x21,  0x30,     6,     4,     5,     5,  0x30,  3 },\r
2271         /* 5 : L+AN+ON    */ {  0x21,  0x30,     6,     4,     5,     5,  0x30,  2 },\r
2272         /* 6 : L+ON+EN    */ {  0x21,  0x30,     6,     4,     3,     3,  0x30,  1 }\r
2273     };\r
2274     private static final short[] impAct1 = {0,1,11,12};\r
2275     private static final ImpTabPair impTab_INVERSE_LIKE_DIRECT = new ImpTabPair(\r
2276             impTabL_DEFAULT, impTabR_INVERSE_LIKE_DIRECT, impAct0, impAct1);\r
2277 \r
2278     private static final byte impTabL_INVERSE_LIKE_DIRECT_WITH_MARKS[][] = {\r
2279         /* The case handled in this table is (visually):  R EN L\r
2280          */\r
2281         /*                         L,     R,    EN,    AN,    ON,     S,     B, Res */\r
2282         /* 0 : init       */ {     0,  0x63,     0,     1,     0,     0,     0,  0 },\r
2283         /* 1 : L+AN       */ {     0,  0x63,     0,     1,  0x12,  0x30,     0,  4 },\r
2284         /* 2 : L+AN+ON    */ {  0x20,  0x63,  0x20,     1,     2,  0x30,  0x20,  3 },\r
2285         /* 3 : R          */ {     0,  0x63,  0x55,  0x56,  0x14,  0x30,     0,  3 },\r
2286         /* 4 : R+ON       */ {  0x30,  0x43,  0x55,  0x56,     4,  0x30,  0x30,  3 },\r
2287         /* 5 : R+EN       */ {  0x30,  0x43,     5,  0x56,  0x14,  0x30,  0x30,  4 },\r
2288         /* 6 : R+AN       */ {  0x30,  0x43,  0x55,     6,  0x14,  0x30,  0x30,  4 }\r
2289     };\r
2290     private static final byte impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS[][] = {\r
2291         /* The cases handled in this table are (visually):  R EN L\r
2292                                                             R L AN L\r
2293         */\r
2294         /*                         L,     R,    EN,    AN,    ON,     S,     B, Res */\r
2295         /* 0 : init       */ {  0x13,     0,     1,     1,     0,     0,     0,  0 },\r
2296         /* 1 : R+EN/AN    */ {  0x23,     0,     1,     1,     2,  0x40,     0,  1 },\r
2297         /* 2 : R+EN/AN+ON */ {  0x23,     0,     1,     1,     2,  0x40,     0,  0 },\r
2298         /* 3 : L          */ {    3 ,     0,     3,  0x36,  0x14,  0x40,     0,  1 },\r
2299         /* 4 : L+ON       */ {  0x53,  0x40,     5,  0x36,     4,  0x40,  0x40,  0 },\r
2300         /* 5 : L+ON+EN    */ {  0x53,  0x40,     5,  0x36,     4,  0x40,  0x40,  1 },\r
2301         /* 6 : L+AN       */ {  0x53,  0x40,     6,     6,     4,  0x40,  0x40,  3 }\r
2302     };\r
2303     private static final short impAct2[] = {0,1,7,8,9,10};\r
2304     private static final ImpTabPair impTab_INVERSE_LIKE_DIRECT_WITH_MARKS =\r
2305             new ImpTabPair(impTabL_INVERSE_LIKE_DIRECT_WITH_MARKS,\r
2306                            impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS, impAct0, impAct2);\r
2307 \r
2308     private static final ImpTabPair impTab_INVERSE_FOR_NUMBERS_SPECIAL = new ImpTabPair(\r
2309             impTabL_NUMBERS_SPECIAL, impTabR_INVERSE_LIKE_DIRECT, impAct0, impAct1);\r
2310 \r
2311     private static final byte impTabL_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS[][] = {\r
2312         /*  The case handled in this table is (visually):  R EN L\r
2313         */\r
2314         /*                         L,     R,    EN,    AN,    ON,     S,     B, Res */\r
2315         /* 0 : init       */ {     0,  0x62,     1,     1,     0,     0,     0,  0 },\r
2316         /* 1 : L+EN/AN    */ {     0,  0x62,     1,     1,     0,  0x30,     0,  4 },\r
2317         /* 2 : R          */ {     0,  0x62,  0x54,  0x54,  0x13,  0x30,     0,  3 },\r
2318         /* 3 : R+ON       */ {  0x30,  0x42,  0x54,  0x54,     3,  0x30,  0x30,  3 },\r
2319         /* 4 : R+EN/AN    */ {  0x30,  0x42,     4,     4,  0x13,  0x30,  0x30,  4 }\r
2320     };\r
2321     private static final ImpTabPair impTab_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS = new\r
2322             ImpTabPair(impTabL_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS,\r
2323                        impTabR_INVERSE_LIKE_DIRECT_WITH_MARKS, impAct0, impAct2);\r
2324 \r
2325     private class LevState {\r
2326         byte[][] impTab;                /* level table pointer          */\r
2327         short[] impAct;                 /* action map array             */\r
2328         int startON;                    /* start of ON sequence         */\r
2329         int startL2EN;                  /* start of level 2 sequence    */\r
2330         int lastStrongRTL;              /* index of last found R or AL  */\r
2331         short state;                    /* current state                */\r
2332         byte runLevel;                  /* run level before implicit solving */\r
2333     }\r
2334 \r
2335     /*------------------------------------------------------------------------*/\r
2336 \r
2337     static final int FIRSTALLOC = 10;\r
2338     /*\r
2339      *  param pos:     position where to insert\r
2340      *  param flag:    one of LRM_BEFORE, LRM_AFTER, RLM_BEFORE, RLM_AFTER\r
2341      */\r
2342     private void addPoint(int pos, int flag)\r
2343     {\r
2344         Point point = new Point();\r
2345 \r
2346         int len = insertPoints.points.length;\r
2347         if (len == 0) {\r
2348             insertPoints.points = new Point[FIRSTALLOC];\r
2349             len = FIRSTALLOC;\r
2350         }\r
2351         if (insertPoints.size >= len) { /* no room for new point */\r
2352             Point[] savePoints = insertPoints.points;\r
2353             insertPoints.points = new Point[len * 2];\r
2354             System.arraycopy(savePoints, 0, insertPoints.points, 0, len);\r
2355         }\r
2356         point.pos = pos;\r
2357         point.flag = flag;\r
2358         insertPoints.points[insertPoints.size] = point;\r
2359         insertPoints.size++;\r
2360     }\r
2361 \r
2362     /* perform rules (Wn), (Nn), and (In) on a run of the text ------------------ */\r
2363 \r
2364     /*\r
2365      * This implementation of the (Wn) rules applies all rules in one pass.\r
2366      * In order to do so, it needs a look-ahead of typically 1 character\r
2367      * (except for W5: sequences of ET) and keeps track of changes\r
2368      * in a rule Wp that affect a later Wq (p<q).\r
2369      *\r
2370      * The (Nn) and (In) rules are also performed in that same single loop,\r
2371      * but effectively one iteration behind for white space.\r
2372      *\r
2373      * Since all implicit rules are performed in one step, it is not necessary\r
2374      * to actually store the intermediate directional properties in dirProps[].\r
2375      */\r
2376 \r
2377     private void processPropertySeq(LevState levState, short _prop,\r
2378             int start, int limit) {\r
2379         byte cell;\r
2380         byte[][] impTab = levState.impTab;\r
2381         short[] impAct = levState.impAct;\r
2382         short oldStateSeq,actionSeq;\r
2383         byte level, addLevel;\r
2384         int start0, k;\r
2385 \r
2386         start0 = start;                 /* save original start position */\r
2387         oldStateSeq = levState.state;\r
2388         cell = impTab[oldStateSeq][_prop];\r
2389         levState.state = GetState(cell);        /* isolate the new state */\r
2390         actionSeq = impAct[GetAction(cell)];    /* isolate the action */\r
2391         addLevel = impTab[levState.state][IMPTABLEVELS_RES];\r
2392 \r
2393         if (actionSeq != 0) {\r
2394             switch (actionSeq) {\r
2395             case 1:                     /* init ON seq */\r
2396                 levState.startON = start0;\r
2397                 break;\r
2398 \r
2399             case 2:                     /* prepend ON seq to current seq */\r
2400                 start = levState.startON;\r
2401                 break;\r
2402 \r
2403             case 3:                     /* L or S after possible relevant EN/AN */\r
2404                 /* check if we had EN after R/AL */\r
2405                 if (levState.startL2EN >= 0) {\r
2406                     addPoint(levState.startL2EN, LRM_BEFORE);\r
2407                 }\r
2408                 levState.startL2EN = -1;  /* not within previous if since could also be -2 */\r
2409                 /* check if we had any relevant EN/AN after R/AL */\r
2410                 if ((insertPoints.points.length == 0) ||\r
2411                         (insertPoints.size <= insertPoints.confirmed)) {\r
2412                     /* nothing, just clean up */\r
2413                     levState.lastStrongRTL = -1;\r
2414                     /* check if we have a pending conditional segment */\r
2415                     level = impTab[oldStateSeq][IMPTABLEVELS_RES];\r
2416                     if ((level & 1) != 0 && levState.startON > 0) { /* after ON */\r
2417                         start = levState.startON;   /* reset to basic run level */\r
2418                     }\r
2419                     if (_prop == _S) {              /* add LRM before S */\r
2420                         addPoint(start0, LRM_BEFORE);\r
2421                         insertPoints.confirmed = insertPoints.size;\r
2422                     }\r
2423                     break;\r
2424                 }\r
2425                 /* reset previous RTL cont to level for LTR text */\r
2426                 for (k = levState.lastStrongRTL + 1; k < start0; k++) {\r
2427                     /* reset odd level, leave runLevel+2 as is */\r
2428                     levels[k] = (byte)((levels[k] - 2) & ~1);\r
2429                 }\r
2430                 /* mark insert points as confirmed */\r
2431                 insertPoints.confirmed = insertPoints.size;\r
2432                 levState.lastStrongRTL = -1;\r
2433                 if (_prop == _S) {           /* add LRM before S */\r
2434                     addPoint(start0, LRM_BEFORE);\r
2435                     insertPoints.confirmed = insertPoints.size;\r
2436                 }\r
2437                 break;\r
2438 \r
2439             case 4:                     /* R/AL after possible relevant EN/AN */\r
2440                 /* just clean up */\r
2441                 if (insertPoints.points.length > 0)\r
2442                     /* remove all non confirmed insert points */\r
2443                     insertPoints.size = insertPoints.confirmed;\r
2444                 levState.startON = -1;\r
2445                 levState.startL2EN = -1;\r
2446                 levState.lastStrongRTL = limit - 1;\r
2447                 break;\r
2448 \r
2449             case 5:                     /* EN/AN after R/AL + possible cont */\r
2450                 /* check for real AN */\r
2451                 if ((_prop == _AN) && (NoContextRTL(dirProps[start0]) == AN) &&\r
2452                 (reorderingMode!=REORDER_INVERSE_FOR_NUMBERS_SPECIAL))\r
2453                 {\r
2454                     /* real AN */\r
2455                     if (levState.startL2EN == -1) { /* if no relevant EN already found */\r
2456                         /* just note the righmost digit as a strong RTL */\r
2457                         levState.lastStrongRTL = limit - 1;\r
2458                         break;\r
2459                     }\r
2460                     if (levState.startL2EN >= 0)  { /* after EN, no AN */\r
2461                         addPoint(levState.startL2EN, LRM_BEFORE);\r
2462                         levState.startL2EN = -2;\r
2463                     }\r
2464                     /* note AN */\r
2465                     addPoint(start0, LRM_BEFORE);\r
2466                     break;\r
2467                 }\r
2468                 /* if first EN/AN after R/AL */\r
2469                 if (levState.startL2EN == -1) {\r
2470                     levState.startL2EN = start0;\r
2471                 }\r
2472                 break;\r
2473 \r
2474             case 6:                     /* note location of latest R/AL */\r
2475                 levState.lastStrongRTL = limit - 1;\r
2476                 levState.startON = -1;\r
2477                 break;\r
2478 \r
2479             case 7:                     /* L after R+ON/EN/AN */\r
2480                 /* include possible adjacent number on the left */\r
2481                 for (k = start0-1; k >= 0 && ((levels[k] & 1) == 0); k--) {\r
2482                 }\r
2483                 if (k >= 0) {\r
2484                     addPoint(k, RLM_BEFORE);    /* add RLM before */\r
2485                     insertPoints.confirmed = insertPoints.size; /* confirm it */\r
2486                 }\r
2487                 levState.startON = start0;\r
2488                 break;\r
2489 \r
2490             case 8:                     /* AN after L */\r
2491                 /* AN numbers between L text on both sides may be trouble. */\r
2492                 /* tentatively bracket with LRMs; will be confirmed if followed by L */\r
2493                 addPoint(start0, LRM_BEFORE);   /* add LRM before */\r
2494                 addPoint(start0, LRM_AFTER);    /* add LRM after  */\r
2495                 break;\r
2496 \r
2497             case 9:                     /* R after L+ON/EN/AN */\r
2498                 /* false alert, infirm LRMs around previous AN */\r
2499                 insertPoints.size=insertPoints.confirmed;\r
2500                 if (_prop == _S) {          /* add RLM before S */\r
2501                     addPoint(start0, RLM_BEFORE);\r
2502                     insertPoints.confirmed = insertPoints.size;\r
2503                 }\r
2504                 break;\r
2505 \r
2506             case 10:                    /* L after L+ON/AN */\r
2507                 level = (byte)(levState.runLevel + addLevel);\r
2508                 for (k=levState.startON; k < start0; k++) {\r
2509                     if (levels[k] < level) {\r
2510                         levels[k] = level;\r
2511                     }\r
2512                 }\r
2513                 insertPoints.confirmed = insertPoints.size;   /* confirm inserts */\r
2514                 levState.startON = start0;\r
2515                 break;\r
2516 \r
2517             case 11:                    /* L after L+ON+EN/AN/ON */\r
2518                 level = levState.runLevel;\r
2519                 for (k = start0-1; k >= levState.startON; k--) {\r
2520                     if (levels[k] == level+3) {\r
2521                         while (levels[k] == level+3) {\r
2522                             levels[k--] -= 2;\r
2523                         }\r
2524                         while (levels[k] == level) {\r
2525                             k--;\r
2526                         }\r
2527                     }\r
2528                     if (levels[k] == level+2) {\r
2529                         levels[k] = level;\r
2530                         continue;\r
2531                     }\r
2532                     levels[k] = (byte)(level+1);\r
2533                 }\r
2534                 break;\r
2535 \r
2536             case 12:                    /* R after L+ON+EN/AN/ON */\r
2537                 level = (byte)(levState.runLevel+1);\r
2538                 for (k = start0-1; k >= levState.startON; k--) {\r
2539                     if (levels[k] > level) {\r
2540                         levels[k] -= 2;\r
2541                     }\r
2542                 }\r
2543                 break;\r
2544 \r
2545             default:                        /* we should never get here */\r
2546                 throw new IllegalStateException("Internal ICU error in processPropertySeq");\r
2547             }\r
2548         }\r
2549         if ((addLevel) != 0 || (start < start0)) {\r
2550             level = (byte)(levState.runLevel + addLevel);\r
2551             for (k = start; k < limit; k++) {\r
2552                 levels[k] = level;\r
2553             }\r
2554         }\r
2555     }\r
2556 \r
2557     private void resolveImplicitLevels(int start, int limit, short sor, short eor)\r
2558     {\r
2559         LevState levState = new LevState();\r
2560         int i, start1, start2;\r
2561         short oldStateImp, stateImp, actionImp;\r
2562         short gprop, resProp, cell;\r
2563         boolean inverseRTL;\r
2564         short nextStrongProp = R;\r
2565         int nextStrongPos = -1;\r
2566 \r
2567 \r
2568         /* check for RTL inverse Bidi mode */\r
2569         /* FOOD FOR THOUGHT: in case of RTL inverse Bidi, it would make sense to\r
2570          * loop on the text characters from end to start.\r
2571          * This would need a different properties state table (at least different\r
2572          * actions) and different levels state tables (maybe very similar to the\r
2573          * LTR corresponding ones.\r
2574          */\r
2575         inverseRTL=((start<lastArabicPos) && ((GetParaLevelAt(start) & 1)>0) &&\r
2576                     (reorderingMode==REORDER_INVERSE_LIKE_DIRECT  ||\r
2577                      reorderingMode==REORDER_INVERSE_FOR_NUMBERS_SPECIAL));\r
2578         /* initialize for levels state table */\r
2579         levState.startL2EN = -1;        /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */\r
2580         levState.lastStrongRTL = -1;    /* used for INVERSE_LIKE_DIRECT_WITH_MARKS */\r
2581         levState.state = 0;\r
2582         levState.runLevel = levels[start];\r
2583         levState.impTab = impTabPair.imptab[levState.runLevel & 1];\r
2584         levState.impAct = impTabPair.impact[levState.runLevel & 1];\r
2585         processPropertySeq(levState, sor, start, start);\r
2586         /* initialize for property state table */\r
2587         if (dirProps[start] == NSM) {\r
2588             stateImp = (short)(1 + sor);\r
2589         } else {\r
2590             stateImp = 0;\r
2591         }\r
2592         start1 = start;\r
2593         start2 = 0;\r
2594 \r
2595         for (i = start; i <= limit; i++) {\r
2596             if (i >= limit) {\r
2597                 gprop = eor;\r
2598             } else {\r
2599                 short prop, prop1;\r
2600                 prop = NoContextRTL(dirProps[i]);\r
2601                 if (inverseRTL) {\r
2602                     if (prop == AL) {\r
2603                         /* AL before EN does not make it AN */\r
2604                         prop = R;\r
2605                     } else if (prop == EN) {\r
2606                         if (nextStrongPos <= i) {\r
2607                             /* look for next strong char (L/R/AL) */\r
2608                             int j;\r
2609                             nextStrongProp = R;     /* set default */\r
2610                             nextStrongPos = limit;\r
2611                             for (j = i+1; j < limit; j++) {\r
2612                                 prop1 = NoContextRTL(dirProps[j]);\r
2613                                 if (prop1 == L || prop1 == R || prop1 == AL) {\r
2614                                     nextStrongProp = prop1;\r
2615                                     nextStrongPos = j;\r
2616                                     break;\r
2617                                 }\r
2618                             }\r
2619                         }\r
2620                         if (nextStrongProp == AL) {\r
2621                             prop = AN;\r
2622                         }\r
2623                     }\r
2624                 }\r
2625                 gprop = groupProp[prop];\r
2626             }\r
2627             oldStateImp = stateImp;\r
2628             cell = impTabProps[oldStateImp][gprop];\r
2629             stateImp = GetStateProps(cell);     /* isolate the new state */\r
2630             actionImp = GetActionProps(cell);   /* isolate the action */\r
2631             if ((i == limit) && (actionImp == 0)) {\r
2632                 /* there is an unprocessed sequence if its property == eor   */\r
2633                 actionImp = 1;                  /* process the last sequence */\r
2634             }\r
2635             if (actionImp != 0) {\r
2636                 resProp = impTabProps[oldStateImp][IMPTABPROPS_RES];\r
2637                 switch (actionImp) {\r
2638                 case 1:             /* process current seq1, init new seq1 */\r
2639                     processPropertySeq(levState, resProp, start1, i);\r
2640                     start1 = i;\r
2641                     break;\r
2642                 case 2:             /* init new seq2 */\r
2643                     start2 = i;\r
2644                     break;\r
2645                 case 3:             /* process seq1, process seq2, init new seq1 */\r
2646                     processPropertySeq(levState, resProp, start1, start2);\r
2647                     processPropertySeq(levState, _ON, start2, i);\r
2648                     start1 = i;\r
2649                     break;\r
2650                 case 4:             /* process seq1, set seq1=seq2, init new seq2 */\r
2651                     processPropertySeq(levState, resProp, start1, start2);\r
2652                     start1 = start2;\r
2653                     start2 = i;\r
2654                     break;\r
2655                 default:            /* we should never get here */\r
2656                     throw new IllegalStateException("Internal ICU error in resolveImplicitLevels");\r
2657                 }\r
2658             }\r
2659         }\r
2660         /* flush possible pending sequence, e.g. ON */\r
2661         processPropertySeq(levState, eor, limit, limit);\r
2662     }\r
2663 \r
2664     /* perform (L1) and (X9) ---------------------------------------------------- */\r
2665 \r
2666     /*\r
2667      * Reset the embedding levels for some non-graphic characters (L1).\r
2668      * This method also sets appropriate levels for BN, and\r
2669      * explicit embedding types that are supposed to have been removed\r
2670      * from the paragraph in (X9).\r
2671      */\r
2672     private void adjustWSLevels() {\r
2673         int i;\r
2674 \r
2675         if ((flags & MASK_WS) != 0) {\r
2676             int flag;\r
2677             i = trailingWSStart;\r
2678             while (i > 0) {\r
2679                 /* reset a sequence of WS/BN before eop and B/S to the paragraph paraLevel */\r
2680                 while (i > 0 && ((flag = DirPropFlagNC(dirProps[--i])) & MASK_WS) != 0) {\r
2681                     if (orderParagraphsLTR && (flag & DirPropFlag(B)) != 0) {\r
2682                         levels[i] = 0;\r
2683                     } else {\r
2684                         levels[i] = GetParaLevelAt(i);\r
2685                     }\r
2686                 }\r
2687 \r
2688                 /* reset BN to the next character's paraLevel until B/S, which restarts above loop */\r
2689                 /* here, i+1 is guaranteed to be <length */\r
2690                 while (i > 0) {\r
2691                     flag = DirPropFlagNC(dirProps[--i]);\r
2692                     if ((flag & MASK_BN_EXPLICIT) != 0) {\r
2693                         levels[i] = levels[i + 1];\r
2694                     } else if (orderParagraphsLTR && (flag & DirPropFlag(B)) != 0) {\r
2695                         levels[i] = 0;\r
2696                         break;\r
2697                     } else if ((flag & MASK_B_S) != 0){\r
2698                         levels[i] = GetParaLevelAt(i);\r
2699                         break;\r
2700                     }\r
2701                 }\r
2702             }\r
2703         }\r
2704     }\r
2705 \r
2706     int Bidi_Min(int x, int y) {\r
2707         return x < y ? x : y;\r
2708     }\r
2709 \r
2710     int Bidi_Abs(int x) {\r
2711         return x >= 0 ? x : -x;\r
2712     }\r
2713 \r
2714     void setParaRunsOnly(char[] parmText, byte parmParaLevel) {\r
2715         int[] visualMap;\r
2716         String visualText;\r
2717         int saveLength, saveTrailingWSStart;\r
2718         byte[] saveLevels;\r
2719         byte saveDirection;\r
2720         int i, j, visualStart, logicalStart,\r
2721             oldRunCount, runLength, addedRuns, insertRemove,\r
2722             start, limit, step, indexOddBit, logicalPos,\r
2723             index, index1;\r
2724         int saveOptions;\r
2725 \r
2726         reorderingMode = REORDER_DEFAULT;\r
2727         int parmLength = parmText.length;\r
2728         if (parmLength == 0) {\r
2729             setPara(parmText, parmParaLevel, null);\r
2730             reorderingMode = REORDER_RUNS_ONLY;\r
2731             return;\r
2732         }\r
2733         /* obtain memory for mapping table and visual text */\r
2734         saveOptions = reorderingOptions;\r
2735         if ((saveOptions & OPTION_INSERT_MARKS) > 0) {\r
2736             reorderingOptions &= ~OPTION_INSERT_MARKS;\r
2737             reorderingOptions |= OPTION_REMOVE_CONTROLS;\r
2738         }\r
2739         parmParaLevel &= 1;             /* accept only 0 or 1 */\r
2740         setPara(parmText, parmParaLevel, null);\r
2741         /* we cannot access directly pBiDi->levels since it is not yet set if\r
2742          * direction is not MIXED\r
2743          */\r
2744         saveLevels = new byte[this.length];\r
2745         System.arraycopy(getLevels(), 0, saveLevels, 0, this.length);\r
2746         saveTrailingWSStart = trailingWSStart;\r
2747 \r
2748         /* FOOD FOR THOUGHT: instead of writing the visual text, we could use\r
2749          * the visual map and the dirProps array to drive the second call\r
2750          * to setPara (but must make provision for possible removal of\r
2751          * Bidi controls.  Alternatively, only use the dirProps array via\r
2752          * customized classifier callback.\r
2753          */\r
2754         visualText = writeReordered(DO_MIRRORING);\r
2755         visualMap = getVisualMap();\r
2756         this.reorderingOptions = saveOptions;\r
2757         saveLength = this.length;\r
2758         saveDirection=this.direction;\r
2759 \r
2760         this.reorderingMode = REORDER_INVERSE_LIKE_DIRECT;\r
2761         parmParaLevel ^= 1;\r
2762         setPara(visualText, parmParaLevel, null);\r
2763         BidiLine.getRuns(this);\r
2764         /* check if some runs must be split, count how many splits */\r
2765         addedRuns = 0;\r
2766         oldRunCount = this.runCount;\r
2767         visualStart = 0;\r
2768         for (i = 0; i < oldRunCount; i++, visualStart += runLength) {\r
2769             runLength = runs[i].limit - visualStart;\r
2770             if (runLength < 2) {\r
2771                 continue;\r
2772             }\r
2773             logicalStart = runs[i].start;\r
2774             for (j = logicalStart+1; j < logicalStart+runLength; j++) {\r
2775                 index = visualMap[j];\r
2776                 index1 = visualMap[j-1];\r
2777                 if ((Bidi_Abs(index-index1)!=1) || (saveLevels[index]!=saveLevels[index1])) {\r
2778                     addedRuns++;\r
2779                 }\r
2780             }\r
2781         }\r
2782         if (addedRuns > 0) {\r
2783             getRunsMemory(oldRunCount + addedRuns);\r
2784             if (runCount == 1) {\r
2785                 /* because we switch from UBiDi.simpleRuns to UBiDi.runs */\r
2786                 runsMemory[0] = runs[0];\r
2787             } else {\r
2788                 System.arraycopy(runs, 0, runsMemory, 0, runCount);\r
2789             }\r
2790             runs = runsMemory;\r
2791             runCount += addedRuns;\r
2792             for (i = oldRunCount; i < runCount; i++) {\r
2793                 if (runs[i] == null) {\r
2794                     runs[i] = new BidiRun(0, 0, (byte)0);\r
2795                 }\r
2796             }\r
2797         }\r
2798         /* split runs which are not consecutive in source text */\r
2799         int newI;\r
2800         for (i = oldRunCount-1; i >= 0; i--) {\r
2801             newI = i + addedRuns;\r
2802             runLength = i==0 ? runs[0].limit :\r
2803                                runs[i].limit - runs[i-1].limit;\r
2804             logicalStart = runs[i].start;\r
2805             indexOddBit = runs[i].level & 1;\r
2806             if (runLength < 2) {\r
2807                 if (addedRuns > 0) {\r
2808                     runs[newI].copyFrom(runs[i]);\r
2809                 }\r
2810                 logicalPos = visualMap[logicalStart];\r
2811                 runs[newI].start = logicalPos;\r
2812                 runs[newI].level = (byte)(saveLevels[logicalPos] ^ indexOddBit);\r
2813                 continue;\r
2814             }\r
2815             if (indexOddBit > 0) {\r
2816                 start = logicalStart;\r
2817                 limit = logicalStart + runLength - 1;\r
2818                 step = 1;\r
2819             } else {\r
2820                 start = logicalStart + runLength - 1;\r
2821                 limit = logicalStart;\r
2822                 step = -1;\r
2823             }\r
2824             for (j = start; j != limit; j += step) {\r
2825                 index = visualMap[j];\r
2826                 index1 = visualMap[j+step];\r
2827                 if ((Bidi_Abs(index-index1)!=1) || (saveLevels[index]!=saveLevels[index1])) {\r
2828                     logicalPos = Bidi_Min(visualMap[start], index);\r
2829                     runs[newI].start = logicalPos;\r
2830                     runs[newI].level = (byte)(saveLevels[logicalPos] ^ indexOddBit);\r
2831                     runs[newI].limit = runs[i].limit;\r
2832                     runs[i].limit -= Bidi_Abs(j - start) + 1;\r
2833                     insertRemove = runs[i].insertRemove & (LRM_AFTER|RLM_AFTER);\r
2834                     runs[newI].insertRemove = insertRemove;\r
2835                     runs[i].insertRemove &= ~insertRemove;\r
2836                     start = j + step;\r
2837                     addedRuns--;\r
2838                     newI--;\r
2839                 }\r
2840             }\r
2841             if (addedRuns > 0) {\r
2842                 runs[newI].copyFrom(runs[i]);\r
2843             }\r
2844             logicalPos = Bidi_Min(visualMap[start], visualMap[limit]);\r
2845             runs[newI].start = logicalPos;\r
2846             runs[newI].level = (byte)(saveLevels[logicalPos] ^ indexOddBit);\r
2847         }\r
2848 \r
2849 //    cleanup1:\r
2850         /* restore initial paraLevel */\r
2851         this.paraLevel ^= 1;\r
2852 //    cleanup2:\r
2853         /* restore real text */\r
2854         this.text = parmText;\r
2855         this.length = saveLength;\r
2856         this.originalLength = parmLength;\r
2857         this.direction=saveDirection;\r
2858         this.levels = saveLevels;\r
2859         this.trailingWSStart = saveTrailingWSStart;\r
2860         /* free memory for mapping table and visual text */\r
2861         visualMap = null;\r
2862         visualText = null;\r
2863         if (runCount > 1) {\r
2864             this.direction = MIXED;\r
2865         }\r
2866 //    cleanup3:\r
2867         this.reorderingMode = REORDER_RUNS_ONLY;\r
2868     }\r
2869 \r
2870     /**\r
2871      * Perform the Unicode Bidi algorithm. It is defined in the\r
2872      * <a href="http://www.unicode.org/unicode/reports/tr9/">Unicode Standard Annex #9</a>,\r
2873      * version 13,\r
2874      * also described in The Unicode Standard, Version 4.0 .<p>\r
2875      *\r
2876      * This method takes a piece of plain text containing one or more paragraphs,\r
2877      * with or without externally specified embedding levels from <i>styled</i>\r
2878      * text and computes the left-right-directionality of each character.<p>\r
2879      *\r
2880      * If the entire text is all of the same directionality, then\r
2881      * the method may not perform all the steps described by the algorithm,\r
2882      * i.e., some levels may not be the same as if all steps were performed.\r
2883      * This is not relevant for unidirectional text.<br>\r
2884      * For example, in pure LTR text with numbers the numbers would get\r
2885      * a resolved level of 2 higher than the surrounding text according to\r
2886      * the algorithm. This implementation may set all resolved levels to\r
2887      * the same value in such a case.<p>\r
2888      *\r
2889      * The text can be composed of multiple paragraphs. Occurrence of a block\r
2890      * separator in the text terminates a paragraph, and whatever comes next starts\r
2891      * a new paragraph. The exception to this rule is when a Carriage Return (CR)\r
2892      * is followed by a Line Feed (LF). Both CR and LF are block separators, but\r
2893      * in that case, the pair of characters is considered as terminating the\r
2894      * preceding paragraph, and a new paragraph will be started by a character\r
2895      * coming after the LF.\r
2896      *\r
2897      * Although the text is passed here as a <code>String</code>, it is\r
2898      * stored internally as an array of characters. Therefore the\r
2899      * documentation will refer to indexes of the characters in the text.\r
2900      *\r
2901      * @param text contains the text that the Bidi algorithm will be performed\r
2902      *        on. This text can be retrieved with <code>getText()</code> or\r
2903      *        <code>getTextAsString</code>.<br>\r
2904      *\r
2905      * @param paraLevel specifies the default level for the text;\r
2906      *        it is typically 0 (LTR) or 1 (RTL).\r
2907      *        If the method shall determine the paragraph level from the text,\r
2908      *        then <code>paraLevel</code> can be set to\r
2909      *        either <code>LEVEL_DEFAULT_LTR</code>\r
2910      *        or <code>LEVEL_DEFAULT_RTL</code>; if the text contains multiple\r
2911      *        paragraphs, the paragraph level shall be determined separately for\r
2912      *        each paragraph; if a paragraph does not include any strongly typed\r
2913      *        character, then the desired default is used (0 for LTR or 1 for RTL).\r
2914      *        Any other value between 0 and <code>MAX_EXPLICIT_LEVEL</code>\r
2915      *        is also valid, with odd levels indicating RTL.\r
2916      *\r
2917      * @param embeddingLevels (in) may be used to preset the embedding and override levels,\r
2918      *        ignoring characters like LRE and PDF in the text.\r
2919      *        A level overrides the directional property of its corresponding\r
2920      *        (same index) character if the level has the\r
2921      *        <code>LEVEL_OVERRIDE</code> bit set.<br><br>\r
2922      *        Except for that bit, it must be\r
2923      *        <code>paraLevel<=embeddingLevels[]<=MAX_EXPLICIT_LEVEL</code>,\r
2924      *        with one exception: a level of zero may be specified for a\r
2925      *        paragraph separator even if <code>paraLevel&gt;0</code> when multiple\r
2926      *        paragraphs are submitted in the same call to <code>setPara()</code>.<br><br>\r
2927      *        <strong>Caution: </strong>A reference to this array, not a copy\r
2928      *        of the levels, will be stored in the <code>Bidi</code> object;\r
2929      *        the <code>embeddingLevels</code>\r
2930      *        should not be modified to avoid unexpected results on subsequent\r
2931      *        Bidi operations. However, the <code>setPara()</code> and\r
2932      *        <code>setLine()</code> methods may modify some or all of the\r
2933      *        levels.<br><br>\r
2934      *        <strong>Note:</strong> the <code>embeddingLevels</code> array must\r
2935      *        have one entry for each character in <code>text</code>.\r
2936      *\r
2937      * @throws IllegalArgumentException if the values in embeddingLevels are\r
2938      *         not within the allowed range\r
2939      *\r
2940      * @see #LEVEL_DEFAULT_LTR\r
2941      * @see #LEVEL_DEFAULT_RTL\r
2942      * @see #LEVEL_OVERRIDE\r
2943      * @see #MAX_EXPLICIT_LEVEL\r
2944      * @stable ICU 3.8\r
2945      */\r
2946     public void setPara(String text, byte paraLevel, byte[] embeddingLevels)\r
2947     {\r
2948         if (text == null) {\r
2949             setPara(new char[0], paraLevel, embeddingLevels);\r
2950         } else {\r
2951             setPara(text.toCharArray(), paraLevel, embeddingLevels);\r
2952         }\r
2953     }\r
2954 \r
2955     /**\r
2956      * Perform the Unicode Bidi algorithm. It is defined in the\r
2957      * <a href="http://www.unicode.org/unicode/reports/tr9/">Unicode Standard Annex #9</a>,\r
2958      * version 13,\r
2959      * also described in The Unicode Standard, Version 4.0 .<p>\r
2960      *\r
2961      * This method takes a piece of plain text containing one or more paragraphs,\r
2962      * with or without externally specified embedding levels from <i>styled</i>\r
2963      * text and computes the left-right-directionality of each character.<p>\r
2964      *\r
2965      * If the entire text is all of the same directionality, then\r
2966      * the method may not perform all the steps described by the algorithm,\r
2967      * i.e., some levels may not be the same as if all steps were performed.\r
2968      * This is not relevant for unidirectional text.<br>\r
2969      * For example, in pure LTR text with numbers the numbers would get\r
2970      * a resolved level of 2 higher than the surrounding text according to\r
2971      * the algorithm. This implementation may set all resolved levels to\r
2972      * the same value in such a case.<p>\r
2973      *\r
2974      * The text can be composed of multiple paragraphs. Occurrence of a block\r
2975      * separator in the text terminates a paragraph, and whatever comes next starts\r
2976      * a new paragraph. The exception to this rule is when a Carriage Return (CR)\r
2977      * is followed by a Line Feed (LF). Both CR and LF are block separators, but\r
2978      * in that case, the pair of characters is considered as terminating the\r
2979      * preceding paragraph, and a new paragraph will be started by a character\r
2980      * coming after the LF.\r
2981      *\r
2982      * The text is stored internally as an array of characters. Therefore the\r
2983      * documentation will refer to indexes of the characters in the text.\r
2984      *\r
2985      * @param chars contains the text that the Bidi algorithm will be performed\r
2986      *        on. This text can be retrieved with <code>getText()</code> or\r
2987      *        <code>getTextAsString</code>.<br>\r
2988      *\r
2989      * @param paraLevel specifies the default level for the text;\r
2990      *        it is typically 0 (LTR) or 1 (RTL).\r
2991      *        If the method shall determine the paragraph level from the text,\r
2992      *        then <code>paraLevel</code> can be set to\r
2993      *        either <code>LEVEL_DEFAULT_LTR</code>\r
2994      *        or <code>LEVEL_DEFAULT_RTL</code>; if the text contains multiple\r
2995      *        paragraphs, the paragraph level shall be determined separately for\r
2996      *        each paragraph; if a paragraph does not include any strongly typed\r
2997      *        character, then the desired default is used (0 for LTR or 1 for RTL).\r
2998      *        Any other value between 0 and <code>MAX_EXPLICIT_LEVEL</code>\r
2999      *        is also valid, with odd levels indicating RTL.\r
3000      *\r
3001      * @param embeddingLevels (in) may be used to preset the embedding and\r
3002      *        override levels, ignoring characters like LRE and PDF in the text.\r
3003      *        A level overrides the directional property of its corresponding\r
3004      *        (same index) character if the level has the\r
3005      *        <code>LEVEL_OVERRIDE</code> bit set.<br><br>\r
3006      *        Except for that bit, it must be\r
3007      *        <code>paraLevel<=embeddingLevels[]<=MAX_EXPLICIT_LEVEL</code>,\r
3008      *        with one exception: a level of zero may be specified for a\r
3009      *        paragraph separator even if <code>paraLevel&gt;0</code> when multiple\r
3010      *        paragraphs are submitted in the same call to <code>setPara()</code>.<br><br>\r
3011      *        <strong>Caution: </strong>A reference to this array, not a copy\r
3012      *        of the levels, will be stored in the <code>Bidi</code> object;\r
3013      *        the <code>embeddingLevels</code>\r
3014      *        should not be modified to avoid unexpected results on subsequent\r
3015      *        Bidi operations. However, the <code>setPara()</code> and\r
3016      *        <code>setLine()</code> methods may modify some or all of the\r
3017      *        levels.<br><br>\r
3018      *        <strong>Note:</strong> the <code>embeddingLevels</code> array must\r
3019      *        have one entry for each character in <code>text</code>.\r
3020      *\r
3021      * @throws IllegalArgumentException if the values in embeddingLevels are\r
3022      *         not within the allowed range\r
3023      *\r
3024      * @see #LEVEL_DEFAULT_LTR\r
3025      * @see #LEVEL_DEFAULT_RTL\r
3026      * @see #LEVEL_OVERRIDE\r
3027      * @see #MAX_EXPLICIT_LEVEL\r
3028      * @stable ICU 3.8\r
3029      */\r
3030     public void setPara(char[] chars, byte paraLevel, byte[] embeddingLevels)\r
3031     {\r
3032         /* check the argument values */\r
3033         if (paraLevel < LEVEL_DEFAULT_LTR) {\r
3034             verifyRange(paraLevel, 0, MAX_EXPLICIT_LEVEL + 1);\r
3035         }\r
3036         if (chars == null) {\r
3037             chars = new char[0];\r
3038         }\r
3039 \r
3040         /* special treatment for RUNS_ONLY mode */\r
3041         if (reorderingMode == REORDER_RUNS_ONLY) {\r
3042             setParaRunsOnly(chars, paraLevel);\r
3043             return;\r
3044         }\r
3045 \r
3046         /* initialize the Bidi object */\r
3047         this.paraBidi = null;          /* mark unfinished setPara */\r
3048         this.text = chars;\r
3049         this.length = this.originalLength = this.resultLength = text.length;\r
3050         this.paraLevel = paraLevel;\r
3051         this.direction = LTR;\r
3052         this.paraCount = 1;\r
3053 \r
3054         /* Allocate zero-length arrays instead of setting to null here; then\r
3055          * checks for null in various places can be eliminated.\r
3056          */\r
3057         dirProps = new byte[0];\r
3058         levels = new byte[0];\r
3059         runs = new BidiRun[0];\r
3060         isGoodLogicalToVisualRunsMap = false;\r
3061         insertPoints.size = 0;          /* clean up from last call */\r
3062         insertPoints.confirmed = 0;     /* clean up from last call */\r
3063 \r
3064         /*\r
3065          * Save the original paraLevel if contextual; otherwise, set to 0.\r
3066          */\r
3067         if (IsDefaultLevel(paraLevel)) {\r
3068             defaultParaLevel = paraLevel;\r
3069         } else {\r
3070             defaultParaLevel = 0;\r
3071         }\r
3072 \r
3073         if (length == 0) {\r
3074             /*\r
3075              * For an empty paragraph, create a Bidi object with the paraLevel and\r
3076              * the flags and the direction set but without allocating zero-length arrays.\r
3077              * There is nothing more to do.\r
3078              */\r
3079             if (IsDefaultLevel(paraLevel)) {\r
3080                 this.paraLevel &= 1;\r
3081                 defaultParaLevel = 0;\r
3082             }\r
3083             if ((this.paraLevel & 1) != 0) {\r
3084                 flags = DirPropFlag(R);\r
3085                 direction = RTL;\r
3086             } else {\r
3087                 flags = DirPropFlag(L);\r
3088                 direction = LTR;\r
3089             }\r
3090 \r
3091             runCount = 0;\r
3092             paraCount = 0;\r
3093             paraBidi = this;         /* mark successful setPara */\r
3094             return;\r
3095         }\r
3096 \r
3097         runCount = -1;\r
3098 \r
3099         /*\r
3100          * Get the directional properties,\r
3101          * the flags bit-set, and\r
3102          * determine the paragraph level if necessary.\r
3103          */\r
3104         getDirPropsMemory(length);\r
3105         dirProps = dirPropsMemory;\r
3106         getDirProps();\r
3107         /* the processed length may have changed if OPTION_STREAMING is set */\r
3108         trailingWSStart = length;  /* the levels[] will reflect the WS run */\r
3109 \r
3110         /* allocate paras memory */\r
3111         if (paraCount > 1) {\r
3112             getInitialParasMemory(paraCount);\r
3113             paras = parasMemory;\r
3114             paras[paraCount - 1] = length;\r
3115         } else {\r
3116             /* initialize paras for single paragraph */\r
3117             paras = simpleParas;\r
3118             simpleParas[0] = length;\r
3119         }\r
3120 \r
3121         /* are explicit levels specified? */\r
3122         if (embeddingLevels == null) {\r
3123             /* no: determine explicit levels according to the (Xn) rules */\r
3124             getLevelsMemory(length);\r
3125             levels = levelsMemory;\r
3126             direction = resolveExplicitLevels();\r
3127         } else {\r
3128             /* set BN for all explicit codes, check that all levels are 0 or paraLevel..MAX_EXPLICIT_LEVEL */\r
3129             levels = embeddingLevels;\r
3130             direction = checkExplicitLevels();\r
3131         }\r
3132 \r
3133         /*\r
3134          * The steps after (X9) in the Bidi algorithm are performed only if\r
3135          * the paragraph text has mixed directionality!\r
3136          */\r
3137         switch (direction) {\r
3138         case LTR:\r
3139             /* make sure paraLevel is even */\r
3140             paraLevel = (byte)((paraLevel + 1) & ~1);\r
3141 \r
3142             /* all levels are implicitly at paraLevel (important for getLevels()) */\r
3143             trailingWSStart = 0;\r
3144             break;\r
3145         case RTL:\r
3146             /* make sure paraLevel is odd */\r
3147             paraLevel |= 1;\r
3148 \r
3149             /* all levels are implicitly at paraLevel (important for getLevels()) */\r
3150             trailingWSStart = 0;\r
3151             break;\r
3152         default:\r
3153             /*\r
3154              *  Choose the right implicit state table\r
3155              */\r
3156             switch(reorderingMode) {\r
3157             case REORDER_DEFAULT:\r
3158                 this.impTabPair = impTab_DEFAULT;\r
3159                 break;\r
3160             case REORDER_NUMBERS_SPECIAL:\r
3161                 this.impTabPair = impTab_NUMBERS_SPECIAL;\r
3162                 break;\r
3163             case REORDER_GROUP_NUMBERS_WITH_R:\r
3164                 this.impTabPair = impTab_GROUP_NUMBERS_WITH_R;\r
3165                 break;\r
3166             case REORDER_RUNS_ONLY:\r
3167                 /* we should never get here */\r
3168                 throw new InternalError("Internal ICU error in setPara");\r
3169                 /* break; */\r
3170             case REORDER_INVERSE_NUMBERS_AS_L:\r
3171                 this.impTabPair = impTab_INVERSE_NUMBERS_AS_L;\r
3172                 break;\r
3173             case REORDER_INVERSE_LIKE_DIRECT:\r
3174                 if ((reorderingOptions & OPTION_INSERT_MARKS) != 0) {\r
3175                     this.impTabPair = impTab_INVERSE_LIKE_DIRECT_WITH_MARKS;\r
3176                 } else {\r
3177                     this.impTabPair = impTab_INVERSE_LIKE_DIRECT;\r
3178                 }\r
3179                 break;\r
3180             case REORDER_INVERSE_FOR_NUMBERS_SPECIAL:\r
3181                 if ((reorderingOptions & OPTION_INSERT_MARKS) != 0) {\r
3182                     this.impTabPair = impTab_INVERSE_FOR_NUMBERS_SPECIAL_WITH_MARKS;\r
3183                 } else {\r
3184                     this.impTabPair = impTab_INVERSE_FOR_NUMBERS_SPECIAL;\r
3185                 }\r
3186                 break;\r
3187             }\r
3188             /*\r
3189              * If there are no external levels specified and there\r
3190              * are no significant explicit level codes in the text,\r
3191              * then we can treat the entire paragraph as one run.\r
3192              * Otherwise, we need to perform the following rules on runs of\r
3193              * the text with the same embedding levels. (X10)\r
3194              * "Significant" explicit level codes are ones that actually\r
3195              * affect non-BN characters.\r
3196              * Examples for "insignificant" ones are empty embeddings\r
3197              * LRE-PDF, LRE-RLE-PDF-PDF, etc.\r
3198              */\r
3199             if (embeddingLevels == null && paraCount <= 1 &&\r
3200                 (flags & DirPropFlagMultiRuns) == 0) {\r
3201                 resolveImplicitLevels(0, length,\r
3202                         GetLRFromLevel(GetParaLevelAt(0)),\r
3203                         GetLRFromLevel(GetParaLevelAt(length - 1)));\r
3204             } else {\r
3205                 /* sor, eor: start and end types of same-level-run */\r
3206                 int start, limit = 0;\r
3207                 byte level, nextLevel;\r
3208                 short sor, eor;\r
3209 \r
3210                 /* determine the first sor and set eor to it because of the loop body (sor=eor there) */\r
3211                 level = GetParaLevelAt(0);\r
3212                 nextLevel = levels[0];\r
3213                 if (level < nextLevel) {\r
3214                     eor = GetLRFromLevel(nextLevel);\r
3215                 } else {\r
3216                     eor = GetLRFromLevel(level);\r
3217                 }\r
3218 \r
3219                 do {\r
3220                     /* determine start and limit of the run (end points just behind the run) */\r
3221 \r
3222                     /* the values for this run's start are the same as for the previous run's end */\r
3223                     start = limit;\r
3224                     level = nextLevel;\r
3225                     if ((start > 0) && (NoContextRTL(dirProps[start - 1]) == B)) {\r
3226                         /* except if this is a new paragraph, then set sor = para level */\r
3227                         sor = GetLRFromLevel(GetParaLevelAt(start));\r
3228                     } else {\r
3229                         sor = eor;\r
3230                     }\r
3231 \r
3232                     /* search for the limit of this run */\r
3233                     while (++limit < length && levels[limit] == level) {}\r
3234 \r
3235                     /* get the correct level of the next run */\r
3236                     if (limit < length) {\r
3237                         nextLevel = levels[limit];\r
3238                     } else {\r
3239                         nextLevel = GetParaLevelAt(length - 1);\r
3240                     }\r
3241 \r
3242                     /* determine eor from max(level, nextLevel); sor is last run's eor */\r
3243                     if ((level & ~LEVEL_OVERRIDE) < (nextLevel & ~LEVEL_OVERRIDE)) {\r
3244                         eor = GetLRFromLevel(nextLevel);\r
3245                     } else {\r
3246                         eor = GetLRFromLevel(level);\r
3247                     }\r
3248 \r
3249                     /* if the run consists of overridden directional types, then there\r
3250                        are no implicit types to be resolved */\r
3251                     if ((level & LEVEL_OVERRIDE) == 0) {\r
3252                         resolveImplicitLevels(start, limit, sor, eor);\r
3253                     } else {\r
3254                         /* remove the LEVEL_OVERRIDE flags */\r
3255                         do {\r
3256                             levels[start++] &= ~LEVEL_OVERRIDE;\r
3257                         } while (start < limit);\r
3258                     }\r
3259                 } while (limit  < length);\r
3260             }\r
3261 \r
3262             /* reset the embedding levels for some non-graphic characters (L1), (X9) */\r
3263             adjustWSLevels();\r
3264 \r
3265             break;\r
3266         }\r
3267         /* add RLM for inverse Bidi with contextual orientation resolving\r
3268          * to RTL which would not round-trip otherwise\r
3269          */\r
3270         if ((defaultParaLevel > 0) &&\r
3271             ((reorderingOptions & OPTION_INSERT_MARKS) != 0) &&\r
3272             ((reorderingMode == REORDER_INVERSE_LIKE_DIRECT) ||\r
3273              (reorderingMode == REORDER_INVERSE_FOR_NUMBERS_SPECIAL))) {\r
3274             int start, last;\r
3275             byte dirProp;\r
3276             for (int i = 0; i < paraCount; i++) {\r
3277                 last = paras[i] - 1;\r
3278                 if ((dirProps[last] & CONTEXT_RTL) == 0) {\r
3279                     continue;           /* LTR paragraph */\r
3280                 }\r
3281                 start= i == 0 ? 0 : paras[i - 1];\r
3282                 for (int j = last; j >= start; j--) {\r
3283                     dirProp = NoContextRTL(dirProps[j]);\r
3284                     if (dirProp == L) {\r
3285                         if (j < last) {\r
3286                             while (NoContextRTL(dirProps[last]) == B) {\r
3287                                 last--;\r
3288                             }\r
3289                         }\r
3290                         addPoint(last, RLM_BEFORE);\r
3291                         break;\r
3292                     }\r
3293                     if ((DirPropFlag(dirProp) & MASK_R_AL) != 0) {\r
3294                         break;\r
3295                     }\r
3296                 }\r
3297             }\r
3298         }\r
3299 \r
3300         if ((reorderingOptions & OPTION_REMOVE_CONTROLS) != 0) {\r
3301             resultLength -= controlCount;\r
3302         } else {\r
3303             resultLength += insertPoints.size;\r
3304         }\r
3305         paraBidi = this;             /* mark successful setPara */\r
3306     }\r
3307 \r
3308     /**\r
3309      * Perform the Unicode Bidi algorithm on a given paragraph, as defined in the\r
3310      * <a href="http://www.unicode.org/unicode/reports/tr9/">Unicode Standard Annex #9</a>,\r
3311      * version 13,\r
3312      * also described in The Unicode Standard, Version 4.0 .<p>\r
3313      *\r
3314      * This method takes a paragraph of text and computes the\r
3315      * left-right-directionality of each character. The text should not\r
3316      * contain any Unicode block separators.<p>\r
3317      *\r
3318      * The RUN_DIRECTION attribute in the text, if present, determines the base\r
3319      * direction (left-to-right or right-to-left). If not present, the base\r
3320      * direction is computed using the Unicode Bidirectional Algorithm,\r
3321      * defaulting to left-to-right if there are no strong directional characters\r
3322      * in the text. This attribute, if present, must be applied to all the text\r
3323      * in the paragraph.<p>\r
3324      *\r
3325      * The BIDI_EMBEDDING attribute in the text, if present, represents\r
3326      * embedding level information. Negative values from -1 to -62 indicate\r
3327      * overrides at the absolute value of the level. Positive values from 1 to\r
3328      * 62 indicate embeddings. Where values are zero or not defined, the base\r
3329      * embedding level as determined by the base direction is assumed.<p>\r
3330      *\r
3331      * The NUMERIC_SHAPING attribute in the text, if present, converts European\r
3332      * digits to other decimal digits before running the bidi algorithm. This\r
3333      * attribute, if present, must be applied to all the text in the paragraph.\r
3334      *\r
3335      * If the entire text is all of the same directionality, then\r
3336      * the method may not perform all the steps described by the algorithm,\r
3337      * i.e., some levels may not be the same as if all steps were performed.\r
3338      * This is not relevant for unidirectional text.<br>\r
3339      * For example, in pure LTR text with numbers the numbers would get\r
3340      * a resolved level of 2 higher than the surrounding text according to\r
3341      * the algorithm. This implementation may set all resolved levels to\r
3342      * the same value in such a case.<p>\r
3343      *\r
3344      * @param paragraph a paragraph of text with optional character and\r
3345      *        paragraph attribute information\r
3346      * @stable ICU 3.8\r
3347      */\r
3348     public void setPara(AttributedCharacterIterator paragraph)\r
3349     {\r
3350         byte paraLvl;\r
3351         Boolean runDirection = (Boolean) paragraph.getAttribute(TextAttribute.RUN_DIRECTION);\r
3352         if (runDirection == null) {\r
3353             paraLvl = LEVEL_DEFAULT_LTR;\r
3354         } else {\r
3355             paraLvl = (runDirection.equals(TextAttribute.RUN_DIRECTION_LTR)) ?\r
3356                         LTR : RTL;\r
3357         }\r
3358 \r
3359         byte[] lvls = null;\r
3360         int len = paragraph.getEndIndex() - paragraph.getBeginIndex();\r
3361         byte[] embeddingLevels = new byte[len];\r
3362         char[] txt = new char[len];\r
3363         int i = 0;\r
3364         char ch = paragraph.first();\r
3365         while (ch != AttributedCharacterIterator.DONE) {\r
3366             txt[i] = ch;\r
3367             Integer embedding = (Integer) paragraph.getAttribute(TextAttribute.BIDI_EMBEDDING);\r
3368             if (embedding != null) {\r
3369                 byte level = embedding.byteValue();\r
3370                 if (level == 0) {\r
3371                     /* no-op */\r
3372                 } else if (level < 0) {\r
3373                     lvls = embeddingLevels;\r
3374                     embeddingLevels[i] = (byte)((0 - level) | LEVEL_OVERRIDE);\r
3375                 } else {\r
3376                     lvls = embeddingLevels;\r
3377                     embeddingLevels[i] = level;\r
3378                 }\r
3379             }\r
3380             ch = paragraph.next();\r
3381             ++i;\r
3382         }\r
3383 \r
3384         NumericShaper shaper = (NumericShaper) paragraph.getAttribute(TextAttribute.NUMERIC_SHAPING);\r
3385         if (shaper != null) {\r
3386             shaper.shape(txt, 0, len);\r
3387         }\r
3388         setPara(txt, paraLvl, lvls);\r
3389     }\r
3390 \r
3391     /**\r
3392      * Specify whether block separators must be allocated level zero,\r
3393      * so that successive paragraphs will progress from left to right.\r
3394      * This method must be called before <code>setPara()</code>.\r
3395      * Paragraph separators (B) may appear in the text.  Setting them to level zero\r
3396      * means that all paragraph separators (including one possibly appearing\r
3397      * in the last text position) are kept in the reordered text after the text\r
3398      * that they follow in the source text.\r
3399      * When this feature is not enabled, a paragraph separator at the last\r
3400      * position of the text before reordering will go to the first position\r
3401      * of the reordered text when the paragraph level is odd.\r
3402      *\r
3403      * @param ordarParaLTR specifies whether paragraph separators (B) must\r
3404      * receive level 0, so that successive paragraphs progress from left to right.\r
3405      *\r
3406      * @see #setPara\r
3407      * @stable ICU 3.8\r
3408      */\r
3409     public void orderParagraphsLTR(boolean ordarParaLTR) {\r
3410         orderParagraphsLTR = ordarParaLTR;\r
3411     }\r
3412 \r
3413     /**\r
3414      * Is this <code>Bidi</code> object set to allocate level 0 to block\r
3415      * separators so that successive paragraphs progress from left to right?\r
3416      *\r
3417      * @return <code>true</code> if the <code>Bidi</code> object is set to\r
3418      *         allocate level 0 to block separators.\r
3419      *\r
3420      * @stable ICU 3.8\r
3421      */\r
3422     public boolean isOrderParagraphsLTR() {\r
3423         return orderParagraphsLTR;\r
3424     }\r
3425 \r
3426     /**\r
3427      * Get the directionality of the text.\r
3428      *\r
3429      * @return a value of <code>LTR</code>, <code>RTL</code> or <code>MIXED</code>\r
3430      *         that indicates if the entire text\r
3431      *         represented by this object is unidirectional,\r
3432      *         and which direction, or if it is mixed-directional.\r
3433      *\r
3434      * @throws IllegalStateException if this call is not preceded by a successful\r
3435      *         call to <code>setPara</code> or <code>setLine</code>\r
3436      *\r
3437      * @see #LTR\r
3438      * @see #RTL\r
3439      * @see #MIXED\r
3440      * @stable ICU 3.8\r
3441      */\r
3442     public byte getDirection()\r
3443     {\r
3444         verifyValidParaOrLine();\r
3445         return direction;\r
3446     }\r
3447 \r
3448     /**\r
3449      * Get the text.\r
3450      *\r
3451      * @return A <code>String</code> containing the text that the\r
3452      *         <code>Bidi</code> object was created for.\r
3453      *\r
3454      * @throws IllegalStateException if this call is not preceded by a successful\r
3455      *         call to <code>setPara</code> or <code>setLine</code>\r
3456      *\r
3457      * @see #setPara\r
3458      * @see #setLine\r
3459      * @stable ICU 3.8\r
3460      */\r
3461     public String getTextAsString()\r
3462     {\r
3463         verifyValidParaOrLine();\r
3464         return new String(text);\r
3465     }\r
3466 \r
3467     /**\r
3468      * Get the text.\r
3469      *\r
3470      * @return A <code>char</code> array containing the text that the\r
3471      *         <code>Bidi</code> object was created for.\r
3472      *\r
3473      * @throws IllegalStateException if this call is not preceded by a successful\r
3474      *         call to <code>setPara</code> or <code>setLine</code>\r
3475      *\r
3476      * @see #setPara\r
3477      * @see #setLine\r
3478      * @stable ICU 3.8\r
3479      */\r
3480     public char[] getText()\r
3481     {\r
3482         verifyValidParaOrLine();\r
3483         return text;\r
3484     }\r
3485 \r
3486     /**\r
3487      * Get the length of the text.\r
3488      *\r
3489      * @return The length of the text that the <code>Bidi</code> object was\r
3490      *         created for.\r
3491      *\r
3492      * @throws IllegalStateException if this call is not preceded by a successful\r
3493      *         call to <code>setPara</code> or <code>setLine</code>\r
3494      * @stable ICU 3.8\r
3495      */\r
3496     public int getLength()\r
3497     {\r
3498         verifyValidParaOrLine();\r
3499         return originalLength;\r
3500     }\r
3501 \r
3502     /**\r
3503      * Get the length of the source text processed by the last call to\r
3504      * <code>setPara()</code>. This length may be different from the length of\r
3505      * the source text if option <code>OPTION_STREAMING</code> has been\r
3506      * set.\r
3507      * <br>\r
3508      * Note that whenever the length of the text affects the execution or the\r
3509      * result of a method, it is the processed length which must be considered,\r
3510      * except for <code>setPara</code> (which receives unprocessed source text)\r
3511      * and <code>getLength</code> (which returns the original length of the\r
3512      * source text).<br>\r
3513      * In particular, the processed length is the one to consider in the\r
3514      * following cases:\r
3515      * <ul>\r
3516      * <li>maximum value of the <code>limit</code> argument of\r
3517      * <code>setLine</code></li>\r
3518      * <li>maximum value of the <code>charIndex</code> argument of\r
3519      * <code>getParagraph</code></li>\r
3520      * <li>maximum value of the <code>charIndex</code> argument of\r
3521      * <code>getLevelAt</code></li>\r
3522      * <li>number of elements in the array returned by <code>getLevels</code>\r
3523      * </li>\r
3524      * <li>maximum value of the <code>logicalStart</code> argument of\r
3525      * <code>getLogicalRun</code></li>\r
3526      * <li>maximum value of the <code>logicalIndex</code> argument of\r
3527      * <code>getVisualIndex</code></li>\r
3528      * <li>number of elements returned by <code>getLogicalMap</code></li>\r
3529      * <li>length of text processed by <code>writeReordered</code></li>\r
3530      * </ul>\r
3531      *\r
3532      * @return The length of the part of the source text processed by\r
3533      *         the last call to <code>setPara</code>.\r
3534      *\r
3535      * @throws IllegalStateException if this call is not preceded by a successful\r
3536      *         call to <code>setPara</code> or <code>setLine</code>\r
3537      *\r
3538      * @see #setPara\r
3539      * @see #OPTION_STREAMING\r
3540      * @stable ICU 3.8\r
3541      */\r
3542     public int getProcessedLength() {\r
3543         verifyValidParaOrLine();\r
3544         return length;\r
3545     }\r
3546 \r
3547     /**\r
3548      * Get the length of the reordered text resulting from the last call to\r
3549      * <code>setPara()</code>. This length may be different from the length\r
3550      * of the source text if option <code>OPTION_INSERT_MARKS</code>\r
3551      * or option <code>OPTION_REMOVE_CONTROLS</code> has been set.\r
3552      * <br>\r
3553      * This resulting length is the one to consider in the following cases:\r
3554      * <ul>\r
3555      * <li>maximum value of the <code>visualIndex</code> argument of\r
3556      * <code>getLogicalIndex</code></li>\r
3557      * <li>number of elements returned by <code>getVisualMap</code></li>\r
3558      * </ul>\r
3559      * Note that this length stays identical to the source text length if\r
3560      * Bidi marks are inserted or removed using option bits of\r
3561      * <code>writeReordered</code>, or if option\r
3562      * <code>REORDER_INVERSE_NUMBERS_AS_L</code> has been set.\r
3563      *\r
3564      * @return The length of the reordered text resulting from\r
3565      *         the last call to <code>setPara</code>.\r
3566      *\r
3567      * @throws IllegalStateException if this call is not preceded by a successful\r
3568      *         call to <code>setPara</code> or <code>setLine</code>\r
3569      *\r
3570      * @see #setPara\r
3571      * @see #OPTION_INSERT_MARKS\r
3572      * @see #OPTION_REMOVE_CONTROLS\r
3573      * @see #REORDER_INVERSE_NUMBERS_AS_L\r
3574      * @stable ICU 3.8\r
3575      */\r
3576     public int getResultLength() {\r
3577         verifyValidParaOrLine();\r
3578         return resultLength;\r
3579     }\r
3580 \r
3581     /* paragraphs API methods ------------------------------------------------- */\r
3582 \r
3583     /**\r
3584      * Get the paragraph level of the text.\r
3585      *\r
3586      * @return The paragraph level. If there are multiple paragraphs, their\r
3587      *         level may vary if the required paraLevel is LEVEL_DEFAULT_LTR or\r
3588      *         LEVEL_DEFAULT_RTL.  In that case, the level of the first paragraph\r
3589      *         is returned.\r
3590      *\r
3591      * @throws IllegalStateException if this call is not preceded by a successful\r
3592      *         call to <code>setPara</code> or <code>setLine</code>\r
3593      *\r
3594      * @see #LEVEL_DEFAULT_LTR\r
3595      * @see #LEVEL_DEFAULT_RTL\r
3596      * @see #getParagraph\r
3597      * @see #getParagraphByIndex\r
3598      * @stable ICU 3.8\r
3599      */\r
3600     public byte getParaLevel()\r
3601     {\r
3602         verifyValidParaOrLine();\r
3603         return paraLevel;\r
3604     }\r
3605 \r
3606     /**\r
3607      * Get the number of paragraphs.\r
3608      *\r
3609      * @return The number of paragraphs.\r
3610      *\r
3611      * @throws IllegalStateException if this call is not preceded by a successful\r
3612      *         call to <code>setPara</code> or <code>setLine</code>\r
3613      * @stable ICU 3.8\r
3614      */\r
3615     public int countParagraphs()\r
3616     {\r
3617         verifyValidParaOrLine();\r
3618         return paraCount;\r
3619     }\r
3620 \r
3621     /**\r
3622      * Get a paragraph, given the index of this paragraph.\r
3623      *\r
3624      * This method returns information about a paragraph.<p>\r
3625      *\r
3626      * @param paraIndex is the number of the paragraph, in the\r
3627      *        range <code>[0..countParagraphs()-1]</code>.\r
3628      *\r
3629      * @return a BidiRun object with the details of the paragraph:<br>\r
3630      *        <code>start</code> will receive the index of the first character\r
3631      *        of the paragraph in the text.<br>\r
3632      *        <code>limit</code> will receive the limit of the paragraph.<br>\r
3633      *        <code>embeddingLevel</code> will receive the level of the paragraph.\r
3634      *\r
3635      * @throws IllegalStateException if this call is not preceded by a successful\r
3636      *         call to <code>setPara</code> or <code>setLine</code>\r
3637      * @throws IllegalArgumentException if paraIndex is not in the range\r
3638      *        <code>[0..countParagraphs()-1]</code>\r
3639      *\r
3640      * @see com.ibm.icu.text.BidiRun\r
3641      * @stable ICU 3.8\r
3642      */\r
3643     public BidiRun getParagraphByIndex(int paraIndex)\r
3644     {\r
3645         verifyValidParaOrLine();\r
3646         verifyRange(paraIndex, 0, paraCount);\r
3647 \r
3648         Bidi bidi = paraBidi;             /* get Para object if Line object */\r
3649         int paraStart;\r
3650         if (paraIndex == 0) {\r
3651             paraStart = 0;\r
3652         } else {\r
3653             paraStart = bidi.paras[paraIndex - 1];\r
3654         }\r
3655         BidiRun bidiRun = new BidiRun();\r
3656         bidiRun.start = paraStart;\r
3657         bidiRun.limit = bidi.paras[paraIndex];\r
3658         bidiRun.level = GetParaLevelAt(paraStart);\r
3659         return bidiRun;\r
3660     }\r
3661 \r
3662     /**\r
3663      * Get a paragraph, given a position within the text.\r
3664      * This method returns information about a paragraph.<br>\r
3665      * Note: if the paragraph index is known, it is more efficient to\r
3666      * retrieve the paragraph information using getParagraphByIndex().<p>\r
3667      *\r
3668      * @param charIndex is the index of a character within the text, in the\r
3669      *        range <code>[0..getProcessedLength()-1]</code>.\r
3670      *\r
3671      * @return a BidiRun object with the details of the paragraph:<br>\r
3672      *        <code>start</code> will receive the index of the first character\r
3673      *        of the paragraph in the text.<br>\r
3674      *        <code>limit</code> will receive the limit of the paragraph.<br>\r
3675      *        <code>embeddingLevel</code> will receive the level of the paragraph.\r
3676      *\r
3677      * @throws IllegalStateException if this call is not preceded by a successful\r
3678      *         call to <code>setPara</code> or <code>setLine</code>\r
3679      * @throws IllegalArgumentException if charIndex is not within the legal range\r
3680      *\r
3681      * @see com.ibm.icu.text.BidiRun\r
3682      * @see #getParagraphByIndex\r
3683      * @see #getProcessedLength\r
3684      * @stable ICU 3.8\r
3685      */\r
3686     public BidiRun getParagraph(int charIndex)\r
3687     {\r
3688         verifyValidParaOrLine();\r
3689         Bidi bidi = paraBidi;             /* get Para object if Line object */\r
3690         verifyRange(charIndex, 0, bidi.length);\r
3691         int paraIndex;\r
3692         for (paraIndex = 0; charIndex >= bidi.paras[paraIndex]; paraIndex++) {\r
3693         }\r
3694         return getParagraphByIndex(paraIndex);\r
3695     }\r
3696 \r
3697     /**\r
3698      * Get the index of a paragraph, given a position within the text.<p>\r
3699      *\r
3700      * @param charIndex is the index of a character within the text, in the\r
3701      *        range <code>[0..getProcessedLength()-1]</code>.\r
3702      *\r
3703      * @return The index of the paragraph containing the specified position,\r
3704      *         starting from 0.\r
3705      *\r
3706      * @throws IllegalStateException if this call is not preceded by a successful\r
3707      *         call to <code>setPara</code> or <code>setLine</code>\r
3708      * @throws IllegalArgumentException if charIndex is not within the legal range\r
3709      *\r
3710      * @see com.ibm.icu.text.BidiRun\r
3711      * @see #getProcessedLength\r
3712      * @stable ICU 3.8\r
3713      */\r
3714     public int getParagraphIndex(int charIndex)\r
3715     {\r
3716         verifyValidParaOrLine();\r
3717         Bidi bidi = paraBidi;             /* get Para object if Line object */\r
3718         verifyRange(charIndex, 0, bidi.length);\r
3719         int paraIndex;\r
3720         for (paraIndex = 0; charIndex >= bidi.paras[paraIndex]; paraIndex++) {\r
3721         }\r
3722         return paraIndex;\r
3723     }\r
3724 \r
3725     /**\r
3726      * Set a custom Bidi classifier used by the UBA implementation for Bidi\r
3727      * class determination.\r
3728      *\r
3729      * @param classifier A new custom classifier. This can be null.\r
3730      *\r
3731      * @see #getCustomClassifier\r
3732      * @stable ICU 3.8\r
3733      */\r
3734     public void setCustomClassifier(BidiClassifier classifier) {\r
3735         this.customClassifier = classifier;\r
3736     }\r
3737 \r
3738     /**\r
3739      * Gets the current custom class classifier used for Bidi class\r
3740      * determination.\r
3741      *\r
3742      * @return An instance of class <code>BidiClassifier</code>\r
3743      *\r
3744      * @see #setCustomClassifier\r
3745      * @stable ICU 3.8\r
3746      */\r
3747     public BidiClassifier getCustomClassifier() {\r
3748         return this.customClassifier;\r
3749     }\r
3750 \r
3751     /**\r
3752      * Retrieves the Bidi class for a given code point.\r
3753      * <p>If a <code>BidiClassifier</code> is defined and returns a value\r
3754      * other than <code>CLASS_DEFAULT</code>, that value is used; otherwise\r
3755      * the default class determination mechanism is invoked.</p>\r
3756      *\r
3757      * @param c The code point to get a Bidi class for.\r
3758      *\r
3759      * @return The Bidi class for the character <code>c</code> that is in effect\r
3760      *         for this <code>Bidi</code> instance.\r
3761      *\r
3762      * @see BidiClassifier\r
3763      * @stable ICU 3.8\r
3764      */\r
3765     public int getCustomizedClass(int c) {\r
3766         int dir;\r
3767 \r
3768         if (customClassifier == null ||\r
3769             (dir = customClassifier.classify(c)) == Bidi.CLASS_DEFAULT) {\r
3770             return bdp.getClass(c);\r
3771         } else {\r
3772             return dir;\r
3773         }\r
3774     }\r
3775 \r
3776     /**\r
3777      * <code>setLine()</code> returns a <code>Bidi</code> object to\r
3778      * contain the reordering information, especially the resolved levels,\r
3779      * for all the characters in a line of text. This line of text is\r
3780      * specified by referring to a <code>Bidi</code> object representing\r
3781      * this information for a piece of text containing one or more paragraphs,\r
3782      * and by specifying a range of indexes in this text.<p>\r
3783      * In the new line object, the indexes will range from 0 to <code>limit-start-1</code>.<p>\r
3784      *\r
3785      * This is used after calling <code>setPara()</code>\r
3786      * for a piece of text, and after line-breaking on that text.\r
3787      * It is not necessary if each paragraph is treated as a single line.<p>\r
3788      *\r
3789      * After line-breaking, rules (L1) and (L2) for the treatment of\r
3790      * trailing WS and for reordering are performed on\r
3791      * a <code>Bidi</code> object that represents a line.<p>\r
3792      *\r
3793      * <strong>Important: </strong>the line <code>Bidi</code> object may\r
3794      * reference data within the global text <code>Bidi</code> object.\r
3795      * You should not alter the content of the global text object until\r
3796      * you are finished using the line object.\r
3797      *\r
3798      * @param start is the line's first index into the text.\r
3799      *\r
3800      * @param limit is just behind the line's last index into the text\r
3801      *        (its last index +1).\r
3802      *\r
3803      * @return a <code>Bidi</code> object that will now represent a line of the text.\r
3804      *\r
3805      * @throws IllegalStateException if this call is not preceded by a successful\r
3806      *         call to <code>setPara</code>\r
3807      * @throws IllegalArgumentException if start and limit are not in the range\r
3808      *         <code>0&lt;=start&lt;limit&lt;=getProcessedLength()</code>,\r
3809      *         or if the specified line crosses a paragraph boundary\r
3810      *\r
3811      * @see #setPara\r
3812      * @see #getProcessedLength\r
3813      * @stable ICU 3.8\r
3814      */\r
3815     public Bidi setLine(int start, int limit)\r
3816     {\r
3817         verifyValidPara();\r
3818         verifyRange(start, 0, limit);\r
3819         verifyRange(limit, 0, length+1);\r
3820         if (getParagraphIndex(start) != getParagraphIndex(limit - 1)) {\r
3821             /* the line crosses a paragraph boundary */\r
3822             throw new IllegalArgumentException();\r
3823         }\r
3824         return BidiLine.setLine(this, start, limit);\r
3825     }\r
3826 \r
3827     /**\r
3828      * Get the level for one character.\r
3829      *\r
3830      * @param charIndex the index of a character.\r
3831      *\r
3832      * @return The level for the character at <code>charIndex</code>.\r
3833      *\r
3834      * @throws IllegalStateException if this call is not preceded by a successful\r
3835      *         call to <code>setPara</code> or <code>setLine</code>\r
3836      * @throws IllegalArgumentException if charIndex is not in the range\r
3837      *         <code>0&lt;=charIndex&lt;getProcessedLength()</code>\r
3838      *\r
3839      * @see #getProcessedLength\r
3840      * @stable ICU 3.8\r
3841      */\r
3842     public byte getLevelAt(int charIndex)\r
3843     {\r
3844         verifyValidParaOrLine();\r
3845         verifyRange(charIndex, 0, length);\r
3846         return BidiLine.getLevelAt(this, charIndex);\r
3847     }\r
3848 \r
3849     /**\r
3850      * Get an array of levels for each character.<p>\r
3851      *\r
3852      * Note that this method may allocate memory under some\r
3853      * circumstances, unlike <code>getLevelAt()</code>.\r
3854      *\r
3855      * @return The levels array for the text,\r
3856      *         or <code>null</code> if an error occurs.\r
3857      *\r
3858      * @throws IllegalStateException if this call is not preceded by a successful\r
3859      *         call to <code>setPara</code> or <code>setLine</code>\r
3860      * @stable ICU 3.8\r
3861      */\r
3862     public byte[] getLevels()\r
3863     {\r
3864         verifyValidParaOrLine();\r
3865         if (length <= 0) {\r
3866             return new byte[0];\r
3867         }\r
3868         return BidiLine.getLevels(this);\r
3869     }\r
3870 \r
3871     /**\r
3872      * Get a logical run.\r
3873      * This method returns information about a run and is used\r
3874      * to retrieve runs in logical order.<p>\r
3875      * This is especially useful for line-breaking on a paragraph.\r
3876      *\r
3877      * @param logicalPosition is a logical position within the source text.\r
3878      *\r
3879      * @return a BidiRun object filled with <code>start</code> containing\r
3880      *        the first character of the run, <code>limit</code> containing\r
3881      *        the limit of the run, and <code>embeddingLevel</code> containing\r
3882      *        the level of the run.\r
3883      *\r
3884      * @throws IllegalStateException if this call is not preceded by a successful\r
3885      *         call to <code>setPara</code> or <code>setLine</code>\r
3886      * @throws IllegalArgumentException if logicalPosition is not in the range\r
3887      *         <code>0&lt;=logicalPosition&lt;getProcessedLength()</code>\r
3888      *\r
3889      * @see com.ibm.icu.text.BidiRun\r
3890      * @see com.ibm.icu.text.BidiRun#getStart()\r
3891      * @see com.ibm.icu.text.BidiRun#getLimit()\r
3892      * @see com.ibm.icu.text.BidiRun#getEmbeddingLevel()\r
3893      *\r
3894      * @stable ICU 3.8\r
3895      */\r
3896     public BidiRun getLogicalRun(int logicalPosition)\r
3897     {\r
3898         verifyValidParaOrLine();\r
3899         verifyRange(logicalPosition, 0, length);\r
3900         return BidiLine.getLogicalRun(this, logicalPosition);\r
3901     }\r
3902 \r
3903     /**\r
3904      * Get the number of runs.\r
3905      * This method may invoke the actual reordering on the\r
3906      * <code>Bidi</code> object, after <code>setPara()</code>\r
3907      * may have resolved only the levels of the text. Therefore,\r
3908      * <code>countRuns()</code> may have to allocate memory,\r
3909      * and may throw an exception if it fails to do so.\r
3910      *\r
3911      * @return The number of runs.\r
3912      *\r
3913      * @throws IllegalStateException if this call is not preceded by a successful\r
3914      *         call to <code>setPara</code> or <code>setLine</code>\r
3915      * @stable ICU 3.8\r
3916      */\r
3917     public int countRuns()\r
3918     {\r
3919         verifyValidParaOrLine();\r
3920         BidiLine.getRuns(this);\r
3921         return runCount;\r
3922     }\r
3923 \r
3924     /**\r
3925      *\r
3926      * Get a <code>BidiRun</code> object according to its index. BidiRun methods\r
3927      * may be used to retrieve the run's logical start, length and level,\r
3928      * which can be even for an LTR run or odd for an RTL run.\r
3929      * In an RTL run, the character at the logical start is\r
3930      * visually on the right of the displayed run.\r
3931      * The length is the number of characters in the run.<p>\r
3932      * <code>countRuns()</code> is normally called\r
3933      * before the runs are retrieved.\r
3934      *\r
3935      * <p>\r
3936      *  Example:\r
3937      * <pre>\r
3938      *  Bidi bidi = new Bidi();\r
3939      *  String text = "abc 123 DEFG xyz";\r
3940      *  bidi.setPara(text, Bidi.RTL, null);\r
3941      *  int i, count=bidi.countRuns(), logicalStart, visualIndex=0, length;\r
3942      *  BidiRun run;\r
3943      *  for (i = 0; i &lt; count; ++i) {\r
3944      *      run = bidi.getVisualRun(i);\r
3945      *      logicalStart = run.getStart();\r
3946      *      length = run.getLength();\r
3947      *      if (Bidi.LTR == run.getEmbeddingLevel()) {\r
3948      *          do { // LTR\r
3949      *              show_char(text.charAt(logicalStart++), visualIndex++);\r
3950      *          } while (--length &gt; 0);\r
3951      *      } else {\r
3952      *          logicalStart += length;  // logicalLimit\r
3953      *          do { // RTL\r
3954      *              show_char(text.charAt(--logicalStart), visualIndex++);\r
3955      *          } while (--length &gt; 0);\r
3956      *      }\r
3957      *  }\r
3958      * </pre>\r
3959      * <p>\r
3960      * Note that in right-to-left runs, code like this places\r
3961      * second surrogates before first ones (which is generally a bad idea)\r
3962      * and combining characters before base characters.\r
3963      * <p>\r
3964      * Use of <code>{@link #writeReordered}</code>, optionally with the\r
3965      * <code>{@link #KEEP_BASE_COMBINING}</code> option, can be considered in\r
3966      * order to avoid these issues.\r
3967      *\r
3968      * @param runIndex is the number of the run in visual order, in the\r
3969      *        range <code>[0..countRuns()-1]</code>.\r
3970      *\r
3971      * @return a BidiRun object containing the details of the run. The\r
3972      *         directionality of the run is\r
3973      *         <code>LTR==0</code> or <code>RTL==1</code>,\r
3974      *         never <code>MIXED</code>.\r
3975      *\r
3976      * @throws IllegalStateException if this call is not preceded by a successful\r
3977      *         call to <code>setPara</code> or <code>setLine</code>\r
3978      * @throws IllegalArgumentException if <code>runIndex</code> is not in\r
3979      *         the range <code>0&lt;=runIndex&lt;countRuns()</code>\r
3980      *\r
3981      * @see #countRuns()\r
3982      * @see com.ibm.icu.text.BidiRun\r
3983      * @see com.ibm.icu.text.BidiRun#getStart()\r
3984      * @see com.ibm.icu.text.BidiRun#getLength()\r
3985      * @see com.ibm.icu.text.BidiRun#getEmbeddingLevel()\r
3986      * @stable ICU 3.8\r
3987      */\r
3988     public BidiRun getVisualRun(int runIndex)\r
3989     {\r
3990         verifyValidParaOrLine();\r
3991         BidiLine.getRuns(this);\r
3992         verifyRange(runIndex, 0, runCount);\r
3993         return BidiLine.getVisualRun(this, runIndex);\r
3994     }\r
3995 \r
3996     /**\r
3997      * Get the visual position from a logical text position.\r
3998      * If such a mapping is used many times on the same\r
3999      * <code>Bidi</code> object, then calling\r
4000      * <code>getLogicalMap()</code> is more efficient.\r
4001      * <p>\r
4002      * The value returned may be <code>MAP_NOWHERE</code> if there is no\r
4003      * visual position because the corresponding text character is a Bidi\r
4004      * control removed from output by the option\r
4005      * <code>OPTION_REMOVE_CONTROLS</code>.\r
4006      * <p>\r
4007      * When the visual output is altered by using options of\r
4008      * <code>writeReordered()</code> such as <code>INSERT_LRM_FOR_NUMERIC</code>,\r
4009      * <code>KEEP_BASE_COMBINING</code>, <code>OUTPUT_REVERSE</code>,\r
4010      * <code>REMOVE_BIDI_CONTROLS</code>, the visual position returned may not\r
4011      * be correct. It is advised to use, when possible, reordering options\r
4012      * such as {@link #OPTION_INSERT_MARKS} and {@link #OPTION_REMOVE_CONTROLS}.\r
4013      * <p>\r
4014      * Note that in right-to-left runs, this mapping places\r
4015      * second surrogates before first ones (which is generally a bad idea)\r
4016      * and combining characters before base characters.\r
4017      * Use of <code>{@link #writeReordered}</code>, optionally with the\r
4018      * <code>{@link #KEEP_BASE_COMBINING}</code> option can be considered instead\r
4019      * of using the mapping, in order to avoid these issues.\r
4020      *\r
4021      * @param logicalIndex is the index of a character in the text.\r
4022      *\r
4023      * @return The visual position of this character.\r
4024      *\r
4025      * @throws IllegalStateException if this call is not preceded by a successful\r
4026      *         call to <code>setPara</code> or <code>setLine</code>\r
4027      * @throws IllegalArgumentException if <code>logicalIndex</code> is not in\r
4028      *         the range <code>0&lt;=logicalIndex&lt;getProcessedLength()</code>\r
4029      *\r
4030      * @see #getLogicalMap\r
4031      * @see #getLogicalIndex\r
4032      * @see #getProcessedLength\r
4033      * @see #MAP_NOWHERE\r
4034      * @see #OPTION_REMOVE_CONTROLS\r
4035      * @see #writeReordered\r
4036      * @stable ICU 3.8\r
4037      */\r
4038     public int getVisualIndex(int logicalIndex)\r
4039     {\r
4040         verifyValidParaOrLine();\r
4041         verifyRange(logicalIndex, 0, length);\r
4042         return BidiLine.getVisualIndex(this, logicalIndex);\r
4043     }\r
4044 \r
4045 \r
4046     /**\r
4047      * Get the logical text position from a visual position.\r
4048      * If such a mapping is used many times on the same\r
4049      * <code>Bidi</code> object, then calling\r
4050      * <code>getVisualMap()</code> is more efficient.\r
4051      * <p>\r
4052      * The value returned may be <code>MAP_NOWHERE</code> if there is no\r
4053      * logical position because the corresponding text character is a Bidi\r
4054      * mark inserted in the output by option\r
4055      * <code>OPTION_INSERT_MARKS</code>.\r
4056      * <p>\r
4057      * This is the inverse method to <code>getVisualIndex()</code>.\r
4058      * <p>\r
4059      * When the visual output is altered by using options of\r
4060      * <code>writeReordered()</code> such as <code>INSERT_LRM_FOR_NUMERIC</code>,\r
4061      * <code>KEEP_BASE_COMBINING</code>, <code>OUTPUT_REVERSE</code>,\r
4062      * <code>REMOVE_BIDI_CONTROLS</code>, the logical position returned may not\r
4063      * be correct. It is advised to use, when possible, reordering options\r
4064      * such as {@link #OPTION_INSERT_MARKS} and {@link #OPTION_REMOVE_CONTROLS}.\r
4065      *\r
4066      * @param visualIndex is the visual position of a character.\r
4067      *\r
4068      * @return The index of this character in the text.\r
4069      *\r
4070      * @throws IllegalStateException if this call is not preceded by a successful\r
4071      *         call to <code>setPara</code> or <code>setLine</code>\r
4072      * @throws IllegalArgumentException if <code>visualIndex</code> is not in\r
4073      *         the range <code>0&lt;=visualIndex&lt;getResultLength()</code>\r
4074      *\r
4075      * @see #getVisualMap\r
4076      * @see #getVisualIndex\r
4077      * @see #getResultLength\r
4078      * @see #MAP_NOWHERE\r
4079      * @see #OPTION_INSERT_MARKS\r
4080      * @see #writeReordered\r
4081      * @stable ICU 3.8\r
4082      */\r
4083     public int getLogicalIndex(int visualIndex)\r
4084     {\r
4085         verifyValidParaOrLine();\r
4086         verifyRange(visualIndex, 0, resultLength);\r
4087         /* we can do the trivial cases without the runs array */\r
4088         if (insertPoints.size == 0 && controlCount == 0) {\r
4089             if (direction == LTR) {\r
4090                 return visualIndex;\r
4091             }\r
4092             else if (direction == RTL) {\r
4093                 return length - visualIndex - 1;\r
4094             }\r
4095         }\r
4096         BidiLine.getRuns(this);\r
4097         return BidiLine.getLogicalIndex(this, visualIndex);\r
4098     }\r
4099 \r
4100     /**\r
4101      * Get a logical-to-visual index map (array) for the characters in the\r
4102      * <code>Bidi</code> (paragraph or line) object.\r
4103      * <p>\r
4104      * Some values in the map may be <code>MAP_NOWHERE</code> if the\r
4105      * corresponding text characters are Bidi controls removed from the visual\r
4106      * output by the option <code>OPTION_REMOVE_CONTROLS</code>.\r
4107      * <p>\r
4108      * When the visual output is altered by using options of\r
4109      * <code>writeReordered()</code> such as <code>INSERT_LRM_FOR_NUMERIC</code>,\r
4110      * <code>KEEP_BASE_COMBINING</code>, <code>OUTPUT_REVERSE</code>,\r
4111      * <code>REMOVE_BIDI_CONTROLS</code>, the visual positions returned may not\r
4112      * be correct. It is advised to use, when possible, reordering options\r
4113      * such as {@link #OPTION_INSERT_MARKS} and {@link #OPTION_REMOVE_CONTROLS}.\r
4114      * <p>\r
4115      * Note that in right-to-left runs, this mapping places\r
4116      * second surrogates before first ones (which is generally a bad idea)\r
4117      * and combining characters before base characters.\r
4118      * Use of <code>{@link #writeReordered}</code>, optionally with the\r
4119      * <code>{@link #KEEP_BASE_COMBINING}</code> option can be considered instead\r
4120      * of using the mapping, in order to avoid these issues.\r
4121      *\r
4122      * @return an array of <code>getProcessedLength()</code>\r
4123      *        indexes which will reflect the reordering of the characters.<br><br>\r
4124      *        The index map will result in\r
4125      *        <code>indexMap[logicalIndex]==visualIndex</code>, where\r
4126      *        <code>indexMap</code> represents the returned array.\r
4127      *\r
4128      * @throws IllegalStateException if this call is not preceded by a successful\r
4129      *         call to <code>setPara</code> or <code>setLine</code>\r
4130      *\r
4131      * @see #getVisualMap\r
4132      * @see #getVisualIndex\r
4133      * @see #getProcessedLength\r
4134      * @see #MAP_NOWHERE\r
4135      * @see #OPTION_REMOVE_CONTROLS\r
4136      * @see #writeReordered\r
4137      * @stable ICU 3.8\r
4138      */\r
4139     public int[] getLogicalMap()\r
4140     {\r
4141         /* countRuns() checks successful call to setPara/setLine */\r
4142         countRuns();\r
4143         if (length <= 0) {\r
4144             return new int[0];\r
4145         }\r
4146         return BidiLine.getLogicalMap(this);\r
4147     }\r
4148 \r
4149     /**\r
4150      * Get a visual-to-logical index map (array) for the characters in the\r
4151      * <code>Bidi</code> (paragraph or line) object.\r
4152      * <p>\r
4153      * Some values in the map may be <code>MAP_NOWHERE</code> if the\r
4154      * corresponding text characters are Bidi marks inserted in the visual\r
4155      * output by the option <code>OPTION_INSERT_MARKS</code>.\r
4156      * <p>\r
4157      * When the visual output is altered by using options of\r
4158      * <code>writeReordered()</code> such as <code>INSERT_LRM_FOR_NUMERIC</code>,\r
4159      * <code>KEEP_BASE_COMBINING</code>, <code>OUTPUT_REVERSE</code>,\r
4160      * <code>REMOVE_BIDI_CONTROLS</code>, the logical positions returned may not\r
4161      * be correct. It is advised to use, when possible, reordering options\r
4162      * such as {@link #OPTION_INSERT_MARKS} and {@link #OPTION_REMOVE_CONTROLS}.\r
4163      *\r
4164      * @return an array of <code>getResultLength()</code>\r
4165      *        indexes which will reflect the reordering of the characters.<br><br>\r
4166      *        The index map will result in\r
4167      *        <code>indexMap[visualIndex]==logicalIndex</code>, where\r
4168      *        <code>indexMap</code> represents the returned array.\r
4169      *\r
4170      * @throws IllegalStateException if this call is not preceded by a successful\r
4171      *         call to <code>setPara</code> or <code>setLine</code>\r
4172      *\r
4173      * @see #getLogicalMap\r
4174      * @see #getLogicalIndex\r
4175      * @see #getResultLength\r
4176      * @see #MAP_NOWHERE\r
4177      * @see #OPTION_INSERT_MARKS\r
4178      * @see #writeReordered\r
4179      * @stable ICU 3.8\r
4180      */\r
4181     public int[] getVisualMap()\r
4182     {\r
4183         /* countRuns() checks successful call to setPara/setLine */\r
4184         countRuns();\r
4185         if (resultLength <= 0) {\r
4186             return new int[0];\r
4187         }\r
4188         return BidiLine.getVisualMap(this);\r
4189     }\r
4190 \r
4191     /**\r
4192      * This is a convenience method that does not use a <code>Bidi</code> object.\r
4193      * It is intended to be used for when an application has determined the levels\r
4194      * of objects (character sequences) and just needs to have them reordered (L2).\r
4195      * This is equivalent to using <code>getLogicalMap()</code> on a\r
4196      * <code>Bidi</code> object.\r
4197      *\r
4198      * @param levels is an array of levels that have been determined by\r
4199      *        the application.\r
4200      *\r
4201      * @return an array of <code>levels.length</code>\r
4202      *        indexes which will reflect the reordering of the characters.<p>\r
4203      *        The index map will result in\r
4204      *        <code>indexMap[logicalIndex]==visualIndex</code>, where\r
4205      *        <code>indexMap</code> represents the returned array.\r
4206      *\r
4207      * @stable ICU 3.8\r
4208      */\r
4209     public static int[] reorderLogical(byte[] levels)\r
4210     {\r
4211         return BidiLine.reorderLogical(levels);\r
4212     }\r
4213 \r
4214     /**\r
4215      * This is a convenience method that does not use a <code>Bidi</code> object.\r
4216      * It is intended to be used for when an application has determined the levels\r
4217      * of objects (character sequences) and just needs to have them reordered (L2).\r
4218      * This is equivalent to using <code>getVisualMap()</code> on a\r
4219      * <code>Bidi</code> object.\r
4220      *\r
4221      * @param levels is an array of levels that have been determined by\r
4222      *        the application.\r
4223      *\r
4224      * @return an array of <code>levels.length</code>\r
4225      *        indexes which will reflect the reordering of the characters.<p>\r
4226      *        The index map will result in\r
4227      *        <code>indexMap[visualIndex]==logicalIndex</code>, where\r
4228      *        <code>indexMap</code> represents the returned array.\r
4229      *\r
4230      * @stable ICU 3.8\r
4231      */\r
4232     public static int[] reorderVisual(byte[] levels)\r
4233     {\r
4234         return BidiLine.reorderVisual(levels);\r
4235     }\r
4236 \r
4237     /**\r
4238      * Invert an index map.\r
4239      * The index mapping of the argument map is inverted and returned as\r
4240      * an array of indexes that we will call the inverse map.\r
4241      *\r
4242      * @param srcMap is an array whose elements define the original mapping\r
4243      * from a source array to a destination array.\r
4244      * Some elements of the source array may have no mapping in the\r
4245      * destination array. In that case, their value will be\r
4246      * the special value <code>MAP_NOWHERE</code>.\r
4247      * All elements must be >=0 or equal to <code>MAP_NOWHERE</code>.\r
4248      * Some elements in the source map may have a value greater than the\r
4249      * srcMap.length if the destination array has more elements than the\r
4250      * source array.\r
4251      * There must be no duplicate indexes (two or more elements with the\r
4252      * same value except <code>MAP_NOWHERE</code>).\r
4253      *\r
4254      * @return an array representing the inverse map.\r
4255      *         This array has a number of elements equal to 1 + the highest\r
4256      *         value in <code>srcMap</code>.\r
4257      *         For elements of the result array which have no matching elements\r
4258      *         in the source array, the corresponding elements in the inverse\r
4259      *         map will receive a value equal to <code>MAP_NOWHERE</code>.\r
4260      *         If element with index i in <code>srcMap</code> has a value k different\r
4261      *         from <code>MAP_NOWHERE</code>, this means that element i of\r
4262      *         the source array maps to element k in the destination array.\r
4263      *         The inverse map will have value i in its k-th element.\r
4264      *         For all elements of the destination array which do not map to\r
4265      *         an element in the source array, the corresponding element in the\r
4266      *         inverse map will have a value equal to <code>MAP_NOWHERE</code>.\r
4267      *\r
4268      * @see #MAP_NOWHERE\r
4269      * @stable ICU 3.8\r
4270      */\r
4271     public static int[] invertMap(int[] srcMap)\r
4272     {\r
4273         if (srcMap == null) {\r
4274             return null;\r
4275         } else {\r
4276             return BidiLine.invertMap(srcMap);\r
4277         }\r
4278     }\r
4279 \r
4280     /*\r
4281      * Fields and methods for compatibility with java.text.bidi (Sun implementation)\r
4282      */\r
4283 \r
4284     /**\r
4285      * Constant indicating base direction is left-to-right.\r
4286      * @stable ICU 3.8\r
4287      */\r
4288     public static final int DIRECTION_LEFT_TO_RIGHT = LTR;\r
4289 \r
4290     /**\r
4291      * Constant indicating base direction is right-to-left.\r
4292      * @stable ICU 3.8\r
4293      */\r
4294     public static final int DIRECTION_RIGHT_TO_LEFT = RTL;\r
4295 \r
4296     /**\r
4297      * Constant indicating that the base direction depends on the first strong\r
4298      * directional character in the text according to the Unicode Bidirectional\r
4299      * Algorithm. If no strong directional character is present, the base\r
4300      * direction is left-to-right.\r
4301      * @stable ICU 3.8\r
4302      */\r
4303     public static final int DIRECTION_DEFAULT_LEFT_TO_RIGHT = LEVEL_DEFAULT_LTR;\r
4304 \r
4305     /**\r
4306      * Constant indicating that the base direction depends on the first strong\r
4307      * directional character in the text according to the Unicode Bidirectional\r
4308      * Algorithm. If no strong directional character is present, the base\r
4309      * direction is right-to-left.\r
4310      * @stable ICU 3.8\r
4311      */\r
4312     public static final int DIRECTION_DEFAULT_RIGHT_TO_LEFT = LEVEL_DEFAULT_RTL;\r
4313 \r
4314     /**\r
4315      * Create Bidi from the given paragraph of text and base direction.\r
4316      *\r
4317      * @param paragraph a paragraph of text\r
4318      * @param flags a collection of flags that control the algorithm. The\r
4319      *        algorithm understands the flags DIRECTION_LEFT_TO_RIGHT,\r
4320      *        DIRECTION_RIGHT_TO_LEFT, DIRECTION_DEFAULT_LEFT_TO_RIGHT, and\r
4321      *        DIRECTION_DEFAULT_RIGHT_TO_LEFT. Other values are reserved.\r
4322      * @see #DIRECTION_LEFT_TO_RIGHT\r
4323      * @see #DIRECTION_RIGHT_TO_LEFT\r
4324      * @see #DIRECTION_DEFAULT_LEFT_TO_RIGHT\r
4325      * @see #DIRECTION_DEFAULT_RIGHT_TO_LEFT\r
4326      * @stable ICU 3.8\r
4327      */\r
4328     public Bidi(String paragraph, int flags)\r
4329     {\r
4330         this(paragraph.toCharArray(), 0, null, 0, paragraph.length(), flags);\r
4331     }\r
4332 \r
4333     /**\r
4334      * Create Bidi from the given paragraph of text.<p>\r
4335      *\r
4336      * The RUN_DIRECTION attribute in the text, if present, determines the base\r
4337      * direction (left-to-right or right-to-left). If not present, the base\r
4338      * direction is computed using the Unicode Bidirectional Algorithm,\r
4339      * defaulting to left-to-right if there are no strong directional characters\r
4340      * in the text. This attribute, if present, must be applied to all the text\r
4341      * in the paragraph.<p>\r
4342      *\r
4343      * The BIDI_EMBEDDING attribute in the text, if present, represents\r
4344      * embedding level information. Negative values from -1 to -62 indicate\r
4345      * overrides at the absolute value of the level. Positive values from 1 to\r
4346      * 62 indicate embeddings. Where values are zero or not defined, the base\r
4347      * embedding level as determined by the base direction is assumed.<p>\r
4348      *\r
4349      * The NUMERIC_SHAPING attribute in the text, if present, converts European\r
4350      * digits to other decimal digits before running the bidi algorithm. This\r
4351      * attribute, if present, must be applied to all the text in the paragraph.<p>\r
4352      *\r
4353      * Note: this constructor calls setPara() internally.\r
4354      *\r
4355      * @param paragraph a paragraph of text with optional character and\r
4356      *        paragraph attribute information\r
4357      * @stable ICU 3.8\r
4358      */\r
4359     public Bidi(AttributedCharacterIterator paragraph)\r
4360     {\r
4361         this();\r
4362         setPara(paragraph);\r
4363     }\r
4364 \r
4365     /**\r
4366      * Create Bidi from the given text, embedding, and direction information.\r
4367      * The embeddings array may be null. If present, the values represent\r
4368      * embedding level information. Negative values from -1 to -61 indicate\r
4369      * overrides at the absolute value of the level. Positive values from 1 to\r
4370      * 61 indicate embeddings. Where values are zero, the base embedding level\r
4371      * as determined by the base direction is assumed.<p>\r
4372      *\r
4373      * Note: this constructor calls setPara() internally.\r
4374      *\r
4375      * @param text an array containing the paragraph of text to process.\r
4376      * @param textStart the index into the text array of the start of the\r
4377      *        paragraph.\r
4378      * @param embeddings an array containing embedding values for each character\r
4379      *        in the paragraph. This can be null, in which case it is assumed\r
4380      *        that there is no external embedding information.\r
4381      * @param embStart the index into the embedding array of the start of the\r
4382      *        paragraph.\r
4383      * @param paragraphLength the length of the paragraph in the text and\r
4384      *        embeddings arrays.\r
4385      * @param flags a collection of flags that control the algorithm. The\r
4386      *        algorithm understands the flags DIRECTION_LEFT_TO_RIGHT,\r
4387      *        DIRECTION_RIGHT_TO_LEFT, DIRECTION_DEFAULT_LEFT_TO_RIGHT, and\r
4388      *        DIRECTION_DEFAULT_RIGHT_TO_LEFT. Other values are reserved.\r
4389      *\r
4390      * @throws IllegalArgumentException if the values in embeddings are\r
4391      *         not within the allowed range\r
4392      *\r
4393      * @see #DIRECTION_LEFT_TO_RIGHT\r
4394      * @see #DIRECTION_RIGHT_TO_LEFT\r
4395      * @see #DIRECTION_DEFAULT_LEFT_TO_RIGHT\r
4396      * @see #DIRECTION_DEFAULT_RIGHT_TO_LEFT\r
4397      * @stable ICU 3.8\r
4398      */\r
4399     public Bidi(char[] text,\r
4400             int textStart,\r
4401             byte[] embeddings,\r
4402             int embStart,\r
4403             int paragraphLength,\r
4404             int flags)\r
4405     {\r
4406         this();\r
4407         byte paraLvl;\r
4408         switch (flags) {\r
4409         case DIRECTION_LEFT_TO_RIGHT:\r
4410         default:\r
4411             paraLvl = LTR;\r
4412             break;\r
4413         case DIRECTION_RIGHT_TO_LEFT:\r
4414             paraLvl = RTL;\r
4415             break;\r
4416         case DIRECTION_DEFAULT_LEFT_TO_RIGHT:\r
4417             paraLvl = LEVEL_DEFAULT_LTR;\r
4418             break;\r
4419         case DIRECTION_DEFAULT_RIGHT_TO_LEFT:\r
4420             paraLvl = LEVEL_DEFAULT_RTL;\r
4421             break;\r
4422         }\r
4423         byte[] paraEmbeddings;\r
4424         if (embeddings == null) {\r
4425             paraEmbeddings = null;\r
4426         } else {\r
4427             paraEmbeddings = new byte[paragraphLength];\r
4428             byte lev;\r
4429             for (int i = 0; i < paragraphLength; i++) {\r
4430                 lev = embeddings[i + embStart];\r
4431                 if (lev < 0) {\r
4432                     lev = (byte)((- lev) | LEVEL_OVERRIDE);\r
4433                 } else if (lev == 0) {\r
4434                     lev = paraLvl;\r
4435                     if (paraLvl > MAX_EXPLICIT_LEVEL) {\r
4436                         lev &= 1;\r
4437                     }\r
4438                 }\r
4439                 paraEmbeddings[i] = lev;\r
4440             }\r
4441         }\r
4442         if (textStart == 0 && embStart == 0 && paragraphLength == text.length) {\r
4443             setPara(text, paraLvl, paraEmbeddings);\r
4444         } else {\r
4445             char[] paraText = new char[paragraphLength];\r
4446             System.arraycopy(text, textStart, paraText, 0, paragraphLength);\r
4447             setPara(paraText, paraLvl, paraEmbeddings);\r
4448         }\r
4449     }\r
4450 \r
4451     /**\r
4452      * Create a Bidi object representing the bidi information on a line of text\r
4453      * within the paragraph represented by the current Bidi. This call is not\r
4454      * required if the entire paragraph fits on one line.\r
4455      *\r
4456      * @param lineStart the offset from the start of the paragraph to the start\r
4457      *        of the line.\r
4458      * @param lineLimit the offset from the start of the paragraph to the limit\r
4459      *        of the line.\r
4460      *\r
4461      * @throws IllegalStateException if this call is not preceded by a successful\r
4462      *         call to <code>setPara</code>\r
4463      * @throws IllegalArgumentException if lineStart and lineLimit are not in the range\r
4464      *         <code>0&lt;=lineStart&lt;lineLimit&lt;=getProcessedLength()</code>,\r
4465      *         or if the specified line crosses a paragraph boundary\r
4466      * @stable ICU 3.8\r
4467      */\r
4468     public Bidi createLineBidi(int lineStart, int lineLimit)\r
4469     {\r
4470         return setLine(lineStart, lineLimit);\r
4471     }\r
4472 \r
4473     /**\r
4474      * Return true if the line is not left-to-right or right-to-left. This means\r
4475      * it either has mixed runs of left-to-right and right-to-left text, or the\r
4476      * base direction differs from the direction of the only run of text.\r
4477      *\r
4478      * @return true if the line is not left-to-right or right-to-left.\r
4479      *\r
4480      * @throws IllegalStateException if this call is not preceded by a successful\r
4481      *         call to <code>setPara</code>\r
4482      * @stable ICU 3.8\r
4483      */\r
4484     public boolean isMixed()\r
4485     {\r
4486         return (!isLeftToRight() && !isRightToLeft());\r
4487     }\r
4488 \r
4489     /**\r
4490      * Return true if the line is all left-to-right text and the base direction\r
4491      * is left-to-right.\r
4492      *\r
4493      * @return true if the line is all left-to-right text and the base direction\r
4494      *         is left-to-right.\r
4495      *\r
4496      * @throws IllegalStateException if this call is not preceded by a successful\r
4497      *         call to <code>setPara</code>\r
4498      * @stable ICU 3.8\r
4499      */\r
4500     public boolean isLeftToRight()\r
4501     {\r
4502         return (getDirection() == LTR && (paraLevel & 1) == 0);\r
4503     }\r
4504 \r
4505     /**\r
4506      * Return true if the line is all right-to-left text, and the base direction\r
4507      * is right-to-left\r
4508      *\r
4509      * @return true if the line is all right-to-left text, and the base\r
4510      *         direction is right-to-left\r
4511      *\r
4512      * @throws IllegalStateException if this call is not preceded by a successful\r
4513      *         call to <code>setPara</code>\r
4514      * @stable ICU 3.8\r
4515      */\r
4516     public boolean isRightToLeft()\r
4517     {\r
4518         return (getDirection() == RTL && (paraLevel & 1) == 1);\r
4519     }\r
4520 \r
4521     /**\r
4522      * Return true if the base direction is left-to-right\r
4523      *\r
4524      * @return true if the base direction is left-to-right\r
4525      *\r
4526      * @throws IllegalStateException if this call is not preceded by a successful\r
4527      *         call to <code>setPara</code> or <code>setLine</code>\r
4528      *\r
4529      * @stable ICU 3.8\r
4530      */\r
4531     public boolean baseIsLeftToRight()\r
4532     {\r
4533         return (getParaLevel() == LTR);\r
4534     }\r
4535 \r
4536     /**\r
4537      * Return the base level (0 if left-to-right, 1 if right-to-left).\r
4538      *\r
4539      * @return the base level\r
4540      *\r
4541      * @throws IllegalStateException if this call is not preceded by a successful\r
4542      *         call to <code>setPara</code> or <code>setLine</code>\r
4543      *\r
4544      * @stable ICU 3.8\r
4545      */\r
4546     public int getBaseLevel()\r
4547     {\r
4548         return getParaLevel();\r
4549     }\r
4550 \r
4551     /**\r
4552      * Return the number of level runs.\r
4553      *\r
4554      * @return the number of level runs\r
4555      *\r
4556      * @throws IllegalStateException if this call is not preceded by a successful\r
4557      *         call to <code>setPara</code> or <code>setLine</code>\r
4558      *\r
4559      * @stable ICU 3.8\r
4560      */\r
4561     public int getRunCount()\r
4562     {\r
4563         return countRuns();\r
4564     }\r
4565 \r
4566     /**\r
4567      * Compute the logical to visual run mapping\r
4568      */\r
4569      void getLogicalToVisualRunsMap()\r
4570      {\r
4571         if (isGoodLogicalToVisualRunsMap) {\r
4572             return;\r
4573         }\r
4574         int count = countRuns();\r
4575         if ((logicalToVisualRunsMap == null) ||\r
4576             (logicalToVisualRunsMap.length < count)) {\r
4577             logicalToVisualRunsMap = new int[count];\r
4578         }\r
4579         int i;\r
4580         long[] keys = new long[count];\r
4581         for (i = 0; i < count; i++) {\r
4582             keys[i] = ((long)(runs[i].start)<<32) + i;\r
4583         }\r
4584         Arrays.sort(keys);\r
4585         for (i = 0; i < count; i++) {\r
4586             logicalToVisualRunsMap[i] = (int)(keys[i] & 0x00000000FFFFFFFF);\r
4587         }\r
4588         keys = null;\r
4589         isGoodLogicalToVisualRunsMap = true;\r
4590      }\r
4591 \r
4592     /**\r
4593      * Return the level of the nth logical run in this line.\r
4594      *\r
4595      * @param run the index of the run, between 0 and <code>countRuns()-1</code>\r
4596      *\r
4597      * @return the level of the run\r
4598      *\r
4599      * @throws IllegalStateException if this call is not preceded by a successful\r
4600      *         call to <code>setPara</code> or <code>setLine</code>\r
4601      * @throws IllegalArgumentException if <code>run</code> is not in\r
4602      *         the range <code>0&lt;=run&lt;countRuns()</code>\r
4603      * @stable ICU 3.8\r
4604      */\r
4605     public int getRunLevel(int run)\r
4606     {\r
4607         verifyValidParaOrLine();\r
4608         BidiLine.getRuns(this);\r
4609         verifyRange(run, 0, runCount);\r
4610         getLogicalToVisualRunsMap();\r
4611         return runs[logicalToVisualRunsMap[run]].level;\r
4612     }\r
4613 \r
4614     /**\r
4615      * Return the index of the character at the start of the nth logical run in\r
4616      * this line, as an offset from the start of the line.\r
4617      *\r
4618      * @param run the index of the run, between 0 and <code>countRuns()</code>\r
4619      *\r
4620      * @return the start of the run\r
4621      *\r
4622      * @throws IllegalStateException if this call is not preceded by a successful\r
4623      *         call to <code>setPara</code> or <code>setLine</code>\r
4624      * @throws IllegalArgumentException if <code>run</code> is not in\r
4625      *         the range <code>0&lt;=run&lt;countRuns()</code>\r
4626      * @stable ICU 3.8\r
4627      */\r
4628     public int getRunStart(int run)\r
4629     {\r
4630         verifyValidParaOrLine();\r
4631         BidiLine.getRuns(this);\r
4632         verifyRange(run, 0, runCount);\r
4633         getLogicalToVisualRunsMap();\r
4634         return runs[logicalToVisualRunsMap[run]].start;\r
4635     }\r
4636 \r
4637     /**\r
4638      * Return the index of the character past the end of the nth logical run in\r
4639      * this line, as an offset from the start of the line. For example, this\r
4640      * will return the length of the line for the last run on the line.\r
4641      *\r
4642      * @param run the index of the run, between 0 and <code>countRuns()</code>\r
4643      *\r
4644      * @return the limit of the run\r
4645      *\r
4646      * @throws IllegalStateException if this call is not preceded by a successful\r
4647      *         call to <code>setPara</code> or <code>setLine</code>\r
4648      * @throws IllegalArgumentException if <code>run</code> is not in\r
4649      *         the range <code>0&lt;=run&lt;countRuns()</code>\r
4650      * @stable ICU 3.8\r
4651      */\r
4652     public int getRunLimit(int run)\r
4653     {\r
4654         verifyValidParaOrLine();\r
4655         BidiLine.getRuns(this);\r
4656         verifyRange(run, 0, runCount);\r
4657         getLogicalToVisualRunsMap();\r
4658         int idx = logicalToVisualRunsMap[run];\r
4659         int len = idx == 0 ? runs[idx].limit :\r
4660                                 runs[idx].limit - runs[idx-1].limit;\r
4661         return runs[idx].start + len;\r
4662     }\r
4663 \r
4664     /**\r
4665      * Return true if the specified text requires bidi analysis. If this returns\r
4666      * false, the text will display left-to-right. Clients can then avoid\r
4667      * constructing a Bidi object. Text in the Arabic Presentation Forms area of\r
4668      * Unicode is presumed to already be shaped and ordered for display, and so\r
4669      * will not cause this method to return true.\r
4670      *\r
4671      * @param text the text containing the characters to test\r
4672      * @param start the start of the range of characters to test\r
4673      * @param limit the limit of the range of characters to test\r
4674      *\r
4675      * @return true if the range of characters requires bidi analysis\r
4676      *\r
4677      * @stable ICU 3.8\r
4678      */\r
4679     public static boolean requiresBidi(char[] text,\r
4680             int start,\r
4681             int limit)\r
4682     {\r
4683         final int RTLMask = (1 << UCharacter.DIRECTIONALITY_RIGHT_TO_LEFT |\r
4684                 1 << UCharacter.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC |\r
4685                 1 << UCharacter.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING |\r
4686                 1 << UCharacter.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE |\r
4687                 1 << UCharacter.DIRECTIONALITY_ARABIC_NUMBER);\r
4688 \r
4689         for (int i = start; i < limit; ++i) {\r
4690             if (((1 << UCharacter.getDirection(text[i])) & RTLMask) != 0) {\r
4691                 return true;\r
4692             }\r
4693         }\r
4694         return false;\r
4695     }\r
4696 \r
4697     /**\r
4698      * Reorder the objects in the array into visual order based on their levels.\r
4699      * This is a utility method to use when you have a collection of objects\r
4700      * representing runs of text in logical order, each run containing text at a\r
4701      * single level. The elements at <code>index</code> from\r
4702      * <code>objectStart</code> up to <code>objectStart + count</code> in the\r
4703      * objects array will be reordered into visual order assuming\r
4704      * each run of text has the level indicated by the corresponding element in\r
4705      * the levels array (at <code>index - objectStart + levelStart</code>).\r
4706      *\r
4707      * @param levels an array representing the bidi level of each object\r
4708      * @param levelStart the start position in the levels array\r
4709      * @param objects the array of objects to be reordered into visual order\r
4710      * @param objectStart the start position in the objects array\r
4711      * @param count the number of objects to reorder\r
4712      * @stable ICU 3.8\r
4713      */\r
4714     public static void reorderVisually(byte[] levels,\r
4715             int levelStart,\r
4716             Object[] objects,\r
4717             int objectStart,\r
4718             int count)\r
4719     {\r
4720         byte[] reorderLevels = new byte[count];\r
4721         System.arraycopy(levels, levelStart, reorderLevels, 0, count);\r
4722         int[] indexMap = reorderVisual(reorderLevels);\r
4723         Object[] temp = new Object[count];\r
4724         System.arraycopy(objects, objectStart, temp, 0, count);\r
4725         for (int i = 0; i < count; ++i) {\r
4726             objects[objectStart + i] = temp[indexMap[i]];\r
4727         }\r
4728     }\r
4729 \r
4730     /**\r
4731      * Take a <code>Bidi</code> object containing the reordering\r
4732      * information for a piece of text (one or more paragraphs) set by\r
4733      * <code>setPara()</code> or for a line of text set by <code>setLine()</code>\r
4734      * and return a string containing the reordered text.\r
4735      *\r
4736      * <p>The text may have been aliased (only a reference was stored\r
4737      * without copying the contents), thus it must not have been modified\r
4738      * since the <code>setPara()</code> call.</p>\r
4739      *\r
4740      * This method preserves the integrity of characters with multiple\r
4741      * code units and (optionally) combining characters.\r
4742      * Characters in RTL runs can be replaced by mirror-image characters\r
4743      * in the returned string. Note that "real" mirroring has to be done in a\r
4744      * rendering engine by glyph selection and that for many "mirrored"\r
4745      * characters there are no Unicode characters as mirror-image equivalents.\r
4746      * There are also options to insert or remove Bidi control\r
4747      * characters; see the descriptions of the return value and the\r
4748      * <code>options</code> parameter, and of the option bit flags.\r
4749      *\r
4750      * @param options A bit set of options for the reordering that control\r
4751      *                how the reordered text is written.\r
4752      *                The options include mirroring the characters on a code\r
4753      *                point basis and inserting LRM characters, which is used\r
4754      *                especially for transforming visually stored text\r
4755      *                to logically stored text (although this is still an\r
4756      *                imperfect implementation of an "inverse Bidi" algorithm\r
4757      *                because it uses the "forward Bidi" algorithm at its core).\r
4758      *                The available options are:\r
4759      *                <code>DO_MIRRORING</code>,\r
4760      *                <code>INSERT_LRM_FOR_NUMERIC</code>,\r
4761      *                <code>KEEP_BASE_COMBINING</code>,\r
4762      *                <code>OUTPUT_REVERSE</code>,\r
4763      *                <code>REMOVE_BIDI_CONTROLS</code>,\r
4764      *                <code>STREAMING</code>\r
4765      *\r
4766      * @return The reordered text.\r
4767      *         If the <code>INSERT_LRM_FOR_NUMERIC</code> option is set, then\r
4768      *         the length of the returned string could be as large as\r
4769      *         <code>getLength()+2*countRuns()</code>.<br>\r
4770      *         If the <code>REMOVE_BIDI_CONTROLS</code> option is set, then the\r
4771      *         length of the returned string may be less than\r
4772      *         <code>getLength()</code>.<br>\r
4773      *         If none of these options is set, then the length of the returned\r
4774      *         string will be exactly <code>getProcessedLength()</code>.\r
4775      *\r
4776      * @throws IllegalStateException if this call is not preceded by a successful\r
4777      *         call to <code>setPara</code> or <code>setLine</code>\r
4778      *\r
4779      * @see #DO_MIRRORING\r
4780      * @see #INSERT_LRM_FOR_NUMERIC\r
4781      * @see #KEEP_BASE_COMBINING\r
4782      * @see #OUTPUT_REVERSE\r
4783      * @see #REMOVE_BIDI_CONTROLS\r
4784      * @see #OPTION_STREAMING\r
4785      * @see #getProcessedLength\r
4786      * @stable ICU 3.8\r
4787      */\r
4788     public String writeReordered(int options)\r
4789     {\r
4790         verifyValidParaOrLine();\r
4791         if (length == 0) {\r
4792             /* nothing to do */\r
4793             return "";\r
4794         }\r
4795 \r
4796         return BidiWriter.writeReordered(this, options);\r
4797     }\r
4798 \r
4799     /**\r
4800      * Reverse a Right-To-Left run of Unicode text.\r
4801      *\r
4802      * This method preserves the integrity of characters with multiple\r
4803      * code units and (optionally) combining characters.\r
4804      * Characters can be replaced by mirror-image characters\r
4805      * in the destination buffer. Note that "real" mirroring has\r
4806      * to be done in a rendering engine by glyph selection\r
4807      * and that for many "mirrored" characters there are no\r
4808      * Unicode characters as mirror-image equivalents.\r
4809      * There are also options to insert or remove Bidi control\r
4810      * characters.\r
4811      *\r
4812      * This method is the implementation for reversing RTL runs as part\r
4813      * of <code>writeReordered()</code>. For detailed descriptions\r
4814      * of the parameters, see there.\r
4815      * Since no Bidi controls are inserted here, the output string length\r
4816      * will never exceed <code>src.length()</code>.\r
4817      *\r
4818      * @see #writeReordered\r
4819      *\r
4820      * @param src The RTL run text.\r
4821      *\r
4822      * @param options A bit set of options for the reordering that control\r
4823      *                how the reordered text is written.\r
4824      *                See the <code>options</code> parameter in <code>writeReordered()</code>.\r
4825      *\r
4826      * @return The reordered text.\r
4827      *         If the <code>REMOVE_BIDI_CONTROLS</code> option\r
4828      *         is set, then the length of the returned string may be less than\r
4829      *         <code>src.length()</code>. If this option is not set,\r
4830      *         then the length of the returned string will be exactly\r
4831      *         <code>src.length()</code>.\r
4832      *\r
4833      * @throws IllegalArgumentException if <code>src</code> is null.\r
4834      * @stable ICU 3.8\r
4835      */\r
4836     public static String writeReverse(String src, int options)\r
4837     {\r
4838         /* error checking */\r
4839         if (src == null) {\r
4840             throw new IllegalArgumentException();\r
4841         }\r
4842 \r
4843         if (src.length() > 0) {\r
4844             return BidiWriter.writeReverse(src, options);\r
4845         } else {\r
4846             /* nothing to do */\r
4847             return "";\r
4848         }\r
4849     }\r
4850 \r
4851 }\r