]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-4_8_1_1/main/classes/core/src/com/ibm/icu/text/BidiLine.java
Added flags.
[Dictionary.git] / jars / icu4j-4_8_1_1 / main / classes / core / src / com / ibm / icu / text / BidiLine.java
1 /*
2 *******************************************************************************
3 *   Copyright (C) 2001-2009, International Business Machines
4 *   Corporation and others.  All Rights Reserved.
5 *******************************************************************************
6 */
7 /* Written by Simon Montagu, Matitiahu Allouche
8  * (ported from C code written by Markus W. Scherer)
9  */
10
11 package com.ibm.icu.text;
12
13
14 import java.util.Arrays;
15
16 final class BidiLine {
17
18     /*
19      * General remarks about the functions in this file:
20      *
21      * These functions deal with the aspects of potentially mixed-directional
22      * text in a single paragraph or in a line of a single paragraph
23      * which has already been processed according to
24      * the Unicode 3.0 Bidi algorithm as defined in
25      * http://www.unicode.org/unicode/reports/tr9/ , version 13,
26      * also described in The Unicode Standard, Version 4.0.1 .
27      *
28      * This means that there is a Bidi object with a levels
29      * and a dirProps array.
30      * paraLevel and direction are also set.
31      * Only if the length of the text is zero, then levels==dirProps==NULL.
32      *
33      * The overall directionality of the paragraph
34      * or line is used to bypass the reordering steps if possible.
35      * Even purely RTL text does not need reordering there because
36      * the getLogical/VisualIndex() methods can compute the
37      * index on the fly in such a case.
38      *
39      * The implementation of the access to same-level-runs and of the reordering
40      * do attempt to provide better performance and less memory usage compared to
41      * a direct implementation of especially rule (L2) with an array of
42      * one (32-bit) integer per text character.
43      *
44      * Here, the levels array is scanned as soon as necessary, and a vector of
45      * same-level-runs is created. Reordering then is done on this vector.
46      * For each run of text positions that were resolved to the same level,
47      * only 8 bytes are stored: the first text position of the run and the visual
48      * position behind the run after reordering.
49      * One sign bit is used to hold the directionality of the run.
50      * This is inefficient if there are many very short runs. If the average run
51      * length is <2, then this uses more memory.
52      *
53      * In a further attempt to save memory, the levels array is never changed
54      * after all the resolution rules (Xn, Wn, Nn, In).
55      * Many methods have to consider the field trailingWSStart:
56      * if it is less than length, then there is an implicit trailing run
57      * at the paraLevel,
58      * which is not reflected in the levels array.
59      * This allows a line Bidi object to use the same levels array as
60      * its paragraph parent object.
61      *
62      * When a Bidi object is created for a line of a paragraph, then the
63      * paragraph's levels and dirProps arrays are reused by way of setting
64      * a pointer into them, not by copying. This again saves memory and forbids to
65      * change the now shared levels for (L1).
66      */
67
68     /* handle trailing WS (L1) -------------------------------------------------- */
69
70     /*
71      * setTrailingWSStart() sets the start index for a trailing
72      * run of WS in the line. This is necessary because we do not modify
73      * the paragraph's levels array that we just point into.
74      * Using trailingWSStart is another form of performing (L1).
75      *
76      * To make subsequent operations easier, we also include the run
77      * before the WS if it is at the paraLevel - we merge the two here.
78      *
79      * This method is called only from setLine(), so paraLevel is
80      * set correctly for the line even when contextual multiple paragraphs.
81      */
82
83     static void setTrailingWSStart(Bidi bidi)
84     {
85         byte[] dirProps = bidi.dirProps;
86         byte[] levels = bidi.levels;
87         int start = bidi.length;
88         byte paraLevel = bidi.paraLevel;
89
90         /* If the line is terminated by a block separator, all preceding WS etc...
91            are already set to paragraph level.
92            Setting trailingWSStart to pBidi->length will avoid changing the
93            level of B chars from 0 to paraLevel in getLevels when
94            orderParagraphsLTR==TRUE
95         */
96         if (Bidi.NoContextRTL(dirProps[start - 1]) == Bidi.B) {
97             bidi.trailingWSStart = start;   /* currently == bidi.length */
98             return;
99         }
100         /* go backwards across all WS, BN, explicit codes */
101         while (start > 0 &&
102                 (Bidi.DirPropFlagNC(dirProps[start - 1]) & Bidi.MASK_WS) != 0) {
103             --start;
104         }
105
106         /* if the WS run can be merged with the previous run then do so here */
107         while (start > 0 && levels[start - 1] == paraLevel) {
108             --start;
109         }
110
111         bidi.trailingWSStart=start;
112     }
113
114     static Bidi setLine(Bidi paraBidi, int start, int limit) {
115         int length;
116
117         Bidi lineBidi = new Bidi();
118
119         /* set the values in lineBidi from its paraBidi parent */
120         /* class members are already initialized to 0 */
121         // lineBidi.paraBidi = null;        /* mark unfinished setLine */
122         // lineBidi.flags = 0;
123         // lineBidi.controlCount = 0;
124
125         length = lineBidi.length = lineBidi.originalLength =
126                 lineBidi.resultLength = limit - start;
127
128         lineBidi.text = new char[length];
129         System.arraycopy(paraBidi.text, start, lineBidi.text, 0, length);
130         lineBidi.paraLevel = paraBidi.GetParaLevelAt(start);
131         lineBidi.paraCount = paraBidi.paraCount;
132         lineBidi.runs = new BidiRun[0];
133         lineBidi.reorderingMode = paraBidi.reorderingMode;
134         lineBidi.reorderingOptions = paraBidi.reorderingOptions;
135         if (paraBidi.controlCount > 0) {
136             int j;
137             for (j = start; j < limit; j++) {
138                 if (Bidi.IsBidiControlChar(paraBidi.text[j])) {
139                     lineBidi.controlCount++;
140                 }
141             }
142             lineBidi.resultLength -= lineBidi.controlCount;
143         }
144         /* copy proper subset of DirProps */
145         lineBidi.getDirPropsMemory(length);
146         lineBidi.dirProps = lineBidi.dirPropsMemory;
147         System.arraycopy(paraBidi.dirProps, start, lineBidi.dirProps, 0,
148                          length);
149         /* copy proper subset of Levels */
150         lineBidi.getLevelsMemory(length);
151         lineBidi.levels = lineBidi.levelsMemory;
152         System.arraycopy(paraBidi.levels, start, lineBidi.levels, 0,
153                          length);
154         lineBidi.runCount = -1;
155
156         if (paraBidi.direction != Bidi.MIXED) {
157             /* the parent is already trivial */
158             lineBidi.direction = paraBidi.direction;
159
160             /*
161              * The parent's levels are all either
162              * implicitly or explicitly ==paraLevel;
163              * do the same here.
164              */
165             if (paraBidi.trailingWSStart <= start) {
166                 lineBidi.trailingWSStart = 0;
167             } else if (paraBidi.trailingWSStart < limit) {
168                 lineBidi.trailingWSStart = paraBidi.trailingWSStart - start;
169             } else {
170                 lineBidi.trailingWSStart = length;
171             }
172         } else {
173             byte[] levels = lineBidi.levels;
174             int i, trailingWSStart;
175             byte level;
176
177             setTrailingWSStart(lineBidi);
178             trailingWSStart = lineBidi.trailingWSStart;
179
180             /* recalculate lineBidi.direction */
181             if (trailingWSStart == 0) {
182                 /* all levels are at paraLevel */
183                 lineBidi.direction = (byte)(lineBidi.paraLevel & 1);
184             } else {
185                 /* get the level of the first character */
186                 level = (byte)(levels[0] & 1);
187
188                 /* if there is anything of a different level, then the line
189                    is mixed */
190                 if (trailingWSStart < length &&
191                     (lineBidi.paraLevel & 1) != level) {
192                     /* the trailing WS is at paraLevel, which differs from
193                        levels[0] */
194                     lineBidi.direction = Bidi.MIXED;
195                 } else {
196                     /* see if levels[1..trailingWSStart-1] have the same
197                        direction as levels[0] and paraLevel */
198                     for (i = 1; ; i++) {
199                         if (i == trailingWSStart) {
200                             /* the direction values match those in level */
201                             lineBidi.direction = level;
202                             break;
203                         } else if ((levels[i] & 1) != level) {
204                             lineBidi.direction = Bidi.MIXED;
205                             break;
206                         }
207                     }
208                 }
209             }
210
211             switch(lineBidi.direction) {
212                 case Bidi.DIRECTION_LEFT_TO_RIGHT:
213                     /* make sure paraLevel is even */
214                     lineBidi.paraLevel = (byte)
215                         ((lineBidi.paraLevel + 1) & ~1);
216
217                     /* all levels are implicitly at paraLevel (important for
218                        getLevels()) */
219                     lineBidi.trailingWSStart = 0;
220                     break;
221                 case Bidi.DIRECTION_RIGHT_TO_LEFT:
222                     /* make sure paraLevel is odd */
223                     lineBidi.paraLevel |= 1;
224
225                     /* all levels are implicitly at paraLevel (important for
226                        getLevels()) */
227                     lineBidi.trailingWSStart = 0;
228                     break;
229                 default:
230                     break;
231             }
232         }
233         lineBidi.paraBidi = paraBidi;     /* mark successful setLine */
234         return lineBidi;
235     }
236
237     static byte getLevelAt(Bidi bidi, int charIndex)
238     {
239         /* return paraLevel if in the trailing WS run, otherwise the real level */
240         if (bidi.direction != Bidi.MIXED || charIndex >= bidi.trailingWSStart) {
241             return bidi.GetParaLevelAt(charIndex);
242         } else {
243             return bidi.levels[charIndex];
244         }
245     }
246
247     static byte[] getLevels(Bidi bidi)
248     {
249         int start = bidi.trailingWSStart;
250         int length = bidi.length;
251
252         if (start != length) {
253             /* the current levels array does not reflect the WS run */
254             /*
255              * After the previous if(), we know that the levels array
256              * has an implicit trailing WS run and therefore does not fully
257              * reflect itself all the levels.
258              * This must be a Bidi object for a line, and
259              * we need to create a new levels array.
260              */
261             /* bidi.paraLevel is ok even if contextual multiple paragraphs,
262                since bidi is a line object                                     */
263             Arrays.fill(bidi.levels, start, length, bidi.paraLevel);
264
265             /* this new levels array is set for the line and reflects the WS run */
266             bidi.trailingWSStart = length;
267         }
268         if (length < bidi.levels.length) {
269             byte[] levels = new byte[length];
270             System.arraycopy(bidi.levels, 0, levels, 0, length);
271             return levels;
272         }
273         return bidi.levels;
274     }
275
276     static BidiRun getLogicalRun(Bidi bidi, int logicalPosition)
277     {
278         /* this is done based on runs rather than on levels since levels have
279            a special interpretation when REORDER_RUNS_ONLY
280          */
281         BidiRun newRun = new BidiRun(), iRun;
282         getRuns(bidi);
283         int runCount = bidi.runCount;
284         int visualStart = 0, logicalLimit = 0;
285         iRun = bidi.runs[0];
286
287         for (int i = 0; i < runCount; i++) {
288             iRun = bidi.runs[i];
289             logicalLimit = iRun.start + iRun.limit - visualStart;
290             if ((logicalPosition >= iRun.start) &&
291                 (logicalPosition < logicalLimit)) {
292                 break;
293             }
294             visualStart = iRun.limit;
295         }
296         newRun.start = iRun.start;
297         newRun.limit = logicalLimit;
298         newRun.level = iRun.level;
299         return newRun;
300     }
301
302     static BidiRun getVisualRun(Bidi bidi, int runIndex)
303     {
304         int start = bidi.runs[runIndex].start;
305         int limit;
306         byte level = bidi.runs[runIndex].level;
307
308         if (runIndex > 0) {
309             limit = start +
310                     bidi.runs[runIndex].limit -
311                     bidi.runs[runIndex - 1].limit;
312         } else {
313             limit = start + bidi.runs[0].limit;
314         }
315         return new BidiRun(start, limit, level);
316     }
317
318     /* in trivial cases there is only one trivial run; called by getRuns() */
319     static void getSingleRun(Bidi bidi, byte level) {
320         /* simple, single-run case */
321         bidi.runs = bidi.simpleRuns;
322         bidi.runCount = 1;
323
324         /* fill and reorder the single run */
325         bidi.runs[0] = new BidiRun(0, bidi.length, level);
326     }
327
328     /* reorder the runs array (L2) ---------------------------------------------- */
329
330     /*
331      * Reorder the same-level runs in the runs array.
332      * Here, runCount>1 and maxLevel>=minLevel>=paraLevel.
333      * All the visualStart fields=logical start before reordering.
334      * The "odd" bits are not set yet.
335      *
336      * Reordering with this data structure lends itself to some handy shortcuts:
337      *
338      * Since each run is moved but not modified, and since at the initial maxLevel
339      * each sequence of same-level runs consists of only one run each, we
340      * don't need to do anything there and can predecrement maxLevel.
341      * In many simple cases, the reordering is thus done entirely in the
342      * index mapping.
343      * Also, reordering occurs only down to the lowest odd level that occurs,
344      * which is minLevel|1. However, if the lowest level itself is odd, then
345      * in the last reordering the sequence of the runs at this level or higher
346      * will be all runs, and we don't need the elaborate loop to search for them.
347      * This is covered by ++minLevel instead of minLevel|=1 followed
348      * by an extra reorder-all after the reorder-some loop.
349      * About a trailing WS run:
350      * Such a run would need special treatment because its level is not
351      * reflected in levels[] if this is not a paragraph object.
352      * Instead, all characters from trailingWSStart on are implicitly at
353      * paraLevel.
354      * However, for all maxLevel>paraLevel, this run will never be reordered
355      * and does not need to be taken into account. maxLevel==paraLevel is only reordered
356      * if minLevel==paraLevel is odd, which is done in the extra segment.
357      * This means that for the main reordering loop we don't need to consider
358      * this run and can --runCount. If it is later part of the all-runs
359      * reordering, then runCount is adjusted accordingly.
360      */
361     private static void reorderLine(Bidi bidi, byte minLevel, byte maxLevel) {
362
363         /* nothing to do? */
364         if (maxLevel<=(minLevel|1)) {
365             return;
366         }
367
368         BidiRun[] runs;
369         BidiRun tempRun;
370         byte[] levels;
371         int firstRun, endRun, limitRun, runCount;
372
373         /*
374          * Reorder only down to the lowest odd level
375          * and reorder at an odd minLevel in a separate, simpler loop.
376          * See comments above for why minLevel is always incremented.
377          */
378         ++minLevel;
379
380         runs = bidi.runs;
381         levels = bidi.levels;
382         runCount = bidi.runCount;
383
384         /* do not include the WS run at paraLevel<=old minLevel except in the simple loop */
385         if (bidi.trailingWSStart < bidi.length) {
386             --runCount;
387         }
388
389         while (--maxLevel >= minLevel) {
390             firstRun = 0;
391
392             /* loop for all sequences of runs */
393             for ( ; ; ) {
394                 /* look for a sequence of runs that are all at >=maxLevel */
395                 /* look for the first run of such a sequence */
396                 while (firstRun < runCount && levels[runs[firstRun].start] < maxLevel) {
397                     ++firstRun;
398                 }
399                 if (firstRun >= runCount) {
400                     break;  /* no more such runs */
401                 }
402
403                 /* look for the limit run of such a sequence (the run behind it) */
404                 for (limitRun = firstRun; ++limitRun < runCount &&
405                       levels[runs[limitRun].start]>=maxLevel; ) {}
406
407                 /* Swap the entire sequence of runs from firstRun to limitRun-1. */
408                 endRun = limitRun - 1;
409                 while (firstRun < endRun) {
410                     tempRun = runs[firstRun];
411                     runs[firstRun] = runs[endRun];
412                     runs[endRun] = tempRun;
413                     ++firstRun;
414                     --endRun;
415                 }
416
417                 if (limitRun == runCount) {
418                     break;  /* no more such runs */
419                 } else {
420                     firstRun = limitRun + 1;
421                 }
422             }
423         }
424
425         /* now do maxLevel==old minLevel (==odd!), see above */
426         if ((minLevel & 1) == 0) {
427             firstRun = 0;
428
429             /* include the trailing WS run in this complete reordering */
430             if (bidi.trailingWSStart == bidi.length) {
431                 --runCount;
432             }
433
434             /* Swap the entire sequence of all runs. (endRun==runCount) */
435             while (firstRun < runCount) {
436                 tempRun = runs[firstRun];
437                 runs[firstRun] = runs[runCount];
438                 runs[runCount] = tempRun;
439                 ++firstRun;
440                 --runCount;
441             }
442         }
443     }
444
445     /* compute the runs array --------------------------------------------------- */
446
447     static int getRunFromLogicalIndex(Bidi bidi, int logicalIndex) {
448         BidiRun[] runs = bidi.runs;
449         int runCount = bidi.runCount, visualStart = 0, i, length, logicalStart;
450
451         for (i = 0; i < runCount; i++) {
452             length = runs[i].limit - visualStart;
453             logicalStart = runs[i].start;
454             if ((logicalIndex >= logicalStart) && (logicalIndex < (logicalStart+length))) {
455                 return i;
456             }
457             visualStart += length;
458         }
459         ///CLOVER:OFF
460         /* we should never get here */
461         throw new IllegalStateException("Internal ICU error in getRunFromLogicalIndex");
462         ///CLOVER:ON
463     }
464
465     /*
466      * Compute the runs array from the levels array.
467      * After getRuns() returns true, runCount is guaranteed to be >0
468      * and the runs are reordered.
469      * Odd-level runs have visualStart on their visual right edge and
470      * they progress visually to the left.
471      * If option OPTION_INSERT_MARKS is set, insertRemove will contain the
472      * sum of appropriate LRM/RLM_BEFORE/AFTER flags.
473      * If option OPTION_REMOVE_CONTROLS is set, insertRemove will contain the
474      * negative number of BiDi control characters within this run.
475      */
476     static void getRuns(Bidi bidi) {
477         /*
478          * This method returns immediately if the runs are already set. This
479          * includes the case of length==0 (handled in setPara)..
480          */
481         if (bidi.runCount >= 0) {
482             return;
483         }
484         if (bidi.direction != Bidi.MIXED) {
485             /* simple, single-run case - this covers length==0 */
486             /* bidi.paraLevel is ok even for contextual multiple paragraphs */
487             getSingleRun(bidi, bidi.paraLevel);
488         } else /* Bidi.MIXED, length>0 */ {
489             /* mixed directionality */
490             int length = bidi.length, limit;
491             byte[] levels = bidi.levels;
492             int i, runCount;
493             byte level = Bidi.LEVEL_DEFAULT_LTR;   /* initialize with no valid level */
494             /*
495              * If there are WS characters at the end of the line
496              * and the run preceding them has a level different from
497              * paraLevel, then they will form their own run at paraLevel (L1).
498              * Count them separately.
499              * We need some special treatment for this in order to not
500              * modify the levels array which a line Bidi object shares
501              * with its paragraph parent and its other line siblings.
502              * In other words, for the trailing WS, it may be
503              * levels[]!=paraLevel but we have to treat it like it were so.
504              */
505             limit = bidi.trailingWSStart;
506             /* count the runs, there is at least one non-WS run, and limit>0 */
507             runCount = 0;
508             for (i = 0; i < limit; ++i) {
509                 /* increment runCount at the start of each run */
510                 if (levels[i] != level) {
511                     ++runCount;
512                     level = levels[i];
513                 }
514             }
515
516             /*
517              * We don't need to see if the last run can be merged with a trailing
518              * WS run because setTrailingWSStart() would have done that.
519              */
520             if (runCount == 1 && limit == length) {
521                 /* There is only one non-WS run and no trailing WS-run. */
522                 getSingleRun(bidi, levels[0]);
523             } else /* runCount>1 || limit<length */ {
524                 /* allocate and set the runs */
525                 BidiRun[] runs;
526                 int runIndex, start;
527                 byte minLevel = Bidi.MAX_EXPLICIT_LEVEL + 1;
528                 byte maxLevel=0;
529
530                 /* now, count a (non-mergeable) WS run */
531                 if (limit < length) {
532                     ++runCount;
533                 }
534
535                 /* runCount > 1 */
536                 bidi.getRunsMemory(runCount);
537                 runs = bidi.runsMemory;
538
539                 /* set the runs */
540                 /* FOOD FOR THOUGHT: this could be optimized, e.g.:
541                  * 464->444, 484->444, 575->555, 595->555
542                  * However, that would take longer. Check also how it would
543                  * interact with BiDi control removal and inserting Marks.
544                  */
545                 runIndex = 0;
546
547                 /* search for the run limits and initialize visualLimit values with the run lengths */
548                 i = 0;
549                 do {
550                     /* prepare this run */
551                     start = i;
552                     level = levels[i];
553                     if (level < minLevel) {
554                         minLevel = level;
555                     }
556                     if (level > maxLevel) {
557                         maxLevel = level;
558                     }
559
560                     /* look for the run limit */
561                     while (++i < limit && levels[i] == level) {}
562
563                     /* i is another run limit */
564                     runs[runIndex] = new BidiRun(start, i - start, level);
565                     ++runIndex;
566                 } while (i < limit);
567
568                 if (limit < length) {
569                     /* there is a separate WS run */
570                     runs[runIndex] = new BidiRun(limit, length - limit, bidi.paraLevel);
571                     /* For the trailing WS run, bidi.paraLevel is ok even
572                        if contextual multiple paragraphs.                   */
573                     if (bidi.paraLevel < minLevel) {
574                         minLevel = bidi.paraLevel;
575                     }
576                 }
577
578                 /* set the object fields */
579                 bidi.runs = runs;
580                 bidi.runCount = runCount;
581
582                 reorderLine(bidi, minLevel, maxLevel);
583
584                 /* now add the direction flags and adjust the visualLimit's to be just that */
585                 /* this loop will also handle the trailing WS run */
586                 limit = 0;
587                 for (i = 0; i < runCount; ++i) {
588                     runs[i].level = levels[runs[i].start];
589                     limit = (runs[i].limit += limit);
590                 }
591
592                 /* Set the embedding level for the trailing WS run. */
593                 /* For a RTL paragraph, it will be the *first* run in visual order. */
594                 /* For the trailing WS run, bidi.paraLevel is ok even if
595                    contextual multiple paragraphs.                          */
596                 if (runIndex < runCount) {
597                     int trailingRun = ((bidi.paraLevel & 1) != 0)? 0 : runIndex;
598                     runs[trailingRun].level = bidi.paraLevel;
599                 }
600             }
601         }
602
603         /* handle insert LRM/RLM BEFORE/AFTER run */
604         if (bidi.insertPoints.size > 0) {
605             Bidi.Point point;
606             int runIndex, ip;
607             for (ip = 0; ip < bidi.insertPoints.size; ip++) {
608                 point = bidi.insertPoints.points[ip];
609                 runIndex = getRunFromLogicalIndex(bidi, point.pos);
610                 bidi.runs[runIndex].insertRemove |= point.flag;
611             }
612         }
613
614         /* handle remove BiDi control characters */
615         if (bidi.controlCount > 0) {
616             int runIndex, ic;
617             char c;
618             for (ic = 0; ic < bidi.length; ic++) {
619                 c = bidi.text[ic];
620                 if (Bidi.IsBidiControlChar(c)) {
621                     runIndex = getRunFromLogicalIndex(bidi, ic);
622                     bidi.runs[runIndex].insertRemove--;
623                 }
624             }
625         }
626     }
627
628     static int[] prepareReorder(byte[] levels, byte[] pMinLevel, byte[] pMaxLevel)
629     {
630         int start;
631         byte level, minLevel, maxLevel;
632
633         if (levels == null || levels.length <= 0) {
634             return null;
635         }
636
637         /* determine minLevel and maxLevel */
638         minLevel = Bidi.MAX_EXPLICIT_LEVEL + 1;
639         maxLevel = 0;
640         for (start = levels.length; start>0; ) {
641             level = levels[--start];
642             if (level > Bidi.MAX_EXPLICIT_LEVEL + 1) {
643                 return null;
644             }
645             if (level < minLevel) {
646                 minLevel = level;
647             }
648             if (level > maxLevel) {
649                 maxLevel = level;
650             }
651         }
652         pMinLevel[0] = minLevel;
653         pMaxLevel[0] = maxLevel;
654
655         /* initialize the index map */
656         int[] indexMap = new int[levels.length];
657         for (start = levels.length; start > 0; ) {
658             --start;
659             indexMap[start] = start;
660         }
661
662         return indexMap;
663     }
664
665     static int[] reorderLogical(byte[] levels)
666     {
667         byte[] aMinLevel = new byte[1];
668         byte[] aMaxLevel = new byte[1];
669         int start, limit, sumOfSosEos;
670         byte minLevel, maxLevel;
671         int[] indexMap = prepareReorder(levels, aMinLevel, aMaxLevel);
672         if (indexMap == null) {
673             return null;
674         }
675
676         minLevel = aMinLevel[0];
677         maxLevel = aMaxLevel[0];
678
679         /* nothing to do? */
680         if (minLevel == maxLevel && (minLevel & 1) == 0) {
681             return indexMap;
682         }
683
684         /* reorder only down to the lowest odd level */
685         minLevel |= 1;
686
687         /* loop maxLevel..minLevel */
688         do {
689             start = 0;
690
691             /* loop for all sequences of levels to reorder at the current maxLevel */
692             for ( ; ; ) {
693                 /* look for a sequence of levels that are all at >=maxLevel */
694                 /* look for the first index of such a sequence */
695                 while (start < levels.length && levels[start] < maxLevel) {
696                     ++start;
697                 }
698                 if (start >= levels.length) {
699                     break;  /* no more such sequences */
700                 }
701
702                 /* look for the limit of such a sequence (the index behind it) */
703                 for (limit = start; ++limit < levels.length && levels[limit] >= maxLevel; ) {}
704
705                 /*
706                  * sos=start of sequence, eos=end of sequence
707                  *
708                  * The closed (inclusive) interval from sos to eos includes all the logical
709                  * and visual indexes within this sequence. They are logically and
710                  * visually contiguous and in the same range.
711                  *
712                  * For each run, the new visual index=sos+eos-old visual index;
713                  * we pre-add sos+eos into sumOfSosEos ->
714                  * new visual index=sumOfSosEos-old visual index;
715                  */
716                 sumOfSosEos = start + limit - 1;
717
718                 /* reorder each index in the sequence */
719                 do {
720                     indexMap[start] = sumOfSosEos - indexMap[start];
721                 } while (++start < limit);
722
723                 /* start==limit */
724                 if (limit == levels.length) {
725                     break;  /* no more such sequences */
726                 } else {
727                     start = limit + 1;
728                 }
729             }
730         } while (--maxLevel >= minLevel);
731         return indexMap;
732     }
733
734     static int[] reorderVisual(byte[] levels)
735     {
736         byte[] aMinLevel = new byte[1];
737         byte[] aMaxLevel = new byte[1];
738         int start, end, limit, temp;
739         byte minLevel, maxLevel;
740
741         int[] indexMap = prepareReorder(levels, aMinLevel, aMaxLevel);
742         if (indexMap == null) {
743             return null;
744         }
745
746         minLevel = aMinLevel[0];
747         maxLevel = aMaxLevel[0];
748
749         /* nothing to do? */
750         if (minLevel == maxLevel && (minLevel & 1) == 0) {
751             return indexMap;
752         }
753
754         /* reorder only down to the lowest odd level */
755         minLevel |= 1;
756
757         /* loop maxLevel..minLevel */
758         do {
759             start = 0;
760
761             /* loop for all sequences of levels to reorder at the current maxLevel */
762             for ( ; ; ) {
763                 /* look for a sequence of levels that are all at >=maxLevel */
764                 /* look for the first index of such a sequence */
765                 while (start < levels.length && levels[start] < maxLevel) {
766                     ++start;
767                 }
768                 if (start >= levels.length) {
769                     break;  /* no more such runs */
770                 }
771
772                 /* look for the limit of such a sequence (the index behind it) */
773                 for (limit = start; ++limit < levels.length && levels[limit] >= maxLevel; ) {}
774
775                 /*
776                  * Swap the entire interval of indexes from start to limit-1.
777                  * We don't need to swap the levels for the purpose of this
778                  * algorithm: the sequence of levels that we look at does not
779                  * move anyway.
780                  */
781                 end = limit - 1;
782                 while (start < end) {
783                     temp = indexMap[start];
784                     indexMap[start] = indexMap[end];
785                     indexMap[end] = temp;
786
787                     ++start;
788                     --end;
789                 }
790
791                 if (limit == levels.length) {
792                     break;  /* no more such sequences */
793                 } else {
794                     start = limit + 1;
795                 }
796             }
797         } while (--maxLevel >= minLevel);
798
799         return indexMap;
800     }
801
802     static int getVisualIndex(Bidi bidi, int logicalIndex)
803     {
804         int visualIndex = Bidi.MAP_NOWHERE;
805
806         /* we can do the trivial cases without the runs array */
807         switch(bidi.direction) {
808         case Bidi.LTR:
809             visualIndex = logicalIndex;
810             break;
811         case Bidi.RTL:
812             visualIndex = bidi.length - logicalIndex - 1;
813             break;
814         default:
815             getRuns(bidi);
816             BidiRun[] runs = bidi.runs;
817             int i, visualStart = 0, offset, length;
818
819             /* linear search for the run, search on the visual runs */
820             for (i = 0; i < bidi.runCount; ++i) {
821                 length = runs[i].limit - visualStart;
822                 offset = logicalIndex - runs[i].start;
823                 if (offset >= 0 && offset < length) {
824                     if (runs[i].isEvenRun()) {
825                         /* LTR */
826                         visualIndex = visualStart + offset;
827                     } else {
828                         /* RTL */
829                         visualIndex = visualStart + length - offset - 1;
830                     }
831                     break;                  /* exit for loop */
832                 }
833                 visualStart += length;
834             }
835             if (i >= bidi.runCount) {
836                 return Bidi.MAP_NOWHERE;
837             }
838         }
839
840         if (bidi.insertPoints.size > 0) {
841             /* add the number of added marks until the calculated visual index */
842             BidiRun runs[] = bidi.runs;
843             int i, length, insertRemove;
844             int visualStart = 0, markFound = 0;
845             for (i = 0; ; i++, visualStart += length) {
846                 length = runs[i].limit - visualStart;
847                 insertRemove = runs[i].insertRemove;
848                 if ((insertRemove & (Bidi.LRM_BEFORE|Bidi.RLM_BEFORE)) > 0) {
849                     markFound++;
850                 }
851                 /* is it the run containing the visual index? */
852                 if (visualIndex < runs[i].limit) {
853                     return visualIndex + markFound;
854                 }
855                 if ((insertRemove & (Bidi.LRM_AFTER|Bidi.RLM_AFTER)) > 0) {
856                     markFound++;
857                 }
858             }
859         }
860         else if (bidi.controlCount > 0) {
861             /* subtract the number of controls until the calculated visual index */
862             BidiRun[] runs = bidi.runs;
863             int i, j, start, limit, length, insertRemove;
864             int visualStart = 0, controlFound = 0;
865             char uchar = bidi.text[logicalIndex];
866             /* is the logical index pointing to a control ? */
867             if (Bidi.IsBidiControlChar(uchar)) {
868                 return Bidi.MAP_NOWHERE;
869             }
870             /* loop on runs */
871             for (i = 0; ; i++, visualStart += length) {
872                 length = runs[i].limit - visualStart;
873                 insertRemove = runs[i].insertRemove;
874                 /* calculated visual index is beyond this run? */
875                 if (visualIndex >= runs[i].limit) {
876                     controlFound -= insertRemove;
877                     continue;
878                 }
879                 /* calculated visual index must be within current run */
880                 if (insertRemove == 0) {
881                     return visualIndex - controlFound;
882                 }
883                 if (runs[i].isEvenRun()) {
884                     /* LTR: check from run start to logical index */
885                     start = runs[i].start;
886                     limit = logicalIndex;
887                 } else {
888                     /* RTL: check from logical index to run end */
889                     start = logicalIndex + 1;
890                     limit = runs[i].start + length;
891                 }
892                 for (j = start; j < limit; j++) {
893                     uchar = bidi.text[j];
894                     if (Bidi.IsBidiControlChar(uchar)) {
895                         controlFound++;
896                     }
897                 }
898                 return visualIndex - controlFound;
899             }
900         }
901
902         return visualIndex;
903     }
904
905     static int getLogicalIndex(Bidi bidi, int visualIndex)
906     {
907         BidiRun[] runs;
908         int i, runCount, start;
909
910         runs = bidi.runs;
911         runCount = bidi.runCount;
912         if (bidi.insertPoints.size > 0) {
913             /* handle inserted LRM/RLM */
914             int markFound = 0, insertRemove;
915             int visualStart = 0, length;
916             /* subtract number of marks until visual index */
917             for (i = 0; ; i++, visualStart += length) {
918                 length = runs[i].limit - visualStart;
919                 insertRemove = runs[i].insertRemove;
920                 if ((insertRemove & (Bidi.LRM_BEFORE|Bidi.RLM_BEFORE)) > 0) {
921                     if (visualIndex <= (visualStart+markFound)) {
922                         return Bidi.MAP_NOWHERE;
923                     }
924                     markFound++;
925                 }
926                 /* is adjusted visual index within this run? */
927                 if (visualIndex < (runs[i].limit + markFound)) {
928                     visualIndex -= markFound;
929                     break;
930                 }
931                 if ((insertRemove & (Bidi.LRM_AFTER|Bidi.RLM_AFTER)) > 0) {
932                     if (visualIndex == (visualStart + length + markFound)) {
933                         return Bidi.MAP_NOWHERE;
934                     }
935                     markFound++;
936                 }
937             }
938         }
939         else if (bidi.controlCount > 0) {
940             /* handle removed BiDi control characters */
941             int controlFound = 0, insertRemove, length;
942             int logicalStart, logicalEnd, visualStart = 0, j, k;
943             char uchar;
944             boolean evenRun;
945             /* add number of controls until visual index */
946             for (i = 0; ; i++, visualStart += length) {
947                 length = runs[i].limit - visualStart;
948                 insertRemove = runs[i].insertRemove;
949                 /* is adjusted visual index beyond current run? */
950                 if (visualIndex >= (runs[i].limit - controlFound + insertRemove)) {
951                     controlFound -= insertRemove;
952                     continue;
953                 }
954                 /* adjusted visual index is within current run */
955                 if (insertRemove == 0) {
956                     visualIndex += controlFound;
957                     break;
958                 }
959                 /* count non-control chars until visualIndex */
960                 logicalStart = runs[i].start;
961                 evenRun = runs[i].isEvenRun();
962                 logicalEnd = logicalStart + length - 1;
963                 for (j = 0; j < length; j++) {
964                     k= evenRun ? logicalStart+j : logicalEnd-j;
965                     uchar = bidi.text[k];
966                     if (Bidi.IsBidiControlChar(uchar)) {
967                         controlFound++;
968                     }
969                     if ((visualIndex + controlFound) == (visualStart + j)) {
970                         break;
971                     }
972                 }
973                 visualIndex += controlFound;
974                 break;
975             }
976         }
977         /* handle all cases */
978         if (runCount <= 10) {
979             /* linear search for the run */
980             for (i = 0; visualIndex >= runs[i].limit; ++i) {}
981         } else {
982             /* binary search for the run */
983             int begin = 0, limit = runCount;
984
985             /* the middle if() is guaranteed to find the run, we don't need a loop limit */
986             for ( ; ; ) {
987                 i = (begin + limit) / 2;
988                 if (visualIndex >= runs[i].limit) {
989                     begin = i + 1;
990                 } else if (i==0 || visualIndex >= runs[i-1].limit) {
991                     break;
992                 } else {
993                     limit = i;
994                 }
995             }
996         }
997
998         start= runs[i].start;
999         if (runs[i].isEvenRun()) {
1000             /* LTR */
1001             /* the offset in runs[i] is visualIndex-runs[i-1].visualLimit */
1002             if (i > 0) {
1003                 visualIndex -= runs[i - 1].limit;
1004             }
1005             return start + visualIndex;
1006         } else {
1007             /* RTL */
1008             return start + runs[i].limit - visualIndex - 1;
1009         }
1010     }
1011
1012     static int[] getLogicalMap(Bidi bidi)
1013     {
1014         /* fill a logical-to-visual index map using the runs[] */
1015         BidiRun[] runs = bidi.runs;
1016         int logicalStart, visualStart, logicalLimit, visualLimit;
1017         int[] indexMap = new int[bidi.length];
1018         if (bidi.length > bidi.resultLength) {
1019             Arrays.fill(indexMap, Bidi.MAP_NOWHERE);
1020         }
1021
1022         visualStart = 0;
1023         for (int j = 0; j < bidi.runCount; ++j) {
1024             logicalStart = runs[j].start;
1025             visualLimit = runs[j].limit;
1026             if (runs[j].isEvenRun()) {
1027                 do { /* LTR */
1028                     indexMap[logicalStart++] = visualStart++;
1029                 } while (visualStart < visualLimit);
1030             } else {
1031                 logicalStart += visualLimit - visualStart;  /* logicalLimit */
1032                 do { /* RTL */
1033                     indexMap[--logicalStart] = visualStart++;
1034                 } while (visualStart < visualLimit);
1035             }
1036             /* visualStart==visualLimit; */
1037         }
1038
1039         if (bidi.insertPoints.size > 0) {
1040             int markFound = 0, runCount = bidi.runCount;
1041             int length, insertRemove, i, j;
1042             runs = bidi.runs;
1043             visualStart = 0;
1044             /* add number of marks found until each index */
1045             for (i = 0; i < runCount; i++, visualStart += length) {
1046                 length = runs[i].limit - visualStart;
1047                 insertRemove = runs[i].insertRemove;
1048                 if ((insertRemove & (Bidi.LRM_BEFORE|Bidi.RLM_BEFORE)) > 0) {
1049                     markFound++;
1050                 }
1051                 if (markFound > 0) {
1052                     logicalStart = runs[i].start;
1053                     logicalLimit = logicalStart + length;
1054                     for (j = logicalStart; j < logicalLimit; j++) {
1055                         indexMap[j] += markFound;
1056                     }
1057                 }
1058                 if ((insertRemove & (Bidi.LRM_AFTER|Bidi.RLM_AFTER)) > 0) {
1059                     markFound++;
1060                 }
1061             }
1062         }
1063         else if (bidi.controlCount > 0) {
1064             int controlFound = 0, runCount = bidi.runCount;
1065             int length, insertRemove, i, j, k;
1066             boolean evenRun;
1067             char uchar;
1068             runs = bidi.runs;
1069             visualStart = 0;
1070             /* subtract number of controls found until each index */
1071             for (i = 0; i < runCount; i++, visualStart += length) {
1072                 length = runs[i].limit - visualStart;
1073                 insertRemove = runs[i].insertRemove;
1074                 /* no control found within previous runs nor within this run */
1075                 if ((controlFound - insertRemove) == 0) {
1076                     continue;
1077                 }
1078                 logicalStart = runs[i].start;
1079                 evenRun = runs[i].isEvenRun();
1080                 logicalLimit = logicalStart + length;
1081                 /* if no control within this run */
1082                 if (insertRemove == 0) {
1083                     for (j = logicalStart; j < logicalLimit; j++) {
1084                         indexMap[j] -= controlFound;
1085                     }
1086                     continue;
1087                 }
1088                 for (j = 0; j < length; j++) {
1089                     k = evenRun ? logicalStart + j : logicalLimit - j - 1;
1090                     uchar = bidi.text[k];
1091                     if (Bidi.IsBidiControlChar(uchar)) {
1092                         controlFound++;
1093                         indexMap[k] = Bidi.MAP_NOWHERE;
1094                         continue;
1095                     }
1096                     indexMap[k] -= controlFound;
1097                 }
1098             }
1099         }
1100         return indexMap;
1101     }
1102
1103     static int[] getVisualMap(Bidi bidi)
1104     {
1105         /* fill a visual-to-logical index map using the runs[] */
1106         BidiRun[] runs = bidi.runs;
1107         int logicalStart, visualStart, visualLimit;
1108         int allocLength = bidi.length > bidi.resultLength ? bidi.length
1109                                                           : bidi.resultLength;
1110         int[] indexMap = new int[allocLength];
1111
1112         visualStart = 0;
1113         int idx = 0;
1114         for (int j = 0; j < bidi.runCount; ++j) {
1115             logicalStart = runs[j].start;
1116             visualLimit = runs[j].limit;
1117             if (runs[j].isEvenRun()) {
1118                 do { /* LTR */
1119                     indexMap[idx++] = logicalStart++;
1120                 } while (++visualStart < visualLimit);
1121             } else {
1122                 logicalStart += visualLimit - visualStart;  /* logicalLimit */
1123                 do { /* RTL */
1124                     indexMap[idx++] = --logicalStart;
1125                 } while (++visualStart < visualLimit);
1126             }
1127             /* visualStart==visualLimit; */
1128         }
1129
1130         if (bidi.insertPoints.size > 0) {
1131             int markFound = 0, runCount = bidi.runCount;
1132             int insertRemove, i, j, k;
1133             runs = bidi.runs;
1134             /* count all inserted marks */
1135             for (i = 0; i < runCount; i++) {
1136                 insertRemove = runs[i].insertRemove;
1137                 if ((insertRemove & (Bidi.LRM_BEFORE|Bidi.RLM_BEFORE)) > 0) {
1138                     markFound++;
1139                 }
1140                 if ((insertRemove & (Bidi.LRM_AFTER|Bidi.RLM_AFTER)) > 0) {
1141                     markFound++;
1142                 }
1143             }
1144             /* move back indexes by number of preceding marks */
1145             k = bidi.resultLength;
1146             for (i = runCount - 1; i >= 0 && markFound > 0; i--) {
1147                 insertRemove = runs[i].insertRemove;
1148                 if ((insertRemove & (Bidi.LRM_AFTER|Bidi.RLM_AFTER)) > 0) {
1149                     indexMap[--k] = Bidi.MAP_NOWHERE;
1150                     markFound--;
1151                 }
1152                 visualStart = i > 0 ? runs[i-1].limit : 0;
1153                 for (j = runs[i].limit - 1; j >= visualStart && markFound > 0; j--) {
1154                     indexMap[--k] = indexMap[j];
1155                 }
1156                 if ((insertRemove & (Bidi.LRM_BEFORE|Bidi.RLM_BEFORE)) > 0) {
1157                     indexMap[--k] = Bidi.MAP_NOWHERE;
1158                     markFound--;
1159                 }
1160             }
1161         }
1162         else if (bidi.controlCount > 0) {
1163             int runCount = bidi.runCount, logicalEnd;
1164             int insertRemove, length, i, j, k, m;
1165             char uchar;
1166             boolean evenRun;
1167             runs = bidi.runs;
1168             visualStart = 0;
1169             /* move forward indexes by number of preceding controls */
1170             k = 0;
1171             for (i = 0; i < runCount; i++, visualStart += length) {
1172                 length = runs[i].limit - visualStart;
1173                 insertRemove = runs[i].insertRemove;
1174                 /* if no control found yet, nothing to do in this run */
1175                 if ((insertRemove == 0) && (k == visualStart)) {
1176                     k += length;
1177                     continue;
1178                 }
1179                 /* if no control in this run */
1180                 if (insertRemove == 0) {
1181                     visualLimit = runs[i].limit;
1182                     for (j = visualStart; j < visualLimit; j++) {
1183                         indexMap[k++] = indexMap[j];
1184                     }
1185                     continue;
1186                 }
1187                 logicalStart = runs[i].start;
1188                 evenRun = runs[i].isEvenRun();
1189                 logicalEnd = logicalStart + length - 1;
1190                 for (j = 0; j < length; j++) {
1191                     m = evenRun ? logicalStart + j : logicalEnd - j;
1192                     uchar = bidi.text[m];
1193                     if (!Bidi.IsBidiControlChar(uchar)) {
1194                         indexMap[k++] = m;
1195                     }
1196                 }
1197             }
1198         }
1199         if (allocLength == bidi.resultLength) {
1200             return indexMap;
1201         }
1202         int[] newMap = new int[bidi.resultLength];
1203         System.arraycopy(indexMap, 0, newMap, 0, bidi.resultLength);
1204         return newMap;
1205     }
1206
1207     static int[] invertMap(int[] srcMap)
1208     {
1209         int srcLength = srcMap.length;
1210         int destLength = -1, count = 0, i, srcEntry;
1211
1212         /* find highest value and count positive indexes in srcMap */
1213         for (i = 0; i < srcLength; i++) {
1214             srcEntry = srcMap[i];
1215             if (srcEntry > destLength) {
1216                 destLength = srcEntry;
1217             }
1218             if (srcEntry >= 0) {
1219                 count++;
1220             }
1221         }
1222         destLength++;           /* add 1 for origin 0 */
1223         int[] destMap = new int[destLength];
1224         if (count < destLength) {
1225             /* we must fill unmatched destMap entries with -1 */
1226             Arrays.fill(destMap, Bidi.MAP_NOWHERE);
1227         }
1228         for (i = 0; i < srcLength; i++) {
1229             srcEntry = srcMap[i];
1230             if (srcEntry >= 0) {
1231                 destMap[srcEntry] = i;
1232             }
1233         }
1234         return destMap;
1235     }
1236 }