1 /*
2  * Copyright (c) 2009, 2021, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 
26 /*
27 *******************************************************************************
28 *   Copyright (C) 2001-2014, International Business Machines
29 *   Corporation and others.  All Rights Reserved.
30 *******************************************************************************
31 */
32 /* Written by Simon Montagu, Matitiahu Allouche
33  * (ported from C code written by Markus W. Scherer)
34  */
35 
36 package jdk.internal.icu.text;
37 
38 import java.text.Bidi;
39 import java.util.Arrays;
40 
41 final class BidiLine {
42 
43     /*
44      * General remarks about the functions in this file:
45      *
46      * These functions deal with the aspects of potentially mixed-directional
47      * text in a single paragraph or in a line of a single paragraph
48      * which has already been processed according to
49      * the Unicode 3.0 Bidi algorithm as defined in
50      * <a href="http://www.unicode.org/reports/tr9/">Unicode Standard Annex #9:
51      * Unicode Bidirectional Algorithm</a>, version 13,
52      * also described in The Unicode Standard, Version 4.0.1 .
53      *
54      * This means that there is a Bidi object with a levels
55      * and a dirProps array.
56      * paraLevel and direction are also set.
57      * Only if the length of the text is zero, then levels==dirProps==NULL.
58      *
59      * The overall directionality of the paragraph
60      * or line is used to bypass the reordering steps if possible.
61      * Even purely RTL text does not need reordering there because
62      * the getLogical/VisualIndex() methods can compute the
63      * index on the fly in such a case.
64      *
65      * The implementation of the access to same-level-runs and of the reordering
66      * do attempt to provide better performance and less memory usage compared to
67      * a direct implementation of especially rule (L2) with an array of
68      * one (32-bit) integer per text character.
69      *
70      * Here, the levels array is scanned as soon as necessary, and a vector of
71      * same-level-runs is created. Reordering then is done on this vector.
72      * For each run of text positions that were resolved to the same level,
73      * only 8 bytes are stored: the first text position of the run and the visual
74      * position behind the run after reordering.
75      * One sign bit is used to hold the directionality of the run.
76      * This is inefficient if there are many very short runs. If the average run
77      * length is <2, then this uses more memory.
78      *
79      * In a further attempt to save memory, the levels array is never changed
80      * after all the resolution rules (Xn, Wn, Nn, In).
81      * Many methods have to consider the field trailingWSStart:
82      * if it is less than length, then there is an implicit trailing run
83      * at the paraLevel,
84      * which is not reflected in the levels array.
85      * This allows a line Bidi object to use the same levels array as
86      * its paragraph parent object.
87      *
88      * When a Bidi object is created for a line of a paragraph, then the
89      * paragraph's levels and dirProps arrays are reused by way of setting
90      * a pointer into them, not by copying. This again saves memory and forbids to
91      * change the now shared levels for (L1).
92      */
93 
94     /* handle trailing WS (L1) -------------------------------------------------- */
95 
96     /*
97      * setTrailingWSStart() sets the start index for a trailing
98      * run of WS in the line. This is necessary because we do not modify
99      * the paragraph's levels array that we just point into.
100      * Using trailingWSStart is another form of performing (L1).
101      *
102      * To make subsequent operations easier, we also include the run
103      * before the WS if it is at the paraLevel - we merge the two here.
104      *
105      * This method is called only from setLine(), so paraLevel is
106      * set correctly for the line even when contextual multiple paragraphs.
107      */
108 
setTrailingWSStart(BidiBase bidiBase)109     static void setTrailingWSStart(BidiBase bidiBase)
110     {
111         byte[] dirProps = bidiBase.dirProps;
112         byte[] levels = bidiBase.levels;
113         int start = bidiBase.length;
114         byte paraLevel = bidiBase.paraLevel;
115 
116         /* If the line is terminated by a block separator, all preceding WS etc...
117            are already set to paragraph level.
118            Setting trailingWSStart to pBidi->length will avoid changing the
119            level of B chars from 0 to paraLevel in getLevels when
120            orderParagraphsLTR==TRUE
121         */
122         if (dirProps[start - 1] == BidiBase.B) {
123             bidiBase.trailingWSStart = start;   /* currently == bidiBase.length */
124             return;
125         }
126         /* go backwards across all WS, BN, explicit codes */
127         while (start > 0 &&
128                 (BidiBase.DirPropFlag(dirProps[start - 1]) & BidiBase.MASK_WS) != 0) {
129             --start;
130         }
131 
132         /* if the WS run can be merged with the previous run then do so here */
133         while (start > 0 && levels[start - 1] == paraLevel) {
134             --start;
135         }
136 
137         bidiBase.trailingWSStart=start;
138     }
139 
setLine(BidiBase paraBidi, Bidi newBidi, BidiBase lineBidi, int start, int limit)140     static Bidi setLine(BidiBase paraBidi,
141                               Bidi newBidi, BidiBase lineBidi,
142                               int start, int limit) {
143         int length;
144 
145         /* set the values in lineBidi from its paraBidi parent */
146         /* class members are already initialized to 0 */
147         // lineBidi.paraBidi = null;        /* mark unfinished setLine */
148         // lineBidi.flags = 0;
149         // lineBidi.controlCount = 0;
150 
151         length = lineBidi.length = lineBidi.originalLength =
152                 lineBidi.resultLength = limit - start;
153 
154         lineBidi.text = new char[length];
155         System.arraycopy(paraBidi.text, start, lineBidi.text, 0, length);
156         lineBidi.paraLevel = paraBidi.GetParaLevelAt(start);
157         lineBidi.paraCount = paraBidi.paraCount;
158         lineBidi.runs = new BidiRun[0];
159         lineBidi.reorderingMode = paraBidi.reorderingMode;
160         lineBidi.reorderingOptions = paraBidi.reorderingOptions;
161         if (paraBidi.controlCount > 0) {
162             int j;
163             for (j = start; j < limit; j++) {
164                 if (BidiBase.IsBidiControlChar(paraBidi.text[j])) {
165                     lineBidi.controlCount++;
166                 }
167             }
168             lineBidi.resultLength -= lineBidi.controlCount;
169         }
170         /* copy proper subset of DirProps */
171         lineBidi.getDirPropsMemory(length);
172         lineBidi.dirProps = lineBidi.dirPropsMemory;
173         System.arraycopy(paraBidi.dirProps, start, lineBidi.dirProps, 0,
174                          length);
175         /* copy proper subset of Levels */
176         lineBidi.getLevelsMemory(length);
177         lineBidi.levels = lineBidi.levelsMemory;
178         System.arraycopy(paraBidi.levels, start, lineBidi.levels, 0,
179                          length);
180         lineBidi.runCount = -1;
181 
182         if (paraBidi.direction != BidiBase.MIXED) {
183             /* the parent is already trivial */
184             lineBidi.direction = paraBidi.direction;
185 
186             /*
187              * The parent's levels are all either
188              * implicitly or explicitly ==paraLevel;
189              * do the same here.
190              */
191             if (paraBidi.trailingWSStart <= start) {
192                 lineBidi.trailingWSStart = 0;
193             } else if (paraBidi.trailingWSStart < limit) {
194                 lineBidi.trailingWSStart = paraBidi.trailingWSStart - start;
195             } else {
196                 lineBidi.trailingWSStart = length;
197             }
198         } else {
199             byte[] levels = lineBidi.levels;
200             int i, trailingWSStart;
201             byte level;
202 
203             setTrailingWSStart(lineBidi);
204             trailingWSStart = lineBidi.trailingWSStart;
205 
206             /* recalculate lineBidiBase.direction */
207             if (trailingWSStart == 0) {
208                 /* all levels are at paraLevel */
209                 lineBidi.direction = (byte)(lineBidi.paraLevel & 1);
210             } else {
211                 /* get the level of the first character */
212                 level = (byte)(levels[0] & 1);
213 
214                 /* if there is anything of a different level, then the line
215                    is mixed */
216                 if (trailingWSStart < length &&
217                     (lineBidi.paraLevel & 1) != level) {
218                     /* the trailing WS is at paraLevel, which differs from
219                        levels[0] */
220                     lineBidi.direction = BidiBase.MIXED;
221                 } else {
222                     /* see if levels[1..trailingWSStart-1] have the same
223                        direction as levels[0] and paraLevel */
224                     for (i = 1; ; i++) {
225                         if (i == trailingWSStart) {
226                             /* the direction values match those in level */
227                             lineBidi.direction = level;
228                             break;
229                         } else if ((levels[i] & 1) != level) {
230                             lineBidi.direction = BidiBase.MIXED;
231                             break;
232                         }
233                     }
234                 }
235             }
236 
237             switch(lineBidi.direction) {
238                 case Bidi.DIRECTION_LEFT_TO_RIGHT:
239                     /* make sure paraLevel is even */
240                     lineBidi.paraLevel = (byte)
241                         ((lineBidi.paraLevel + 1) & ~1);
242 
243                     /* all levels are implicitly at paraLevel (important for
244                        getLevels()) */
245                     lineBidi.trailingWSStart = 0;
246                     break;
247                 case Bidi.DIRECTION_RIGHT_TO_LEFT:
248                     /* make sure paraLevel is odd */
249                     lineBidi.paraLevel |= 1;
250 
251                     /* all levels are implicitly at paraLevel (important for
252                        getLevels()) */
253                     lineBidi.trailingWSStart = 0;
254                     break;
255                 default:
256                     break;
257             }
258         }
259 
260         lineBidi.paraBidi = paraBidi;     /* mark successful setLine */
261 
262         return newBidi;
263     }
264 
getLevelAt(BidiBase bidiBase, int charIndex)265     static byte getLevelAt(BidiBase bidiBase, int charIndex)
266     {
267         /* return paraLevel if in the trailing WS run, otherwise the real level */
268         if (bidiBase.direction != BidiBase.MIXED || charIndex >= bidiBase.trailingWSStart) {
269             return bidiBase.GetParaLevelAt(charIndex);
270         } else {
271             return bidiBase.levels[charIndex];
272         }
273     }
274 
getLevels(BidiBase bidiBase)275     static byte[] getLevels(BidiBase bidiBase)
276     {
277         int start = bidiBase.trailingWSStart;
278         int length = bidiBase.length;
279 
280         if (start != length) {
281             /* the current levels array does not reflect the WS run */
282             /*
283              * After the previous if(), we know that the levels array
284              * has an implicit trailing WS run and therefore does not fully
285              * reflect itself all the levels.
286              * This must be a Bidi object for a line, and
287              * we need to create a new levels array.
288              */
289             /* bidiBase.paraLevel is ok even if contextual multiple paragraphs,
290                since bidiBase is a line object                                     */
291             Arrays.fill(bidiBase.levels, start, length, bidiBase.paraLevel);
292 
293             /* this new levels array is set for the line and reflects the WS run */
294             bidiBase.trailingWSStart = length;
295         }
296         if (length < bidiBase.levels.length) {
297             byte[] levels = new byte[length];
298             System.arraycopy(bidiBase.levels, 0, levels, 0, length);
299             return levels;
300         }
301         return bidiBase.levels;
302     }
303 
getVisualRun(BidiBase bidiBase, int runIndex)304     static BidiRun getVisualRun(BidiBase bidiBase, int runIndex) {
305         int start = bidiBase.runs[runIndex].start;
306         int limit;
307         byte level = bidiBase.runs[runIndex].level;
308 
309         if (runIndex > 0) {
310             limit = start +
311                     bidiBase.runs[runIndex].limit -
312                     bidiBase.runs[runIndex - 1].limit;
313         } else {
314             limit = start + bidiBase.runs[0].limit;
315         }
316         return new BidiRun(start, limit, level);
317     }
318 
319     /* in trivial cases there is only one trivial run; called by getRuns() */
getSingleRun(BidiBase bidiBase, byte level)320     private static void getSingleRun(BidiBase bidiBase, byte level) {
321         /* simple, single-run case */
322         bidiBase.runs = bidiBase.simpleRuns;
323         bidiBase.runCount = 1;
324 
325         /* fill and reorder the single run */
326         bidiBase.runs[0] = new BidiRun(0, bidiBase.length, level);
327     }
328 
329     /* reorder the runs array (L2) ---------------------------------------------- */
330 
331     /*
332      * Reorder the same-level runs in the runs array.
333      * Here, runCount>1 and maxLevel>=minLevel>=paraLevel.
334      * All the visualStart fields=logical start before reordering.
335      * The "odd" bits are not set yet.
336      *
337      * Reordering with this data structure lends itself to some handy shortcuts:
338      *
339      * Since each run is moved but not modified, and since at the initial maxLevel
340      * each sequence of same-level runs consists of only one run each, we
341      * don't need to do anything there and can predecrement maxLevel.
342      * In many simple cases, the reordering is thus done entirely in the
343      * index mapping.
344      * Also, reordering occurs only down to the lowest odd level that occurs,
345      * which is minLevel|1. However, if the lowest level itself is odd, then
346      * in the last reordering the sequence of the runs at this level or higher
347      * will be all runs, and we don't need the elaborate loop to search for them.
348      * This is covered by ++minLevel instead of minLevel|=1 followed
349      * by an extra reorder-all after the reorder-some loop.
350      * About a trailing WS run:
351      * Such a run would need special treatment because its level is not
352      * reflected in levels[] if this is not a paragraph object.
353      * Instead, all characters from trailingWSStart on are implicitly at
354      * paraLevel.
355      * However, for all maxLevel>paraLevel, this run will never be reordered
356      * and does not need to be taken into account. maxLevel==paraLevel is only reordered
357      * if minLevel==paraLevel is odd, which is done in the extra segment.
358      * This means that for the main reordering loop we don't need to consider
359      * this run and can --runCount. If it is later part of the all-runs
360      * reordering, then runCount is adjusted accordingly.
361      */
reorderLine(BidiBase bidiBase, byte minLevel, byte maxLevel)362     private static void reorderLine(BidiBase bidiBase, byte minLevel, byte maxLevel) {
363 
364         /* nothing to do? */
365         if (maxLevel<=(minLevel|1)) {
366             return;
367         }
368 
369         BidiRun[] runs;
370         BidiRun tempRun;
371         byte[] levels;
372         int firstRun, endRun, limitRun, runCount;
373 
374         /*
375          * Reorder only down to the lowest odd level
376          * and reorder at an odd minLevel in a separate, simpler loop.
377          * See comments above for why minLevel is always incremented.
378          */
379         ++minLevel;
380 
381         runs = bidiBase.runs;
382         levels = bidiBase.levels;
383         runCount = bidiBase.runCount;
384 
385         /* do not include the WS run at paraLevel<=old minLevel except in the simple loop */
386         if (bidiBase.trailingWSStart < bidiBase.length) {
387             --runCount;
388         }
389 
390         while (--maxLevel >= minLevel) {
391             firstRun = 0;
392 
393             /* loop for all sequences of runs */
394             for ( ; ; ) {
395                 /* look for a sequence of runs that are all at >=maxLevel */
396                 /* look for the first run of such a sequence */
397                 while (firstRun < runCount && levels[runs[firstRun].start] < maxLevel) {
398                     ++firstRun;
399                 }
400                 if (firstRun >= runCount) {
401                     break;  /* no more such runs */
402                 }
403 
404                 /* look for the limit run of such a sequence (the run behind it) */
405                 for (limitRun = firstRun; ++limitRun < runCount &&
406                       levels[runs[limitRun].start]>=maxLevel; ) {}
407 
408                 /* Swap the entire sequence of runs from firstRun to limitRun-1. */
409                 endRun = limitRun - 1;
410                 while (firstRun < endRun) {
411                     tempRun = runs[firstRun];
412                     runs[firstRun] = runs[endRun];
413                     runs[endRun] = tempRun;
414                     ++firstRun;
415                     --endRun;
416                 }
417 
418                 if (limitRun == runCount) {
419                     break;  /* no more such runs */
420                 } else {
421                     firstRun = limitRun + 1;
422                 }
423             }
424         }
425 
426         /* now do maxLevel==old minLevel (==odd!), see above */
427         if ((minLevel & 1) == 0) {
428             firstRun = 0;
429 
430             /* include the trailing WS run in this complete reordering */
431             if (bidiBase.trailingWSStart == bidiBase.length) {
432                 --runCount;
433             }
434 
435             /* Swap the entire sequence of all runs. (endRun==runCount) */
436             while (firstRun < runCount) {
437                 tempRun = runs[firstRun];
438                 runs[firstRun] = runs[runCount];
439                 runs[runCount] = tempRun;
440                 ++firstRun;
441                 --runCount;
442             }
443         }
444     }
445 
446     /* compute the runs array --------------------------------------------------- */
447 
getRunFromLogicalIndex(BidiBase bidiBase, int logicalIndex)448     static int getRunFromLogicalIndex(BidiBase bidiBase, int logicalIndex) {
449         BidiRun[] runs = bidiBase.runs;
450         int runCount = bidiBase.runCount, visualStart = 0, i, length, logicalStart;
451 
452         for (i = 0; i < runCount; i++) {
453             length = runs[i].limit - visualStart;
454             logicalStart = runs[i].start;
455             if ((logicalIndex >= logicalStart) && (logicalIndex < (logicalStart+length))) {
456                 return i;
457             }
458             visualStart += length;
459         }
460         /* we should never get here */
461         throw new IllegalStateException("Internal ICU error in getRunFromLogicalIndex");
462     }
463 
464     /*
465      * Compute the runs array from the levels array.
466      * After getRuns() returns true, runCount is guaranteed to be >0
467      * and the runs are reordered.
468      * Odd-level runs have visualStart on their visual right edge and
469      * they progress visually to the left.
470      * If option OPTION_INSERT_MARKS is set, insertRemove will contain the
471      * sum of appropriate LRM/RLM_BEFORE/AFTER flags.
472      * If option OPTION_REMOVE_CONTROLS is set, insertRemove will contain the
473      * negative number of BiDi control characters within this run.
474      */
getRuns(BidiBase bidiBase)475     static void getRuns(BidiBase bidiBase) {
476         /*
477          * This method returns immediately if the runs are already set. This
478          * includes the case of length==0 (handled in setPara)..
479          */
480         if (bidiBase.runCount >= 0) {
481             return;
482         }
483         if (bidiBase.direction != BidiBase.MIXED) {
484             /* simple, single-run case - this covers length==0 */
485             /* bidiBase.paraLevel is ok even for contextual multiple paragraphs */
486             getSingleRun(bidiBase, bidiBase.paraLevel);
487         } else /* BidiBase.MIXED, length>0 */ {
488             /* mixed directionality */
489             int length = bidiBase.length, limit;
490             byte[] levels = bidiBase.levels;
491             int i, runCount;
492             byte level = -1;    /* initialize with no valid level */
493             /*
494              * If there are WS characters at the end of the line
495              * and the run preceding them has a level different from
496              * paraLevel, then they will form their own run at paraLevel (L1).
497              * Count them separately.
498              * We need some special treatment for this in order to not
499              * modify the levels array which a line Bidi object shares
500              * with its paragraph parent and its other line siblings.
501              * In other words, for the trailing WS, it may be
502              * levels[]!=paraLevel but we have to treat it like it were so.
503              */
504             limit = bidiBase.trailingWSStart;
505             /* count the runs, there is at least one non-WS run, and limit>0 */
506             runCount = 0;
507             for (i = 0; i < limit; ++i) {
508                 /* increment runCount at the start of each run */
509                 if (levels[i] != level) {
510                     ++runCount;
511                     level = levels[i];
512                 }
513             }
514 
515             /*
516              * We don't need to see if the last run can be merged with a trailing
517              * WS run because setTrailingWSStart() would have done that.
518              */
519             if (runCount == 1 && limit == length) {
520                 /* There is only one non-WS run and no trailing WS-run. */
521                 getSingleRun(bidiBase, levels[0]);
522             } else /* runCount>1 || limit<length */ {
523                 /* allocate and set the runs */
524                 BidiRun[] runs;
525                 int runIndex, start;
526                 byte minLevel = BidiBase.MAX_EXPLICIT_LEVEL + 1;
527                 byte maxLevel=0;
528 
529                 /* now, count a (non-mergeable) WS run */
530                 if (limit < length) {
531                     ++runCount;
532                 }
533 
534                 /* runCount > 1 */
535                 bidiBase.getRunsMemory(runCount);
536                 runs = bidiBase.runsMemory;
537 
538                 /* set the runs */
539                 /* FOOD FOR THOUGHT: this could be optimized, e.g.:
540                  * 464->444, 484->444, 575->555, 595->555
541                  * However, that would take longer. Check also how it would
542                  * interact with BiDi control removal and inserting Marks.
543                  */
544                 runIndex = 0;
545 
546                 /* search for the run limits and initialize visualLimit values with the run lengths */
547                 i = 0;
548                 do {
549                     /* prepare this run */
550                     start = i;
551                     level = levels[i];
552                     if (level < minLevel) {
553                         minLevel = level;
554                     }
555                     if (level > maxLevel) {
556                         maxLevel = level;
557                     }
558 
559                     /* look for the run limit */
560                     while (++i < limit && levels[i] == level) {}
561 
562                     /* i is another run limit */
563                     runs[runIndex] = new BidiRun(start, i - start, level);
564                     ++runIndex;
565                 } while (i < limit);
566 
567                 if (limit < length) {
568                     /* there is a separate WS run */
569                     runs[runIndex] = new BidiRun(limit, length - limit, bidiBase.paraLevel);
570                     /* For the trailing WS run, bidiBase.paraLevel is ok even
571                        if contextual multiple paragraphs.                   */
572                     if (bidiBase.paraLevel < minLevel) {
573                         minLevel = bidiBase.paraLevel;
574                     }
575                 }
576 
577                 /* set the object fields */
578                 bidiBase.runs = runs;
579                 bidiBase.runCount = runCount;
580 
581                 reorderLine(bidiBase, minLevel, maxLevel);
582 
583                 /* now add the direction flags and adjust the visualLimit's to be just that */
584                 /* this loop will also handle the trailing WS run */
585                 limit = 0;
586                 for (i = 0; i < runCount; ++i) {
587                     runs[i].level = levels[runs[i].start];
588                     limit = (runs[i].limit += limit);
589                 }
590 
591                 /* Set the embedding level for the trailing WS run. */
592                 /* For a RTL paragraph, it will be the *first* run in visual order. */
593                 /* For the trailing WS run, bidiBase.paraLevel is ok even if
594                    contextual multiple paragraphs.                          */
595                 if (runIndex < runCount) {
596                     int trailingRun = ((bidiBase.paraLevel & 1) != 0)? 0 : runIndex;
597                     runs[trailingRun].level = bidiBase.paraLevel;
598                 }
599             }
600         }
601 
602         /* handle insert LRM/RLM BEFORE/AFTER run */
603         if (bidiBase.insertPoints.size > 0) {
604             BidiBase.Point point;
605             int runIndex, ip;
606             for (ip = 0; ip < bidiBase.insertPoints.size; ip++) {
607                 point = bidiBase.insertPoints.points[ip];
608                 runIndex = getRunFromLogicalIndex(bidiBase, point.pos);
609                 bidiBase.runs[runIndex].insertRemove |= point.flag;
610             }
611         }
612 
613         /* handle remove BiDi control characters */
614         if (bidiBase.controlCount > 0) {
615             int runIndex, ic;
616             char c;
617             for (ic = 0; ic < bidiBase.length; ic++) {
618                 c = bidiBase.text[ic];
619                 if (BidiBase.IsBidiControlChar(c)) {
620                     runIndex = getRunFromLogicalIndex(bidiBase, ic);
621                     bidiBase.runs[runIndex].insertRemove--;
622                 }
623             }
624         }
625     }
626 
prepareReorder(byte[] levels, byte[] pMinLevel, byte[] pMaxLevel)627     static int[] prepareReorder(byte[] levels, byte[] pMinLevel, byte[] pMaxLevel)
628     {
629         int start;
630         byte level, minLevel, maxLevel;
631 
632         if (levels == null || levels.length <= 0) {
633             return null;
634         }
635 
636         /* determine minLevel and maxLevel */
637         minLevel = BidiBase.MAX_EXPLICIT_LEVEL + 1;
638         maxLevel = 0;
639         for (start = levels.length; start>0; ) {
640             level = levels[--start];
641             if (level < 0 || level > (BidiBase.MAX_EXPLICIT_LEVEL + 1)) {
642                 return null;
643             }
644             if (level < minLevel) {
645                 minLevel = level;
646             }
647             if (level > maxLevel) {
648                 maxLevel = level;
649             }
650         }
651         pMinLevel[0] = minLevel;
652         pMaxLevel[0] = maxLevel;
653 
654         /* initialize the index map */
655         int[] indexMap = new int[levels.length];
656         for (start = levels.length; start > 0; ) {
657             --start;
658             indexMap[start] = start;
659         }
660 
661         return indexMap;
662     }
663 
reorderVisual(byte[] levels)664     static int[] reorderVisual(byte[] levels)
665     {
666         byte[] aMinLevel = new byte[1];
667         byte[] aMaxLevel = new byte[1];
668         int start, end, limit, temp;
669         byte minLevel, maxLevel;
670 
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 runs */
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                  * Swap the entire interval of indexes from start to limit-1.
707                  * We don't need to swap the levels for the purpose of this
708                  * algorithm: the sequence of levels that we look at does not
709                  * move anyway.
710                  */
711                 end = limit - 1;
712                 while (start < end) {
713                     temp = indexMap[start];
714                     indexMap[start] = indexMap[end];
715                     indexMap[end] = temp;
716 
717                     ++start;
718                     --end;
719                 }
720 
721                 if (limit == levels.length) {
722                     break;  /* no more such sequences */
723                 } else {
724                     start = limit + 1;
725                 }
726             }
727         } while (--maxLevel >= minLevel);
728 
729         return indexMap;
730     }
731 
getVisualMap(BidiBase bidiBase)732     static int[] getVisualMap(BidiBase bidiBase)
733     {
734         /* fill a visual-to-logical index map using the runs[] */
735         BidiRun[] runs = bidiBase.runs;
736         int logicalStart, visualStart, visualLimit;
737         int allocLength = bidiBase.length > bidiBase.resultLength ? bidiBase.length
738                                                           : bidiBase.resultLength;
739         int[] indexMap = new int[allocLength];
740 
741         visualStart = 0;
742         int idx = 0;
743         for (int j = 0; j < bidiBase.runCount; ++j) {
744             logicalStart = runs[j].start;
745             visualLimit = runs[j].limit;
746             if (runs[j].isEvenRun()) {
747                 do { /* LTR */
748                     indexMap[idx++] = logicalStart++;
749                 } while (++visualStart < visualLimit);
750             } else {
751                 logicalStart += visualLimit - visualStart;  /* logicalLimit */
752                 do { /* RTL */
753                     indexMap[idx++] = --logicalStart;
754                 } while (++visualStart < visualLimit);
755             }
756             /* visualStart==visualLimit; */
757         }
758 
759         if (bidiBase.insertPoints.size > 0) {
760             int markFound = 0, runCount = bidiBase.runCount;
761             int insertRemove, i, j, k;
762             runs = bidiBase.runs;
763             /* count all inserted marks */
764             for (i = 0; i < runCount; i++) {
765                 insertRemove = runs[i].insertRemove;
766                 if ((insertRemove & (BidiBase.LRM_BEFORE|BidiBase.RLM_BEFORE)) > 0) {
767                     markFound++;
768                 }
769                 if ((insertRemove & (BidiBase.LRM_AFTER|BidiBase.RLM_AFTER)) > 0) {
770                     markFound++;
771                 }
772             }
773             /* move back indexes by number of preceding marks */
774             k = bidiBase.resultLength;
775             for (i = runCount - 1; i >= 0 && markFound > 0; i--) {
776                 insertRemove = runs[i].insertRemove;
777                 if ((insertRemove & (BidiBase.LRM_AFTER|BidiBase.RLM_AFTER)) > 0) {
778                     indexMap[--k] = BidiBase.MAP_NOWHERE;
779                     markFound--;
780                 }
781                 visualStart = i > 0 ? runs[i-1].limit : 0;
782                 for (j = runs[i].limit - 1; j >= visualStart && markFound > 0; j--) {
783                     indexMap[--k] = indexMap[j];
784                 }
785                 if ((insertRemove & (BidiBase.LRM_BEFORE|BidiBase.RLM_BEFORE)) > 0) {
786                     indexMap[--k] = BidiBase.MAP_NOWHERE;
787                     markFound--;
788                 }
789             }
790         }
791         else if (bidiBase.controlCount > 0) {
792             int runCount = bidiBase.runCount, logicalEnd;
793             int insertRemove, length, i, j, k, m;
794             char uchar;
795             boolean evenRun;
796             runs = bidiBase.runs;
797             visualStart = 0;
798             /* move forward indexes by number of preceding controls */
799             k = 0;
800             for (i = 0; i < runCount; i++, visualStart += length) {
801                 length = runs[i].limit - visualStart;
802                 insertRemove = runs[i].insertRemove;
803                 /* if no control found yet, nothing to do in this run */
804                 if ((insertRemove == 0) && (k == visualStart)) {
805                     k += length;
806                     continue;
807                 }
808                 /* if no control in this run */
809                 if (insertRemove == 0) {
810                     visualLimit = runs[i].limit;
811                     for (j = visualStart; j < visualLimit; j++) {
812                         indexMap[k++] = indexMap[j];
813                     }
814                     continue;
815                 }
816                 logicalStart = runs[i].start;
817                 evenRun = runs[i].isEvenRun();
818                 logicalEnd = logicalStart + length - 1;
819                 for (j = 0; j < length; j++) {
820                     m = evenRun ? logicalStart + j : logicalEnd - j;
821                     uchar = bidiBase.text[m];
822                     if (!BidiBase.IsBidiControlChar(uchar)) {
823                         indexMap[k++] = m;
824                     }
825                 }
826             }
827         }
828         if (allocLength == bidiBase.resultLength) {
829             return indexMap;
830         }
831         int[] newMap = new int[bidiBase.resultLength];
832         System.arraycopy(indexMap, 0, newMap, 0, bidiBase.resultLength);
833         return newMap;
834     }
835 
836 }
837