1 /*
   2  * Copyright (c) 2009, 2020, 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      * http://www.unicode.org/unicode/reports/tr9/ , version 13,
  51      * also described in The Unicode Standard, Version 4.0.1 .
  52      *
  53      * This means that there is a Bidi object with a levels
  54      * and a dirProps array.
  55      * paraLevel and direction are also set.
  56      * Only if the length of the text is zero, then levels==dirProps==NULL.
  57      *
  58      * The overall directionality of the paragraph
  59      * or line is used to bypass the reordering steps if possible.
  60      * Even purely RTL text does not need reordering there because
  61      * the getLogical/VisualIndex() methods can compute the
  62      * index on the fly in such a case.
  63      *
  64      * The implementation of the access to same-level-runs and of the reordering
  65      * do attempt to provide better performance and less memory usage compared to
  66      * a direct implementation of especially rule (L2) with an array of
  67      * one (32-bit) integer per text character.
  68      *
  69      * Here, the levels array is scanned as soon as necessary, and a vector of
  70      * same-level-runs is created. Reordering then is done on this vector.
  71      * For each run of text positions that were resolved to the same level,
  72      * only 8 bytes are stored: the first text position of the run and the visual
  73      * position behind the run after reordering.
  74      * One sign bit is used to hold the directionality of the run.
  75      * This is inefficient if there are many very short runs. If the average run
  76      * length is <2, then this uses more memory.
  77      *
  78      * In a further attempt to save memory, the levels array is never changed
  79      * after all the resolution rules (Xn, Wn, Nn, In).
  80      * Many methods have to consider the field trailingWSStart:
  81      * if it is less than length, then there is an implicit trailing run
  82      * at the paraLevel,
  83      * which is not reflected in the levels array.
  84      * This allows a line Bidi object to use the same levels array as
  85      * its paragraph parent object.
  86      *
  87      * When a Bidi object is created for a line of a paragraph, then the
  88      * paragraph's levels and dirProps arrays are reused by way of setting
  89      * a pointer into them, not by copying. This again saves memory and forbids to
  90      * change the now shared levels for (L1).
  91      */
  92 
  93     /* handle trailing WS (L1) -------------------------------------------------- */
  94 
  95     /*
  96      * setTrailingWSStart() sets the start index for a trailing
  97      * run of WS in the line. This is necessary because we do not modify
  98      * the paragraph's levels array that we just point into.
  99      * Using trailingWSStart is another form of performing (L1).
 100      *
 101      * To make subsequent operations easier, we also include the run
 102      * before the WS if it is at the paraLevel - we merge the two here.
 103      *
 104      * This method is called only from setLine(), so paraLevel is
 105      * set correctly for the line even when contextual multiple paragraphs.
 106      */
 107 
 108     static void setTrailingWSStart(BidiBase bidiBase)
 109     {
 110         byte[] dirProps = bidiBase.dirProps;
 111         byte[] levels = bidiBase.levels;
 112         int start = bidiBase.length;
 113         byte paraLevel = bidiBase.paraLevel;
 114 
 115         /* If the line is terminated by a block separator, all preceding WS etc...
 116            are already set to paragraph level.
 117            Setting trailingWSStart to pBidi->length will avoid changing the
 118            level of B chars from 0 to paraLevel in getLevels when
 119            orderParagraphsLTR==TRUE
 120         */
 121         if (dirProps[start - 1] == BidiBase.B) {
 122             bidiBase.trailingWSStart = start;   /* currently == bidiBase.length */
 123             return;
 124         }
 125         /* go backwards across all WS, BN, explicit codes */
 126         while (start > 0 &&
 127                 (BidiBase.DirPropFlag(dirProps[start - 1]) & BidiBase.MASK_WS) != 0) {
 128             --start;
 129         }
 130 
 131         /* if the WS run can be merged with the previous run then do so here */
 132         while (start > 0 && levels[start - 1] == paraLevel) {
 133             --start;
 134         }
 135 
 136         bidiBase.trailingWSStart=start;
 137     }
 138 
 139     static Bidi setLine(BidiBase paraBidi,
 140                               Bidi newBidi, BidiBase lineBidi,
 141                               int start, int limit) {
 142         int length;
 143 
 144         /* set the values in lineBidi from its paraBidi parent */
 145         /* class members are already initialized to 0 */
 146         // lineBidi.paraBidi = null;        /* mark unfinished setLine */
 147         // lineBidi.flags = 0;
 148         // lineBidi.controlCount = 0;
 149 
 150         length = lineBidi.length = lineBidi.originalLength =
 151                 lineBidi.resultLength = limit - start;
 152 
 153         lineBidi.text = new char[length];
 154         System.arraycopy(paraBidi.text, start, lineBidi.text, 0, length);
 155         lineBidi.paraLevel = paraBidi.GetParaLevelAt(start);
 156         lineBidi.paraCount = paraBidi.paraCount;
 157         lineBidi.runs = new BidiRun[0];
 158         lineBidi.reorderingMode = paraBidi.reorderingMode;
 159         lineBidi.reorderingOptions = paraBidi.reorderingOptions;
 160         if (paraBidi.controlCount > 0) {
 161             int j;
 162             for (j = start; j < limit; j++) {
 163                 if (BidiBase.IsBidiControlChar(paraBidi.text[j])) {
 164                     lineBidi.controlCount++;
 165                 }
 166             }
 167             lineBidi.resultLength -= lineBidi.controlCount;
 168         }
 169         /* copy proper subset of DirProps */
 170         lineBidi.getDirPropsMemory(length);
 171         lineBidi.dirProps = lineBidi.dirPropsMemory;
 172         System.arraycopy(paraBidi.dirProps, start, lineBidi.dirProps, 0,
 173                          length);
 174         /* copy proper subset of Levels */
 175         lineBidi.getLevelsMemory(length);
 176         lineBidi.levels = lineBidi.levelsMemory;
 177         System.arraycopy(paraBidi.levels, start, lineBidi.levels, 0,
 178                          length);
 179         lineBidi.runCount = -1;
 180 
 181         if (paraBidi.direction != BidiBase.MIXED) {
 182             /* the parent is already trivial */
 183             lineBidi.direction = paraBidi.direction;
 184 
 185             /*
 186              * The parent's levels are all either
 187              * implicitly or explicitly ==paraLevel;
 188              * do the same here.
 189              */
 190             if (paraBidi.trailingWSStart <= start) {
 191                 lineBidi.trailingWSStart = 0;
 192             } else if (paraBidi.trailingWSStart < limit) {
 193                 lineBidi.trailingWSStart = paraBidi.trailingWSStart - start;
 194             } else {
 195                 lineBidi.trailingWSStart = length;
 196             }
 197         } else {
 198             byte[] levels = lineBidi.levels;
 199             int i, trailingWSStart;
 200             byte level;
 201 
 202             setTrailingWSStart(lineBidi);
 203             trailingWSStart = lineBidi.trailingWSStart;
 204 
 205             /* recalculate lineBidiBase.direction */
 206             if (trailingWSStart == 0) {
 207                 /* all levels are at paraLevel */
 208                 lineBidi.direction = (byte)(lineBidi.paraLevel & 1);
 209             } else {
 210                 /* get the level of the first character */
 211                 level = (byte)(levels[0] & 1);
 212 
 213                 /* if there is anything of a different level, then the line
 214                    is mixed */
 215                 if (trailingWSStart < length &&
 216                     (lineBidi.paraLevel & 1) != level) {
 217                     /* the trailing WS is at paraLevel, which differs from
 218                        levels[0] */
 219                     lineBidi.direction = BidiBase.MIXED;
 220                 } else {
 221                     /* see if levels[1..trailingWSStart-1] have the same
 222                        direction as levels[0] and paraLevel */
 223                     for (i = 1; ; i++) {
 224                         if (i == trailingWSStart) {
 225                             /* the direction values match those in level */
 226                             lineBidi.direction = level;
 227                             break;
 228                         } else if ((levels[i] & 1) != level) {
 229                             lineBidi.direction = BidiBase.MIXED;
 230                             break;
 231                         }
 232                     }
 233                 }
 234             }
 235 
 236             switch(lineBidi.direction) {
 237                 case Bidi.DIRECTION_LEFT_TO_RIGHT:
 238                     /* make sure paraLevel is even */
 239                     lineBidi.paraLevel = (byte)
 240                         ((lineBidi.paraLevel + 1) & ~1);
 241 
 242                     /* all levels are implicitly at paraLevel (important for
 243                        getLevels()) */
 244                     lineBidi.trailingWSStart = 0;
 245                     break;
 246                 case Bidi.DIRECTION_RIGHT_TO_LEFT:
 247                     /* make sure paraLevel is odd */
 248                     lineBidi.paraLevel |= 1;
 249 
 250                     /* all levels are implicitly at paraLevel (important for
 251                        getLevels()) */
 252                     lineBidi.trailingWSStart = 0;
 253                     break;
 254                 default:
 255                     break;
 256             }
 257         }
 258 
 259         lineBidi.paraBidi = paraBidi;     /* mark successful setLine */
 260 
 261         return newBidi;
 262     }
 263 
 264     static byte getLevelAt(BidiBase bidiBase, int charIndex)
 265     {
 266         /* return paraLevel if in the trailing WS run, otherwise the real level */
 267         if (bidiBase.direction != BidiBase.MIXED || charIndex >= bidiBase.trailingWSStart) {
 268             return bidiBase.GetParaLevelAt(charIndex);
 269         } else {
 270             return bidiBase.levels[charIndex];
 271         }
 272     }
 273 
 274     static byte[] getLevels(BidiBase bidiBase)
 275     {
 276         int start = bidiBase.trailingWSStart;
 277         int length = bidiBase.length;
 278 
 279         if (start != length) {
 280             /* the current levels array does not reflect the WS run */
 281             /*
 282              * After the previous if(), we know that the levels array
 283              * has an implicit trailing WS run and therefore does not fully
 284              * reflect itself all the levels.
 285              * This must be a Bidi object for a line, and
 286              * we need to create a new levels array.
 287              */
 288             /* bidiBase.paraLevel is ok even if contextual multiple paragraphs,
 289                since bidiBase is a line object                                     */
 290             Arrays.fill(bidiBase.levels, start, length, bidiBase.paraLevel);
 291 
 292             /* this new levels array is set for the line and reflects the WS run */
 293             bidiBase.trailingWSStart = length;
 294         }
 295         if (length < bidiBase.levels.length) {
 296             byte[] levels = new byte[length];
 297             System.arraycopy(bidiBase.levels, 0, levels, 0, length);
 298             return levels;
 299         }
 300         return bidiBase.levels;
 301     }
 302 
 303     static BidiRun getVisualRun(BidiBase bidiBase, int runIndex) {
 304         int start = bidiBase.runs[runIndex].start;
 305         int limit;
 306         byte level = bidiBase.runs[runIndex].level;
 307 
 308         if (runIndex > 0) {
 309             limit = start +
 310                     bidiBase.runs[runIndex].limit -
 311                     bidiBase.runs[runIndex - 1].limit;
 312         } else {
 313             limit = start + bidiBase.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     private static void getSingleRun(BidiBase bidiBase, byte level) {
 320         /* simple, single-run case */
 321         bidiBase.runs = bidiBase.simpleRuns;
 322         bidiBase.runCount = 1;
 323 
 324         /* fill and reorder the single run */
 325         bidiBase.runs[0] = new BidiRun(0, bidiBase.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(BidiBase bidiBase, 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 = bidiBase.runs;
 381         levels = bidiBase.levels;
 382         runCount = bidiBase.runCount;
 383 
 384         /* do not include the WS run at paraLevel<=old minLevel except in the simple loop */
 385         if (bidiBase.trailingWSStart < bidiBase.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 (bidiBase.trailingWSStart == bidiBase.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(BidiBase bidiBase, int logicalIndex) {
 448         BidiRun[] runs = bidiBase.runs;
 449         int runCount = bidiBase.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         /* we should never get here */
 460         throw new IllegalStateException("Internal ICU error in getRunFromLogicalIndex");
 461     }
 462 
 463     /*
 464      * Compute the runs array from the levels array.
 465      * After getRuns() returns true, runCount is guaranteed to be >0
 466      * and the runs are reordered.
 467      * Odd-level runs have visualStart on their visual right edge and
 468      * they progress visually to the left.
 469      * If option OPTION_INSERT_MARKS is set, insertRemove will contain the
 470      * sum of appropriate LRM/RLM_BEFORE/AFTER flags.
 471      * If option OPTION_REMOVE_CONTROLS is set, insertRemove will contain the
 472      * negative number of BiDi control characters within this run.
 473      */
 474     static void getRuns(BidiBase bidiBase) {
 475         /*
 476          * This method returns immediately if the runs are already set. This
 477          * includes the case of length==0 (handled in setPara)..
 478          */
 479         if (bidiBase.runCount >= 0) {
 480             return;
 481         }
 482         if (bidiBase.direction != BidiBase.MIXED) {
 483             /* simple, single-run case - this covers length==0 */
 484             /* bidiBase.paraLevel is ok even for contextual multiple paragraphs */
 485             getSingleRun(bidiBase, bidiBase.paraLevel);
 486         } else /* BidiBase.MIXED, length>0 */ {
 487             /* mixed directionality */
 488             int length = bidiBase.length, limit;
 489             byte[] levels = bidiBase.levels;
 490             int i, runCount;
 491             byte level = -1;    /* initialize with no valid level */
 492             /*
 493              * If there are WS characters at the end of the line
 494              * and the run preceding them has a level different from
 495              * paraLevel, then they will form their own run at paraLevel (L1).
 496              * Count them separately.
 497              * We need some special treatment for this in order to not
 498              * modify the levels array which a line Bidi object shares
 499              * with its paragraph parent and its other line siblings.
 500              * In other words, for the trailing WS, it may be
 501              * levels[]!=paraLevel but we have to treat it like it were so.
 502              */
 503             limit = bidiBase.trailingWSStart;
 504             /* count the runs, there is at least one non-WS run, and limit>0 */
 505             runCount = 0;
 506             for (i = 0; i < limit; ++i) {
 507                 /* increment runCount at the start of each run */
 508                 if (levels[i] != level) {
 509                     ++runCount;
 510                     level = levels[i];
 511                 }
 512             }
 513 
 514             /*
 515              * We don't need to see if the last run can be merged with a trailing
 516              * WS run because setTrailingWSStart() would have done that.
 517              */
 518             if (runCount == 1 && limit == length) {
 519                 /* There is only one non-WS run and no trailing WS-run. */
 520                 getSingleRun(bidiBase, levels[0]);
 521             } else /* runCount>1 || limit<length */ {
 522                 /* allocate and set the runs */
 523                 BidiRun[] runs;
 524                 int runIndex, start;
 525                 byte minLevel = BidiBase.MAX_EXPLICIT_LEVEL + 1;
 526                 byte maxLevel=0;
 527 
 528                 /* now, count a (non-mergeable) WS run */
 529                 if (limit < length) {
 530                     ++runCount;
 531                 }
 532 
 533                 /* runCount > 1 */
 534                 bidiBase.getRunsMemory(runCount);
 535                 runs = bidiBase.runsMemory;
 536 
 537                 /* set the runs */
 538                 /* FOOD FOR THOUGHT: this could be optimized, e.g.:
 539                  * 464->444, 484->444, 575->555, 595->555
 540                  * However, that would take longer. Check also how it would
 541                  * interact with BiDi control removal and inserting Marks.
 542                  */
 543                 runIndex = 0;
 544 
 545                 /* search for the run limits and initialize visualLimit values with the run lengths */
 546                 i = 0;
 547                 do {
 548                     /* prepare this run */
 549                     start = i;
 550                     level = levels[i];
 551                     if (level < minLevel) {
 552                         minLevel = level;
 553                     }
 554                     if (level > maxLevel) {
 555                         maxLevel = level;
 556                     }
 557 
 558                     /* look for the run limit */
 559                     while (++i < limit && levels[i] == level) {}
 560 
 561                     /* i is another run limit */
 562                     runs[runIndex] = new BidiRun(start, i - start, level);
 563                     ++runIndex;
 564                 } while (i < limit);
 565 
 566                 if (limit < length) {
 567                     /* there is a separate WS run */
 568                     runs[runIndex] = new BidiRun(limit, length - limit, bidiBase.paraLevel);
 569                     /* For the trailing WS run, bidiBase.paraLevel is ok even
 570                        if contextual multiple paragraphs.                   */
 571                     if (bidiBase.paraLevel < minLevel) {
 572                         minLevel = bidiBase.paraLevel;
 573                     }
 574                 }
 575 
 576                 /* set the object fields */
 577                 bidiBase.runs = runs;
 578                 bidiBase.runCount = runCount;
 579 
 580                 reorderLine(bidiBase, minLevel, maxLevel);
 581 
 582                 /* now add the direction flags and adjust the visualLimit's to be just that */
 583                 /* this loop will also handle the trailing WS run */
 584                 limit = 0;
 585                 for (i = 0; i < runCount; ++i) {
 586                     runs[i].level = levels[runs[i].start];
 587                     limit = (runs[i].limit += limit);
 588                 }
 589 
 590                 /* Set the embedding level for the trailing WS run. */
 591                 /* For a RTL paragraph, it will be the *first* run in visual order. */
 592                 /* For the trailing WS run, bidiBase.paraLevel is ok even if
 593                    contextual multiple paragraphs.                          */
 594                 if (runIndex < runCount) {
 595                     int trailingRun = ((bidiBase.paraLevel & 1) != 0)? 0 : runIndex;
 596                     runs[trailingRun].level = bidiBase.paraLevel;
 597                 }
 598             }
 599         }
 600 
 601         /* handle insert LRM/RLM BEFORE/AFTER run */
 602         if (bidiBase.insertPoints.size > 0) {
 603             BidiBase.Point point;
 604             int runIndex, ip;
 605             for (ip = 0; ip < bidiBase.insertPoints.size; ip++) {
 606                 point = bidiBase.insertPoints.points[ip];
 607                 runIndex = getRunFromLogicalIndex(bidiBase, point.pos);
 608                 bidiBase.runs[runIndex].insertRemove |= point.flag;
 609             }
 610         }
 611 
 612         /* handle remove BiDi control characters */
 613         if (bidiBase.controlCount > 0) {
 614             int runIndex, ic;
 615             char c;
 616             for (ic = 0; ic < bidiBase.length; ic++) {
 617                 c = bidiBase.text[ic];
 618                 if (BidiBase.IsBidiControlChar(c)) {
 619                     runIndex = getRunFromLogicalIndex(bidiBase, ic);
 620                     bidiBase.runs[runIndex].insertRemove--;
 621                 }
 622             }
 623         }
 624     }
 625 
 626     static int[] prepareReorder(byte[] levels, byte[] pMinLevel, byte[] pMaxLevel)
 627     {
 628         int start;
 629         byte level, minLevel, maxLevel;
 630 
 631         if (levels == null || levels.length <= 0) {
 632             return null;
 633         }
 634 
 635         /* determine minLevel and maxLevel */
 636         minLevel = BidiBase.MAX_EXPLICIT_LEVEL + 1;
 637         maxLevel = 0;
 638         for (start = levels.length; start>0; ) {
 639             level = levels[--start];
 640             if (level < 0 || level > (BidiBase.MAX_EXPLICIT_LEVEL + 1)) {
 641                 return null;
 642             }
 643             if (level < minLevel) {
 644                 minLevel = level;
 645             }
 646             if (level > maxLevel) {
 647                 maxLevel = level;
 648             }
 649         }
 650         pMinLevel[0] = minLevel;
 651         pMaxLevel[0] = maxLevel;
 652 
 653         /* initialize the index map */
 654         int[] indexMap = new int[levels.length];
 655         for (start = levels.length; start > 0; ) {
 656             --start;
 657             indexMap[start] = start;
 658         }
 659 
 660         return indexMap;
 661     }
 662 
 663     static int[] reorderVisual(byte[] levels)
 664     {
 665         byte[] aMinLevel = new byte[1];
 666         byte[] aMaxLevel = new byte[1];
 667         int start, end, limit, temp;
 668         byte minLevel, maxLevel;
 669 
 670         int[] indexMap = prepareReorder(levels, aMinLevel, aMaxLevel);
 671         if (indexMap == null) {
 672             return null;
 673         }
 674 
 675         minLevel = aMinLevel[0];
 676         maxLevel = aMaxLevel[0];
 677 
 678         /* nothing to do? */
 679         if (minLevel == maxLevel && (minLevel & 1) == 0) {
 680             return indexMap;
 681         }
 682 
 683         /* reorder only down to the lowest odd level */
 684         minLevel |= 1;
 685 
 686         /* loop maxLevel..minLevel */
 687         do {
 688             start = 0;
 689 
 690             /* loop for all sequences of levels to reorder at the current maxLevel */
 691             for ( ; ; ) {
 692                 /* look for a sequence of levels that are all at >=maxLevel */
 693                 /* look for the first index of such a sequence */
 694                 while (start < levels.length && levels[start] < maxLevel) {
 695                     ++start;
 696                 }
 697                 if (start >= levels.length) {
 698                     break;  /* no more such runs */
 699                 }
 700 
 701                 /* look for the limit of such a sequence (the index behind it) */
 702                 for (limit = start; ++limit < levels.length && levels[limit] >= maxLevel; ) {}
 703 
 704                 /*
 705                  * Swap the entire interval of indexes from start to limit-1.
 706                  * We don't need to swap the levels for the purpose of this
 707                  * algorithm: the sequence of levels that we look at does not
 708                  * move anyway.
 709                  */
 710                 end = limit - 1;
 711                 while (start < end) {
 712                     temp = indexMap[start];
 713                     indexMap[start] = indexMap[end];
 714                     indexMap[end] = temp;
 715 
 716                     ++start;
 717                     --end;
 718                 }
 719 
 720                 if (limit == levels.length) {
 721                     break;  /* no more such sequences */
 722                 } else {
 723                     start = limit + 1;
 724                 }
 725             }
 726         } while (--maxLevel >= minLevel);
 727 
 728         return indexMap;
 729     }
 730 
 731     static int[] getVisualMap(BidiBase bidiBase)
 732     {
 733         /* fill a visual-to-logical index map using the runs[] */
 734         BidiRun[] runs = bidiBase.runs;
 735         int logicalStart, visualStart, visualLimit;
 736         int allocLength = bidiBase.length > bidiBase.resultLength ? bidiBase.length
 737                                                           : bidiBase.resultLength;
 738         int[] indexMap = new int[allocLength];
 739 
 740         visualStart = 0;
 741         int idx = 0;
 742         for (int j = 0; j < bidiBase.runCount; ++j) {
 743             logicalStart = runs[j].start;
 744             visualLimit = runs[j].limit;
 745             if (runs[j].isEvenRun()) {
 746                 do { /* LTR */
 747                     indexMap[idx++] = logicalStart++;
 748                 } while (++visualStart < visualLimit);
 749             } else {
 750                 logicalStart += visualLimit - visualStart;  /* logicalLimit */
 751                 do { /* RTL */
 752                     indexMap[idx++] = --logicalStart;
 753                 } while (++visualStart < visualLimit);
 754             }
 755             /* visualStart==visualLimit; */
 756         }
 757 
 758         if (bidiBase.insertPoints.size > 0) {
 759             int markFound = 0, runCount = bidiBase.runCount;
 760             int insertRemove, i, j, k;
 761             runs = bidiBase.runs;
 762             /* count all inserted marks */
 763             for (i = 0; i < runCount; i++) {
 764                 insertRemove = runs[i].insertRemove;
 765                 if ((insertRemove & (BidiBase.LRM_BEFORE|BidiBase.RLM_BEFORE)) > 0) {
 766                     markFound++;
 767                 }
 768                 if ((insertRemove & (BidiBase.LRM_AFTER|BidiBase.RLM_AFTER)) > 0) {
 769                     markFound++;
 770                 }
 771             }
 772             /* move back indexes by number of preceding marks */
 773             k = bidiBase.resultLength;
 774             for (i = runCount - 1; i >= 0 && markFound > 0; i--) {
 775                 insertRemove = runs[i].insertRemove;
 776                 if ((insertRemove & (BidiBase.LRM_AFTER|BidiBase.RLM_AFTER)) > 0) {
 777                     indexMap[--k] = BidiBase.MAP_NOWHERE;
 778                     markFound--;
 779                 }
 780                 visualStart = i > 0 ? runs[i-1].limit : 0;
 781                 for (j = runs[i].limit - 1; j >= visualStart && markFound > 0; j--) {
 782                     indexMap[--k] = indexMap[j];
 783                 }
 784                 if ((insertRemove & (BidiBase.LRM_BEFORE|BidiBase.RLM_BEFORE)) > 0) {
 785                     indexMap[--k] = BidiBase.MAP_NOWHERE;
 786                     markFound--;
 787                 }
 788             }
 789         }
 790         else if (bidiBase.controlCount > 0) {
 791             int runCount = bidiBase.runCount, logicalEnd;
 792             int insertRemove, length, i, j, k, m;
 793             char uchar;
 794             boolean evenRun;
 795             runs = bidiBase.runs;
 796             visualStart = 0;
 797             /* move forward indexes by number of preceding controls */
 798             k = 0;
 799             for (i = 0; i < runCount; i++, visualStart += length) {
 800                 length = runs[i].limit - visualStart;
 801                 insertRemove = runs[i].insertRemove;
 802                 /* if no control found yet, nothing to do in this run */
 803                 if ((insertRemove == 0) && (k == visualStart)) {
 804                     k += length;
 805                     continue;
 806                 }
 807                 /* if no control in this run */
 808                 if (insertRemove == 0) {
 809                     visualLimit = runs[i].limit;
 810                     for (j = visualStart; j < visualLimit; j++) {
 811                         indexMap[k++] = indexMap[j];
 812                     }
 813                     continue;
 814                 }
 815                 logicalStart = runs[i].start;
 816                 evenRun = runs[i].isEvenRun();
 817                 logicalEnd = logicalStart + length - 1;
 818                 for (j = 0; j < length; j++) {
 819                     m = evenRun ? logicalStart + j : logicalEnd - j;
 820                     uchar = bidiBase.text[m];
 821                     if (!BidiBase.IsBidiControlChar(uchar)) {
 822                         indexMap[k++] = m;
 823                     }
 824                 }
 825             }
 826         }
 827         if (allocLength == bidiBase.resultLength) {
 828             return indexMap;
 829         }
 830         int[] newMap = new int[bidiBase.resultLength];
 831         System.arraycopy(indexMap, 0, newMap, 0, bidiBase.resultLength);
 832         return newMap;
 833     }
 834 
 835 }