Bidi.java 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. /* Bidi.java -- Bidirectional Algorithm implementation
  2. Copyright (C) 2005, 2006, 2012 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package java.text;
  32. import java.awt.font.NumericShaper;
  33. import java.awt.font.TextAttribute;
  34. import java.util.ArrayList;
  35. /**
  36. * Bidirectional Algorithm implementation.
  37. *
  38. * The full algorithm is
  39. * <a href="http://www.unicode.org/unicode/reports/tr9/">Unicode Standard
  40. * Annex #9: The Bidirectional Algorithm</a>.
  41. *
  42. * @since 1.4
  43. */
  44. public final class Bidi
  45. {
  46. /**
  47. * This indicates that a strongly directional character in the text should
  48. * set the initial direction, but if no such character is found, then the
  49. * initial direction will be left-to-right.
  50. */
  51. public static final int DIRECTION_DEFAULT_LEFT_TO_RIGHT = -2;
  52. /**
  53. * This indicates that a strongly directional character in the text should
  54. * set the initial direction, but if no such character is found, then the
  55. * initial direction will be right-to-left.
  56. */
  57. public static final int DIRECTION_DEFAULT_RIGHT_TO_LEFT = -1;
  58. /**
  59. * This indicates that the initial direction should be left-to-right.
  60. */
  61. public static final int DIRECTION_LEFT_TO_RIGHT = 0;
  62. /**
  63. * This indicates that the initial direction should be right-to-left.
  64. */
  65. public static final int DIRECTION_RIGHT_TO_LEFT = 1;
  66. // Flags used when computing the result.
  67. private static final int LTOR = 1 << DIRECTION_LEFT_TO_RIGHT;
  68. private static final int RTOL = 1 << DIRECTION_RIGHT_TO_LEFT;
  69. // The text we are examining, and the starting offset.
  70. // If we had a better way to handle createLineBidi, we wouldn't
  71. // need this at all -- which for the String case would be an
  72. // efficiency win.
  73. private char[] text;
  74. private int textOffset;
  75. // The embeddings corresponding to the text, and the starting offset.
  76. private byte[] embeddings;
  77. private int embeddingOffset;
  78. // The length of the text (and embeddings) to use.
  79. private int length;
  80. // The flags.
  81. private int flags;
  82. // All instance fields following this point are initialized
  83. // during analysis. Fields before this must be set by the constructor.
  84. // The initial embedding level.
  85. private int baseEmbedding;
  86. // The type of each character in the text.
  87. private byte[] types;
  88. // The levels we compute.
  89. private byte[] levels;
  90. // A list of indices where a formatting code was found. These
  91. // are indicies into the original text -- not into the text after
  92. // the codes have been removed.
  93. private ArrayList<Integer> formatterIndices;
  94. // Indices of the starts of runs in the text.
  95. private int[] runs;
  96. // A convenience field where we keep track of what kinds of runs
  97. // we've seen.
  98. private int resultFlags;
  99. /**
  100. * Create a new Bidi object given an attributed character iterator.
  101. * This constructor will examine various attributes of the text:
  102. * <ul>
  103. * <li> {@link TextAttribute#RUN_DIRECTION} is used to determine the
  104. * paragraph's base embedding level. This constructor will recognize
  105. * either {@link TextAttribute#RUN_DIRECTION_LTR} or
  106. * {@link TextAttribute#RUN_DIRECTION_RTL}. If neither is given,
  107. * {@link #DIRECTION_DEFAULT_LEFT_TO_RIGHT} is assumed.
  108. * </li>
  109. *
  110. * <li> If {@link TextAttribute#NUMERIC_SHAPING} is seen, then numeric
  111. * shaping will be done before the Bidi algorithm is run.
  112. * </li>
  113. *
  114. * <li> If {@link TextAttribute#BIDI_EMBEDDING} is seen on a given
  115. * character, then the value of this attribute will be used as an
  116. * embedding level override.
  117. * </li>
  118. * </ul>
  119. * @param iter the attributed character iterator to use
  120. */
  121. public Bidi(AttributedCharacterIterator iter)
  122. {
  123. // If set, this attribute should be set on all characters.
  124. // We don't check this (should we?) but we do assume that we
  125. // can simply examine the first character.
  126. Object val = iter.getAttribute(TextAttribute.RUN_DIRECTION);
  127. if (val == TextAttribute.RUN_DIRECTION_LTR)
  128. this.flags = DIRECTION_LEFT_TO_RIGHT;
  129. else if (val == TextAttribute.RUN_DIRECTION_RTL)
  130. this.flags = DIRECTION_RIGHT_TO_LEFT;
  131. else
  132. this.flags = DIRECTION_DEFAULT_LEFT_TO_RIGHT;
  133. // Likewise this attribute should be specified on the whole text.
  134. // We read it here and then, if it is set, we apply the numeric shaper
  135. // to the text before processing it.
  136. NumericShaper shaper = null;
  137. val = iter.getAttribute(TextAttribute.NUMERIC_SHAPING);
  138. if (val instanceof NumericShaper)
  139. shaper = (NumericShaper) val;
  140. text = new char[iter.getEndIndex() - iter.getBeginIndex()];
  141. embeddings = new byte[text.length];
  142. embeddingOffset = 0;
  143. length = text.length;
  144. for (int i = 0; i < text.length; ++i)
  145. {
  146. text[i] = iter.current();
  147. val = iter.getAttribute(TextAttribute.BIDI_EMBEDDING);
  148. if (val instanceof Integer)
  149. {
  150. int ival = ((Integer) val).intValue();
  151. byte bval;
  152. if (ival < -62 || ival > 62)
  153. bval = 0;
  154. else
  155. bval = (byte) ival;
  156. embeddings[i] = bval;
  157. }
  158. }
  159. // Invoke the numeric shaper, if specified.
  160. if (shaper != null)
  161. shaper.shape(text, 0, length);
  162. runBidi();
  163. }
  164. /**
  165. * Create a new Bidi object with the indicated text and, possibly, explicit
  166. * embedding settings.
  167. *
  168. * If the embeddings array is null, it is ignored. Otherwise it is taken to
  169. * be explicit embedding settings corresponding to the text. Positive values
  170. * from 1 to 61 are embedding levels, and negative values from -1 to -61 are
  171. * embedding overrides. (FIXME: not at all clear what this really means.)
  172. *
  173. * @param text the text to use
  174. * @param offset the offset of the first character of the text
  175. * @param embeddings the explicit embeddings, or null if there are none
  176. * @param embedOffset the offset of the first embedding value to use
  177. * @param length the length of both the text and the embeddings
  178. * @param flags a flag indicating the base embedding direction
  179. */
  180. public Bidi(char[] text, int offset, byte[] embeddings, int embedOffset,
  181. int length, int flags)
  182. {
  183. if (flags != DIRECTION_DEFAULT_LEFT_TO_RIGHT
  184. && flags != DIRECTION_DEFAULT_RIGHT_TO_LEFT
  185. && flags != DIRECTION_LEFT_TO_RIGHT
  186. && flags != DIRECTION_RIGHT_TO_LEFT)
  187. throw new IllegalArgumentException("unrecognized 'flags' argument: "
  188. + flags);
  189. this.text = text;
  190. this.textOffset = offset;
  191. this.embeddings = embeddings;
  192. this.embeddingOffset = embedOffset;
  193. this.length = length;
  194. this.flags = flags;
  195. runBidi();
  196. }
  197. /**
  198. * Create a new Bidi object using the contents of the given String
  199. * as the text.
  200. * @param text the text to use
  201. * @param flags a flag indicating the base embedding direction
  202. */
  203. public Bidi(String text, int flags)
  204. {
  205. if (flags != DIRECTION_DEFAULT_LEFT_TO_RIGHT
  206. && flags != DIRECTION_DEFAULT_RIGHT_TO_LEFT
  207. && flags != DIRECTION_LEFT_TO_RIGHT
  208. && flags != DIRECTION_RIGHT_TO_LEFT)
  209. throw new IllegalArgumentException("unrecognized 'flags' argument: "
  210. + flags);
  211. // This is inefficient, but it isn't clear whether it matters.
  212. // If it does we can change our implementation a bit to allow either
  213. // a String or a char[].
  214. this.text = text.toCharArray();
  215. this.textOffset = 0;
  216. this.embeddings = null;
  217. this.embeddingOffset = 0;
  218. this.length = text.length();
  219. this.flags = flags;
  220. runBidi();
  221. }
  222. /**
  223. * Implementation function which computes the initial type of
  224. * each character in the input.
  225. */
  226. private void computeTypes()
  227. {
  228. types = new byte[length];
  229. for (int i = 0; i < length; ++i)
  230. types[i] = Character.getDirectionality(text[textOffset + i]);
  231. }
  232. /**
  233. * An internal function which implements rules P2 and P3.
  234. * This computes the base embedding level.
  235. * @return the paragraph's base embedding level
  236. */
  237. private int computeParagraphEmbeddingLevel()
  238. {
  239. // First check to see if the user supplied a directionality override.
  240. if (flags == DIRECTION_LEFT_TO_RIGHT
  241. || flags == DIRECTION_RIGHT_TO_LEFT)
  242. return flags;
  243. // This implements rules P2 and P3.
  244. // (Note that we don't need P1, as the user supplies
  245. // a paragraph.)
  246. for (int i = 0; i < length; ++i)
  247. {
  248. int dir = types[i];
  249. if (dir == Character.DIRECTIONALITY_LEFT_TO_RIGHT)
  250. return DIRECTION_LEFT_TO_RIGHT;
  251. if (dir == Character.DIRECTIONALITY_RIGHT_TO_LEFT
  252. || dir == Character.DIRECTIONALITY_RIGHT_TO_LEFT)
  253. return DIRECTION_RIGHT_TO_LEFT;
  254. }
  255. return (flags == DIRECTION_DEFAULT_LEFT_TO_RIGHT
  256. ? DIRECTION_LEFT_TO_RIGHT
  257. : DIRECTION_RIGHT_TO_LEFT);
  258. }
  259. /**
  260. * An internal function which implements rules X1 through X9.
  261. * This computes the initial levels for the text, handling
  262. * explicit overrides and embeddings.
  263. */
  264. private void computeExplicitLevels()
  265. {
  266. levels = new byte[length];
  267. byte currentEmbedding = (byte) baseEmbedding;
  268. // The directional override is a Character directionality
  269. // constant. -1 means there is no override.
  270. byte directionalOverride = -1;
  271. // The stack of pushed embeddings, and the stack pointer.
  272. // Note that because the direction is inherent in the depth,
  273. // and because we have a bit left over in a byte, we can encode
  274. // the override, if any, directly in this value on the stack.
  275. final int MAX_DEPTH = 62;
  276. byte[] embeddingStack = new byte[MAX_DEPTH];
  277. int sp = 0;
  278. for (int i = 0; i < length; ++i)
  279. {
  280. // If we see an explicit embedding, we use that, even if
  281. // the current character is itself a directional override.
  282. if (embeddings != null && embeddings[embeddingOffset + i] != 0)
  283. {
  284. // It isn't at all clear what we're supposed to do here.
  285. // What does a negative value really mean?
  286. // Should we push on the embedding stack here?
  287. currentEmbedding = embeddings[embeddingOffset + i];
  288. if (currentEmbedding < 0)
  289. {
  290. currentEmbedding = (byte) -currentEmbedding;
  291. directionalOverride
  292. = (((currentEmbedding % 2) == 0)
  293. ? Character.DIRECTIONALITY_LEFT_TO_RIGHT
  294. : Character.DIRECTIONALITY_RIGHT_TO_LEFT);
  295. }
  296. else
  297. directionalOverride = -1;
  298. continue;
  299. }
  300. // No explicit embedding.
  301. boolean isLtoR = false;
  302. boolean isSpecial = true;
  303. switch (types[i])
  304. {
  305. case Character.DIRECTIONALITY_LEFT_TO_RIGHT_EMBEDDING:
  306. case Character.DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE:
  307. isLtoR = true;
  308. // Fall through.
  309. case Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING:
  310. case Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE:
  311. {
  312. byte newEmbedding;
  313. if (isLtoR)
  314. {
  315. // Least greater even.
  316. newEmbedding = (byte) ((currentEmbedding & ~1) + 2);
  317. }
  318. else
  319. {
  320. // Least greater odd.
  321. newEmbedding = (byte) ((currentEmbedding + 1) | 1);
  322. }
  323. // FIXME: we don't properly handle invalid pushes.
  324. if (newEmbedding < MAX_DEPTH)
  325. {
  326. // The new level is valid. Push the old value.
  327. // See above for a comment on the encoding here.
  328. if (directionalOverride != -1)
  329. currentEmbedding |= Byte.MIN_VALUE;
  330. embeddingStack[sp++] = currentEmbedding;
  331. currentEmbedding = newEmbedding;
  332. if (types[i] == Character.DIRECTIONALITY_LEFT_TO_RIGHT_OVERRIDE)
  333. directionalOverride = Character.DIRECTIONALITY_LEFT_TO_RIGHT;
  334. else if (types[i] == Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE)
  335. directionalOverride = Character.DIRECTIONALITY_RIGHT_TO_LEFT;
  336. else
  337. directionalOverride = -1;
  338. }
  339. }
  340. break;
  341. case Character.DIRECTIONALITY_POP_DIRECTIONAL_FORMAT:
  342. {
  343. // FIXME: we don't properly handle a pop with a corresponding
  344. // invalid push.
  345. if (sp == 0)
  346. {
  347. // We saw a pop without a push. Just ignore it.
  348. break;
  349. }
  350. byte newEmbedding = embeddingStack[--sp];
  351. currentEmbedding = (byte) (newEmbedding & 0x7f);
  352. if (newEmbedding < 0)
  353. directionalOverride
  354. = (((newEmbedding & 1) == 0)
  355. ? Character.DIRECTIONALITY_LEFT_TO_RIGHT
  356. : Character.DIRECTIONALITY_RIGHT_TO_LEFT);
  357. else
  358. directionalOverride = -1;
  359. }
  360. break;
  361. default:
  362. isSpecial = false;
  363. break;
  364. }
  365. levels[i] = currentEmbedding;
  366. if (isSpecial)
  367. {
  368. // Mark this character for removal.
  369. if (formatterIndices == null)
  370. formatterIndices = new ArrayList<Integer>();
  371. formatterIndices.add(Integer.valueOf(i));
  372. }
  373. else if (directionalOverride != -1)
  374. types[i] = directionalOverride;
  375. }
  376. // Remove the formatting codes and update both the arrays
  377. // and 'length'. It would be more efficient not to remove
  378. // these codes, but it is also more complicated. Also, the
  379. // Unicode algorithm reference does not properly describe
  380. // how this is to be done -- from what I can tell, their suggestions
  381. // in this area will not yield the correct results.
  382. if (formatterIndices == null)
  383. return;
  384. int output = 0, input = 0;
  385. final int size = formatterIndices.size();
  386. for (int i = 0; i <= size; ++i)
  387. {
  388. int nextFmt;
  389. if (i == size)
  390. nextFmt = length;
  391. else
  392. nextFmt = formatterIndices.get(i).intValue();
  393. // Non-formatter codes are from 'input' to 'nextFmt'.
  394. int len = nextFmt - input;
  395. System.arraycopy(levels, input, levels, output, len);
  396. System.arraycopy(types, input, types, output, len);
  397. output += len;
  398. input = nextFmt + 1;
  399. }
  400. length -= formatterIndices.size();
  401. }
  402. /**
  403. * An internal function to compute the boundaries of runs
  404. * in the text. It isn't strictly necessary to do this, but
  405. * it lets us write some following passes in a less complicated
  406. * way. Also it lets us efficiently implement some of the public
  407. * methods. A run is simply a sequence of characters at the
  408. * same level.
  409. */
  410. private void computeRuns()
  411. {
  412. int runCount = 0;
  413. int currentEmbedding = baseEmbedding;
  414. for (int i = 0; i < length; ++i)
  415. {
  416. if (levels[i] != currentEmbedding)
  417. {
  418. currentEmbedding = levels[i];
  419. ++runCount;
  420. }
  421. }
  422. // This may be called multiple times. If so, and if
  423. // the number of runs has not changed, then don't bother
  424. // allocating a new array.
  425. if (runs == null || runs.length != runCount + 1)
  426. runs = new int[runCount + 1];
  427. int where = 0;
  428. int lastRunStart = 0;
  429. currentEmbedding = baseEmbedding;
  430. for (int i = 0; i < length; ++i)
  431. {
  432. if (levels[i] != currentEmbedding)
  433. {
  434. runs[where++] = lastRunStart;
  435. lastRunStart = i;
  436. currentEmbedding = levels[i];
  437. }
  438. }
  439. runs[where++] = lastRunStart;
  440. }
  441. /**
  442. * An internal method to resolve weak types. This implements
  443. * rules W1 through W7.
  444. */
  445. private void resolveWeakTypes()
  446. {
  447. final int runCount = getRunCount();
  448. int previousLevel = baseEmbedding;
  449. for (int run = 0; run < runCount; ++run)
  450. {
  451. int start = getRunStart(run);
  452. int end = getRunLimit(run);
  453. int level = getRunLevel(run);
  454. // These are the names used in the Bidi algorithm.
  455. byte sor = (((Math.max(previousLevel, level) % 2) == 0)
  456. ? Character.DIRECTIONALITY_LEFT_TO_RIGHT
  457. : Character.DIRECTIONALITY_RIGHT_TO_LEFT);
  458. int nextLevel;
  459. if (run == runCount - 1)
  460. nextLevel = baseEmbedding;
  461. else
  462. nextLevel = getRunLevel(run + 1);
  463. byte eor = (((Math.max(level, nextLevel) % 2) == 0)
  464. ? Character.DIRECTIONALITY_LEFT_TO_RIGHT
  465. : Character.DIRECTIONALITY_RIGHT_TO_LEFT);
  466. byte prevType = sor;
  467. byte prevStrongType = sor;
  468. for (int i = start; i < end; ++i)
  469. {
  470. final byte nextType = (i == end - 1) ? eor : types[i + 1];
  471. // Rule W1: change NSM to the prevailing direction.
  472. if (types[i] == Character.DIRECTIONALITY_NONSPACING_MARK)
  473. types[i] = prevType;
  474. else
  475. prevType = types[i];
  476. // Rule W2: change EN to AN in some cases.
  477. if (types[i] == Character.DIRECTIONALITY_EUROPEAN_NUMBER)
  478. {
  479. if (prevStrongType == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC)
  480. types[i] = Character.DIRECTIONALITY_ARABIC_NUMBER;
  481. }
  482. else if (types[i] == Character.DIRECTIONALITY_LEFT_TO_RIGHT
  483. || types[i] == Character.DIRECTIONALITY_RIGHT_TO_LEFT
  484. || types[i] == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC)
  485. prevStrongType = types[i];
  486. // Rule W3: change AL to R.
  487. if (types[i] == Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC)
  488. types[i] = Character.DIRECTIONALITY_RIGHT_TO_LEFT;
  489. // Rule W4: handle separators between two numbers.
  490. if (prevType == Character.DIRECTIONALITY_EUROPEAN_NUMBER
  491. && nextType == Character.DIRECTIONALITY_EUROPEAN_NUMBER)
  492. {
  493. if (types[i] == Character.DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR
  494. || types[i] == Character.DIRECTIONALITY_COMMON_NUMBER_SEPARATOR)
  495. types[i] = nextType;
  496. }
  497. else if (prevType == Character.DIRECTIONALITY_ARABIC_NUMBER
  498. && nextType == Character.DIRECTIONALITY_ARABIC_NUMBER
  499. && types[i] == Character.DIRECTIONALITY_COMMON_NUMBER_SEPARATOR)
  500. types[i] = nextType;
  501. // Rule W5: change a sequence of european terminators to
  502. // european numbers, if they are adjacent to european numbers.
  503. // We also include BN characters in this.
  504. if (types[i] == Character.DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR
  505. || types[i] == Character.DIRECTIONALITY_BOUNDARY_NEUTRAL)
  506. {
  507. if (prevType == Character.DIRECTIONALITY_EUROPEAN_NUMBER)
  508. types[i] = prevType;
  509. else
  510. {
  511. // Look ahead to see if there is an EN terminating this
  512. // sequence of ETs.
  513. int j = i + 1;
  514. while (j < end
  515. && (types[j] == Character.DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR
  516. || types[j] == Character.DIRECTIONALITY_BOUNDARY_NEUTRAL))
  517. ++j;
  518. if (j < end
  519. && types[j] == Character.DIRECTIONALITY_EUROPEAN_NUMBER)
  520. {
  521. // Change them all to EN now.
  522. for (int k = i; k < j; ++k)
  523. types[k] = Character.DIRECTIONALITY_EUROPEAN_NUMBER;
  524. }
  525. }
  526. }
  527. // Rule W6: separators and terminators change to ON.
  528. // Again we include BN.
  529. if (types[i] == Character.DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR
  530. || types[i] == Character.DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR
  531. || types[i] == Character.DIRECTIONALITY_COMMON_NUMBER_SEPARATOR
  532. || types[i] == Character.DIRECTIONALITY_BOUNDARY_NEUTRAL)
  533. types[i] = Character.DIRECTIONALITY_OTHER_NEUTRALS;
  534. // Rule W7: change european number types.
  535. if (prevStrongType == Character.DIRECTIONALITY_LEFT_TO_RIGHT
  536. && types[i] == Character.DIRECTIONALITY_EUROPEAN_NUMBER)
  537. types[i] = prevStrongType;
  538. }
  539. previousLevel = level;
  540. }
  541. }
  542. /**
  543. * An internal method to resolve neutral types. This implements
  544. * rules N1 and N2.
  545. */
  546. private void resolveNeutralTypes()
  547. {
  548. // This implements rules N1 and N2.
  549. final int runCount = getRunCount();
  550. int previousLevel = baseEmbedding;
  551. for (int run = 0; run < runCount; ++run)
  552. {
  553. int start = getRunStart(run);
  554. int end = getRunLimit(run);
  555. int level = getRunLevel(run);
  556. byte embeddingDirection
  557. = (((level % 2) == 0) ? Character.DIRECTIONALITY_LEFT_TO_RIGHT
  558. : Character.DIRECTIONALITY_RIGHT_TO_LEFT);
  559. // These are the names used in the Bidi algorithm.
  560. byte sor = (((Math.max(previousLevel, level) % 2) == 0)
  561. ? Character.DIRECTIONALITY_LEFT_TO_RIGHT
  562. : Character.DIRECTIONALITY_RIGHT_TO_LEFT);
  563. int nextLevel;
  564. if (run == runCount - 1)
  565. nextLevel = baseEmbedding;
  566. else
  567. nextLevel = getRunLevel(run + 1);
  568. byte eor = (((Math.max(level, nextLevel) % 2) == 0)
  569. ? Character.DIRECTIONALITY_LEFT_TO_RIGHT
  570. : Character.DIRECTIONALITY_RIGHT_TO_LEFT);
  571. byte prevStrong = sor;
  572. int neutralStart = -1;
  573. for (int i = start; i <= end; ++i)
  574. {
  575. byte newStrong = -1;
  576. byte thisType = i == end ? eor : types[i];
  577. switch (thisType)
  578. {
  579. case Character.DIRECTIONALITY_LEFT_TO_RIGHT:
  580. newStrong = Character.DIRECTIONALITY_LEFT_TO_RIGHT;
  581. break;
  582. case Character.DIRECTIONALITY_RIGHT_TO_LEFT:
  583. case Character.DIRECTIONALITY_ARABIC_NUMBER:
  584. case Character.DIRECTIONALITY_EUROPEAN_NUMBER:
  585. newStrong = Character.DIRECTIONALITY_RIGHT_TO_LEFT;
  586. break;
  587. case Character.DIRECTIONALITY_BOUNDARY_NEUTRAL:
  588. case Character.DIRECTIONALITY_OTHER_NEUTRALS:
  589. case Character.DIRECTIONALITY_SEGMENT_SEPARATOR:
  590. case Character.DIRECTIONALITY_PARAGRAPH_SEPARATOR:
  591. case Character.DIRECTIONALITY_WHITESPACE:
  592. if (neutralStart == -1)
  593. neutralStart = i;
  594. break;
  595. }
  596. // If we see a strong character, update all the neutrals.
  597. if (newStrong != -1)
  598. {
  599. if (neutralStart != -1)
  600. {
  601. byte override = (prevStrong == newStrong
  602. ? prevStrong
  603. : embeddingDirection);
  604. for (int j = neutralStart; j < i; ++j)
  605. types[j] = override;
  606. }
  607. prevStrong = newStrong;
  608. neutralStart = -1;
  609. }
  610. }
  611. previousLevel = level;
  612. }
  613. }
  614. /**
  615. * An internal method to resolve implicit levels.
  616. * This implements rules I1 and I2.
  617. */
  618. private void resolveImplicitLevels()
  619. {
  620. // This implements rules I1 and I2.
  621. for (int i = 0; i < length; ++i)
  622. {
  623. if ((levels[i] & 1) == 0)
  624. {
  625. if (types[i] == Character.DIRECTIONALITY_RIGHT_TO_LEFT)
  626. ++levels[i];
  627. else if (types[i] == Character.DIRECTIONALITY_ARABIC_NUMBER
  628. || types[i] == Character.DIRECTIONALITY_EUROPEAN_NUMBER)
  629. levels[i] += 2;
  630. }
  631. else
  632. {
  633. if (types[i] == Character.DIRECTIONALITY_LEFT_TO_RIGHT
  634. || types[i] == Character.DIRECTIONALITY_ARABIC_NUMBER
  635. || types[i] == Character.DIRECTIONALITY_EUROPEAN_NUMBER)
  636. ++levels[i];
  637. }
  638. // Update the result flags.
  639. resultFlags |= 1 << (levels[i] & 1);
  640. }
  641. // One final update of the result flags, using the base level.
  642. resultFlags |= 1 << baseEmbedding;
  643. }
  644. /**
  645. * This reinserts the formatting codes that we removed early on.
  646. * Actually it does not insert formatting codes per se, but rather
  647. * simply inserts new levels at the appropriate locations in the
  648. * 'levels' array.
  649. */
  650. private void reinsertFormattingCodes()
  651. {
  652. if (formatterIndices == null)
  653. return;
  654. int input = length;
  655. int output = levels.length;
  656. // Process from the end as we are copying the array over itself here.
  657. for (int index = formatterIndices.size() - 1; index >= 0; --index)
  658. {
  659. int nextFmt = formatterIndices.get(index).intValue();
  660. // nextFmt points to a location in the original array. So,
  661. // nextFmt+1 is the target of our copying. output is the location
  662. // to which we last copied, thus we can derive the length of the
  663. // copy from it.
  664. int len = output - nextFmt - 1;
  665. output = nextFmt;
  666. input -= len;
  667. // Note that we no longer need 'types' at this point, so we
  668. // only edit 'levels'.
  669. if (nextFmt + 1 < levels.length)
  670. System.arraycopy(levels, input, levels, nextFmt + 1, len);
  671. // Now set the level at the reinsertion point.
  672. int rightLevel;
  673. if (output == levels.length - 1)
  674. rightLevel = baseEmbedding;
  675. else
  676. rightLevel = levels[output + 1];
  677. int leftLevel;
  678. if (input == 0)
  679. leftLevel = baseEmbedding;
  680. else
  681. leftLevel = levels[input];
  682. levels[output] = (byte) Math.max(leftLevel, rightLevel);
  683. }
  684. length = levels.length;
  685. }
  686. /**
  687. * This is the main internal entry point. After a constructor
  688. * has initialized the appropriate local state, it will call
  689. * this method to do all the work.
  690. */
  691. private void runBidi()
  692. {
  693. computeTypes();
  694. baseEmbedding = computeParagraphEmbeddingLevel();
  695. computeExplicitLevels();
  696. computeRuns();
  697. resolveWeakTypes();
  698. resolveNeutralTypes();
  699. resolveImplicitLevels();
  700. // We're done with the types. Let the GC clean up.
  701. types = null;
  702. reinsertFormattingCodes();
  703. // After resolving the implicit levels, the number
  704. // of runs may have changed.
  705. computeRuns();
  706. }
  707. /**
  708. * Return true if the paragraph base embedding is left-to-right,
  709. * false otherwise.
  710. */
  711. public boolean baseIsLeftToRight()
  712. {
  713. return baseEmbedding == DIRECTION_LEFT_TO_RIGHT;
  714. }
  715. /**
  716. * Create a new Bidi object for a single line of text, taken
  717. * from the text used when creating the current Bidi object.
  718. * @param start the index of the first character of the line
  719. * @param end the index of the final character of the line
  720. * @return a new Bidi object for the indicated line of text
  721. */
  722. public Bidi createLineBidi(int start, int end)
  723. {
  724. // This isn't the most efficient implementation possible.
  725. // This probably does not matter, so we choose simplicity instead.
  726. int level = getLevelAt(start);
  727. int flag = (((level % 2) == 0)
  728. ? DIRECTION_LEFT_TO_RIGHT
  729. : DIRECTION_RIGHT_TO_LEFT);
  730. return new Bidi(text, textOffset + start,
  731. embeddings, embeddingOffset + start,
  732. end - start, flag);
  733. }
  734. /**
  735. * Return the base embedding level of the paragraph.
  736. */
  737. public int getBaseLevel()
  738. {
  739. return baseEmbedding;
  740. }
  741. /**
  742. * Return the length of the paragraph, in characters.
  743. */
  744. public int getLength()
  745. {
  746. return length;
  747. }
  748. /**
  749. * Return the level at the indicated character. If the
  750. * supplied index is less than zero or greater than the length
  751. * of the text, then the paragraph's base embedding level will
  752. * be returned.
  753. * @param offset the character to examine
  754. * @return the level of that character
  755. */
  756. public int getLevelAt(int offset)
  757. {
  758. if (offset < 0 || offset >= length)
  759. return getBaseLevel();
  760. return levels[offset];
  761. }
  762. /**
  763. * Return the number of runs in the result. A run is
  764. * a sequence of characters at the same embedding level.
  765. */
  766. public int getRunCount()
  767. {
  768. return runs.length;
  769. }
  770. /**
  771. * Return the level of the indicated run.
  772. * @param which the run to examine
  773. * @return the level of that run
  774. */
  775. public int getRunLevel(int which)
  776. {
  777. return levels[runs[which]];
  778. }
  779. /**
  780. * Return the index of the character just following the end
  781. * of the indicated run.
  782. * @param which the run to examine
  783. * @return the index of the character after the final character
  784. * of the run
  785. */
  786. public int getRunLimit(int which)
  787. {
  788. if (which == runs.length - 1)
  789. return length;
  790. return runs[which + 1];
  791. }
  792. /**
  793. * Return the index of the first character in the indicated run.
  794. * @param which the run to examine
  795. * @return the index of the first character of the run
  796. */
  797. public int getRunStart(int which)
  798. {
  799. return runs[which];
  800. }
  801. /**
  802. * Return true if the text is entirely left-to-right, and the
  803. * base embedding is also left-to-right.
  804. */
  805. public boolean isLeftToRight()
  806. {
  807. return resultFlags == LTOR;
  808. }
  809. /**
  810. * Return true if the text consists of mixed left-to-right and
  811. * right-to-left runs, or if the text consists of one kind of run
  812. * which differs from the base embedding direction.
  813. */
  814. public boolean isMixed()
  815. {
  816. return resultFlags == (LTOR | RTOL);
  817. }
  818. /**
  819. * Return true if the text is entirely right-to-left, and the
  820. * base embedding is also right-to-left.
  821. */
  822. public boolean isRightToLeft()
  823. {
  824. return resultFlags == RTOL;
  825. }
  826. /**
  827. * Return a String describing the internal state of this object.
  828. * This is only useful for debugging.
  829. */
  830. public String toString()
  831. {
  832. return "Bidi Bidi Bidi I like you, Buck!";
  833. }
  834. /**
  835. * Reorder objects according to the levels passed in. This implements
  836. * reordering as defined by the Unicode bidirectional layout specification.
  837. * The levels are integers from 0 to 62; even numbers represent left-to-right
  838. * runs, and odd numbers represent right-to-left runs.
  839. *
  840. * @param levels the levels associated with each object
  841. * @param levelOffset the index of the first level to use
  842. * @param objs the objects to reorder according to the levels
  843. * @param objOffset the index of the first object to use
  844. * @param count the number of objects (and levels) to manipulate
  845. */
  846. public static void reorderVisually(byte[] levels, int levelOffset,
  847. Object[] objs, int objOffset, int count)
  848. {
  849. // We need a copy of the 'levels' array, as we are going to modify it.
  850. // This is unfortunate but difficult to avoid.
  851. byte[] levelCopy = new byte[count];
  852. // Do this explicitly so we can also find the maximum depth at the
  853. // same time.
  854. int max = 0;
  855. int lowestOdd = 63;
  856. for (int i = 0; i < count; ++i)
  857. {
  858. levelCopy[i] = levels[levelOffset + i];
  859. max = Math.max(levelCopy[i], max);
  860. if (levelCopy[i] % 2 != 0)
  861. lowestOdd = Math.min(lowestOdd, levelCopy[i]);
  862. }
  863. // Reverse the runs starting with the deepest.
  864. for (int depth = max; depth >= lowestOdd; --depth)
  865. {
  866. int start = 0;
  867. while (start < count)
  868. {
  869. // Find the start of a run >= DEPTH.
  870. while (start < count && levelCopy[start] < depth)
  871. ++start;
  872. if (start == count)
  873. break;
  874. // Find the end of the run.
  875. int end = start + 1;
  876. while (end < count && levelCopy[end] >= depth)
  877. ++end;
  878. // Reverse this run.
  879. for (int i = 0; i < (end - start) / 2; ++i)
  880. {
  881. byte tmpb = levelCopy[end - i - 1];
  882. levelCopy[end - i - 1] = levelCopy[start + i];
  883. levelCopy[start + i] = tmpb;
  884. Object tmpo = objs[objOffset + end - i - 1];
  885. objs[objOffset + end - i - 1] = objs[objOffset + start + i];
  886. objs[objOffset + start + i] = tmpo;
  887. }
  888. // Handle the next run.
  889. start = end + 1;
  890. }
  891. }
  892. }
  893. /**
  894. * Returns false if all characters in the text between start and end
  895. * are all left-to-right text. This implementation is just calls
  896. * <code>Character.getDirectionality(char)</code> on all characters
  897. * and makes sure all characters are either explicitly left-to-right
  898. * or neutral in directionality (character types L, EN, ES, ET, AN,
  899. * CS, S and WS).
  900. */
  901. public static boolean requiresBidi(char[] text, int start, int end)
  902. {
  903. for (int i = start; i < end; i++)
  904. {
  905. byte dir = Character.getDirectionality(text[i]);
  906. if (dir != Character.DIRECTIONALITY_LEFT_TO_RIGHT
  907. && dir != Character.DIRECTIONALITY_EUROPEAN_NUMBER
  908. && dir != Character.DIRECTIONALITY_EUROPEAN_NUMBER_SEPARATOR
  909. && dir != Character.DIRECTIONALITY_EUROPEAN_NUMBER_TERMINATOR
  910. && dir != Character.DIRECTIONALITY_ARABIC_NUMBER
  911. && dir != Character.DIRECTIONALITY_COMMON_NUMBER_SEPARATOR
  912. && dir != Character.DIRECTIONALITY_SEGMENT_SEPARATOR
  913. && dir != Character.DIRECTIONALITY_WHITESPACE
  914. && dir != Character.DIRECTIONALITY_PARAGRAPH_SEPARATOR)
  915. return true;
  916. }
  917. return false;
  918. }
  919. }