You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UnicodeBidiAlgorithm.java 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /* $Id$ */
  18. package org.apache.fop.complexscripts.bidi;
  19. import org.apache.commons.logging.Log;
  20. import org.apache.commons.logging.LogFactory;
  21. import org.apache.fop.traits.Direction;
  22. import org.apache.fop.util.CharUtilities;
  23. // CSOFF: LineLengthCheck
  24. /**
  25. * <p>The <code>UnicodeBidiAlgorithm</code> class implements functionality prescribed by
  26. * the Unicode Bidirectional Algorithm, Unicode Standard Annex #9.</p>
  27. *
  28. * <p>This work was originally authored by Glenn Adams (gadams@apache.org).</p>
  29. */
  30. public final class UnicodeBidiAlgorithm implements BidiConstants {
  31. /**
  32. * logging instance
  33. */
  34. private static final Log log = LogFactory.getLog(UnicodeBidiAlgorithm.class);
  35. private UnicodeBidiAlgorithm() {
  36. }
  37. /**
  38. * Resolve the directionality levels of each character in a character seqeunce.
  39. * If some character is encoded in the character sequence as a Unicode Surrogate Pair,
  40. * then the directionality level of each of the two members of the pair will be identical.
  41. * @return null if bidirectional processing is not required; otherwise, returns an array
  42. * of integers, where each integer corresponds to exactly one UTF-16
  43. * encoding element present in the input character sequence, and where each integer denotes
  44. * the directionality level of the corresponding encoding element
  45. * @param cs input character sequence representing a UTF-16 encoded string
  46. * @param defaultLevel the default paragraph level, which must be zero (LR) or one (RL)
  47. */
  48. public static int[] resolveLevels(CharSequence cs, Direction defaultLevel) {
  49. int[] chars = new int [ cs.length() ];
  50. if (convertToScalar(cs, chars) || (defaultLevel == Direction.RL)) {
  51. return resolveLevels(chars, (defaultLevel == Direction.RL) ? 1 : 0, new int [ chars.length ]);
  52. } else {
  53. return null;
  54. }
  55. }
  56. /**
  57. * Resolve the directionality levels of each character in a character seqeunce.
  58. * @return null if bidirectional processing is not required; otherwise, returns an array
  59. * of integers, where each integer corresponds to exactly one UTF-16
  60. * encoding element present in the input character sequence, and where each integer denotes
  61. * the directionality level of the corresponding encoding element
  62. * @param chars array of input characters represented as unicode scalar values
  63. * @param defaultLevel the default paragraph level, which must be zero (LR) or one (RL)
  64. * @param levels array to receive levels, one for each character in chars array
  65. */
  66. public static int[] resolveLevels(int[] chars, int defaultLevel, int[] levels) {
  67. return resolveLevels(chars, getClasses(chars), defaultLevel, levels, false);
  68. }
  69. /**
  70. * Resolve the directionality levels of each character in a character seqeunce.
  71. * @return null if bidirectional processing is not required; otherwise, returns an array
  72. * of integers, where each integer corresponds to exactly one UTF-16
  73. * encoding element present in the input character sequence, and where each integer denotes
  74. * the directionality level of the corresponding encoding element
  75. * @param chars array of input characters represented as unicode scalar values
  76. * @param classes array containing one bidi class per character in chars array
  77. * @param defaultLevel the default paragraph level, which must be zero (LR) or one (RL)
  78. * @param levels array to receive levels, one for each character in chars array
  79. * @param useRuleL1 true if rule L1 should be used
  80. */
  81. public static int[] resolveLevels(int[] chars, int[] classes, int defaultLevel, int[] levels, boolean useRuleL1) {
  82. int[] ica = classes;
  83. int[] wca = copySequence(ica);
  84. int[] ea = new int [ levels.length ];
  85. resolveExplicit(wca, defaultLevel, ea);
  86. resolveRuns(wca, defaultLevel, ea, levelsFromEmbeddings(ea, levels));
  87. if (useRuleL1) {
  88. resolveSeparators(ica, wca, defaultLevel, levels);
  89. }
  90. dump("RL: CC(" + ((chars != null) ? chars.length : -1) + ")", chars, classes, defaultLevel, levels);
  91. return levels;
  92. }
  93. private static int[] copySequence(int[] ta) {
  94. int[] na = new int [ ta.length ];
  95. System.arraycopy(ta, 0, na, 0, na.length);
  96. return na;
  97. }
  98. private static void resolveExplicit(int[] wca, int defaultLevel, int[] ea) {
  99. int[] es = new int [ MAX_LEVELS ]; /* embeddings stack */
  100. int ei = 0; /* embeddings stack index */
  101. int ec = defaultLevel; /* current embedding level */
  102. for (int i = 0, n = wca.length; i < n; i++) {
  103. int bc = wca [ i ]; /* bidi class of current char */
  104. int el; /* embedding level to assign to current char */
  105. switch (bc) {
  106. case LRE: // start left-to-right embedding
  107. case RLE: // start right-to-left embedding
  108. case LRO: // start left-to-right override
  109. case RLO: // start right-to-left override
  110. int en; /* new embedding level */
  111. if ((bc == RLE) || (bc == RLO)) {
  112. en = ((ec & ~OVERRIDE) + 1) | 1;
  113. } else {
  114. en = ((ec & ~OVERRIDE) + 2) & ~1;
  115. }
  116. if (en < (MAX_LEVELS + 1)) {
  117. es [ ei++ ] = ec;
  118. if ((bc == LRO) || (bc == RLO)) {
  119. ec = en | OVERRIDE;
  120. } else {
  121. ec = en & ~OVERRIDE;
  122. }
  123. } else {
  124. // max levels exceeded, so don't change level or override
  125. }
  126. el = ec;
  127. break;
  128. case PDF: // pop directional formatting
  129. el = ec;
  130. if (ei > 0) {
  131. ec = es [ --ei ];
  132. } else {
  133. // ignore isolated PDF
  134. }
  135. break;
  136. case B: // paragraph separator
  137. el = ec = defaultLevel;
  138. ei = 0;
  139. break;
  140. default:
  141. el = ec;
  142. break;
  143. }
  144. switch (bc) {
  145. case BN:
  146. break;
  147. case LRE: case RLE: case LRO: case RLO: case PDF:
  148. wca [ i ] = BN;
  149. break;
  150. default:
  151. if ((el & OVERRIDE) != 0) {
  152. wca [ i ] = directionOfLevel(el);
  153. }
  154. break;
  155. }
  156. ea [ i ] = el;
  157. }
  158. }
  159. private static int directionOfLevel(int level) {
  160. return ((level & 1) != 0) ? R : L;
  161. }
  162. private static int levelOfEmbedding(int embedding) {
  163. return embedding & ~OVERRIDE;
  164. }
  165. private static int[] levelsFromEmbeddings(int[] ea, int[] la) {
  166. assert ea != null;
  167. assert la != null;
  168. assert la.length == ea.length;
  169. for (int i = 0, n = la.length; i < n; i++) {
  170. la [ i ] = levelOfEmbedding(ea [ i ]);
  171. }
  172. return la;
  173. }
  174. private static void resolveRuns(int[] wca, int defaultLevel, int[] ea, int[] la) {
  175. if (la.length != wca.length) {
  176. throw new IllegalArgumentException("levels sequence length must match classes sequence length");
  177. } else if (la.length != ea.length) {
  178. throw new IllegalArgumentException("levels sequence length must match embeddings sequence length");
  179. } else {
  180. for (int i = 0, n = ea.length, lPrev = defaultLevel; i < n; ) {
  181. int s = i;
  182. int e = s;
  183. int l = findNextNonRetainedFormattingLevel(wca, ea, s, lPrev);
  184. while (e < n) {
  185. if (la [ e ] != l) {
  186. if (startsWithRetainedFormattingRun(wca, ea, e)) {
  187. e += getLevelRunLength(ea, e);
  188. } else {
  189. break;
  190. }
  191. } else {
  192. e++;
  193. }
  194. }
  195. lPrev = resolveRun(wca, defaultLevel, ea, la, s, e, l, lPrev);
  196. i = e;
  197. }
  198. }
  199. }
  200. private static int findNextNonRetainedFormattingLevel(int[] wca, int[] ea, int start, int lPrev) {
  201. int s = start;
  202. int e = wca.length;
  203. while (s < e) {
  204. if (startsWithRetainedFormattingRun(wca, ea, s)) {
  205. s += getLevelRunLength(ea, s);
  206. } else {
  207. break;
  208. }
  209. }
  210. if (s < e) {
  211. return levelOfEmbedding(ea [ s ]);
  212. } else {
  213. return lPrev;
  214. }
  215. }
  216. private static int getLevelRunLength(int[] ea, int start) {
  217. assert start < ea.length;
  218. int nl = 0;
  219. for (int s = start, e = ea.length, l0 = levelOfEmbedding(ea [ start ]); s < e; s++) {
  220. if (levelOfEmbedding(ea [ s ]) == l0) {
  221. nl++;
  222. } else {
  223. break;
  224. }
  225. }
  226. return nl;
  227. }
  228. private static boolean startsWithRetainedFormattingRun(int[] wca, int[] ea, int start) {
  229. int nl = getLevelRunLength(ea, start);
  230. if (nl > 0) {
  231. int nc = getRetainedFormattingRunLength(wca, start);
  232. return (nc >= nl);
  233. } else {
  234. return false;
  235. }
  236. }
  237. private static int getRetainedFormattingRunLength(int[] wca, int start) {
  238. assert start < wca.length;
  239. int nc = 0;
  240. for (int s = start, e = wca.length; s < e; s++) {
  241. if (wca [ s ] == BidiConstants.BN) {
  242. nc++;
  243. } else {
  244. break;
  245. }
  246. }
  247. return nc;
  248. }
  249. private static int resolveRun(int[] wca, int defaultLevel, int[] ea, int[] la, int start, int end, int level, int levelPrev) {
  250. // determine start of run direction
  251. int sor = directionOfLevel(max(levelPrev, level));
  252. // determine end of run direction
  253. int le = -1;
  254. if (end == wca.length) {
  255. le = max(level, defaultLevel);
  256. } else {
  257. for (int i = end; i < wca.length; i++) {
  258. if (wca [ i ] != BidiConstants.BN) {
  259. le = max(level, la [ i ]);
  260. break;
  261. }
  262. }
  263. if (le < 0) {
  264. le = max(level, defaultLevel);
  265. }
  266. }
  267. int eor = directionOfLevel(le);
  268. if (log.isDebugEnabled()) {
  269. log.debug("BR[" + padLeft(start, 3) + "," + padLeft(end, 3) + "] :" + padLeft(level, 2) + ": SOR(" + getClassName(sor) + "), EOR(" + getClassName(eor) + ")");
  270. }
  271. resolveWeak(wca, defaultLevel, ea, la, start, end, level, sor, eor);
  272. resolveNeutrals(wca, defaultLevel, ea, la, start, end, level, sor, eor);
  273. resolveImplicit(wca, defaultLevel, ea, la, start, end, level, sor, eor);
  274. // if this run is all retained formatting, then return prior level, otherwise this run's level
  275. return isRetainedFormatting(wca, start, end) ? levelPrev : level;
  276. }
  277. private static void resolveWeak(int[] wca, int defaultLevel, int[] ea, int[] la, int start, int end, int level, int sor, int eor) {
  278. // W1 - X BN* NSM -> X BN* X
  279. for (int i = start, n = end, bcPrev = sor; i < n; i++) {
  280. int bc = wca [ i ];
  281. if (bc == NSM) {
  282. wca [ i ] = bcPrev;
  283. } else if (bc != BN) {
  284. bcPrev = bc;
  285. }
  286. }
  287. // W2 - AL ... EN -> AL ... AN
  288. for (int i = start, n = end, bcPrev = sor; i < n; i++) {
  289. int bc = wca [ i ];
  290. if (bc == EN) {
  291. if (bcPrev == AL) {
  292. wca [ i ] = AN;
  293. }
  294. } else if (isStrong(bc)) {
  295. bcPrev = bc;
  296. }
  297. }
  298. // W3 - AL -> R
  299. for (int i = start, n = end; i < n; i++) {
  300. int bc = wca [ i ];
  301. if (bc == AL) {
  302. wca [ i ] = R;
  303. }
  304. }
  305. // W4 - EN BN* ES BN* EN -> EN BN* EN BN* EN; XN BN* CS BN* XN -> XN BN* XN BN* XN
  306. for (int i = start, n = end, bcPrev = sor; i < n; i++) {
  307. int bc = wca [ i ];
  308. if (bc == ES) {
  309. int bcNext = eor;
  310. for (int j = i + 1; j < n; j++) {
  311. if ((bc = wca [ j ]) != BN) {
  312. bcNext = bc;
  313. break;
  314. }
  315. }
  316. if ((bcPrev == EN) && (bcNext == EN)) {
  317. wca [ i ] = EN;
  318. }
  319. } else if (bc == CS) {
  320. int bcNext = eor;
  321. for (int j = i + 1; j < n; j++) {
  322. if ((bc = wca [ j ]) != BN) {
  323. bcNext = bc;
  324. break;
  325. }
  326. }
  327. if ((bcPrev == EN) && (bcNext == EN)) {
  328. wca [ i ] = EN;
  329. } else if ((bcPrev == AN) && (bcNext == AN)) {
  330. wca [ i ] = AN;
  331. }
  332. }
  333. if (bc != BN) {
  334. bcPrev = bc;
  335. }
  336. }
  337. // W5 - EN (ET|BN)* -> EN (EN|BN)*; (ET|BN)* EN -> (EN|BN)* EN
  338. for (int i = start, n = end, bcPrev = sor; i < n; i++) {
  339. int bc = wca [ i ];
  340. if (bc == ET) {
  341. int bcNext = eor;
  342. for (int j = i + 1; j < n; j++) {
  343. bc = wca [ j ];
  344. if ((bc != BN) && (bc != ET)) {
  345. bcNext = bc;
  346. break;
  347. }
  348. }
  349. if ((bcPrev == EN) || (bcNext == EN)) {
  350. wca [ i ] = EN;
  351. }
  352. } else if ((bc != BN) && (bc != ET)) {
  353. bcPrev = bc;
  354. }
  355. }
  356. // W6 - BN* (ET|ES|CS) BN* -> ON* ON ON*
  357. for (int i = start, n = end; i < n; i++) {
  358. int bc = wca [ i ];
  359. if ((bc == ET) || (bc == ES) || (bc == CS)) {
  360. wca [ i ] = ON;
  361. resolveAdjacentBoundaryNeutrals(wca, start, end, i, ON);
  362. }
  363. }
  364. // W7 - L ... EN -> L ... L
  365. for (int i = start, n = end, bcPrev = sor; i < n; i++) {
  366. int bc = wca [ i ];
  367. if (bc == EN) {
  368. if (bcPrev == L) {
  369. wca [ i ] = L;
  370. }
  371. } else if ((bc == L) || (bc == R)) {
  372. bcPrev = bc;
  373. }
  374. }
  375. }
  376. private static void resolveNeutrals(int[] wca, int defaultLevel, int[] ea, int[] la, int start, int end, int level, int sor, int eor) {
  377. // N1 - (L|R) N+ (L|R) -> L L+ L | R R+ R; (AN|EN) N+ R -> (AN|EN) R+ R; R N+ (AN|EN) -> R R+ (AN|EN)
  378. for (int i = start, n = end, bcPrev = sor; i < n; i++) {
  379. int bc = wca [ i ];
  380. if (isNeutral(bc)) {
  381. int bcNext = eor;
  382. for (int j = i + 1; j < n; j++) {
  383. bc = wca [ j ];
  384. if ((bc == L) || (bc == R)) {
  385. bcNext = bc;
  386. break;
  387. } else if ((bc == AN) || (bc == EN)) {
  388. bcNext = R;
  389. break;
  390. } else if (isNeutral(bc)) {
  391. continue;
  392. } else if (isRetainedFormatting(bc)) {
  393. continue;
  394. } else {
  395. break;
  396. }
  397. }
  398. if (bcPrev == bcNext) {
  399. wca [ i ] = bcPrev;
  400. resolveAdjacentBoundaryNeutrals(wca, start, end, i, bcPrev);
  401. }
  402. } else if ((bc == L) || (bc == R)) {
  403. bcPrev = bc;
  404. } else if ((bc == AN) || (bc == EN)) {
  405. bcPrev = R;
  406. }
  407. }
  408. // N2 - N -> embedding level
  409. for (int i = start, n = end; i < n; i++) {
  410. int bc = wca [ i ];
  411. if (isNeutral(bc)) {
  412. int bcEmbedding = directionOfLevel(levelOfEmbedding(ea [ i ]));
  413. wca [ i ] = bcEmbedding;
  414. resolveAdjacentBoundaryNeutrals(wca, start, end, i, bcEmbedding);
  415. }
  416. }
  417. }
  418. private static void resolveAdjacentBoundaryNeutrals(int[] wca, int start, int end, int index, int bcNew) {
  419. if ((index < start) || (index >= end)) {
  420. throw new IllegalArgumentException();
  421. } else {
  422. for (int i = index - 1; i >= start; i--) {
  423. int bc = wca [ i ];
  424. if (bc == BN) {
  425. wca [ i ] = bcNew;
  426. } else {
  427. break;
  428. }
  429. }
  430. for (int i = index + 1; i < end; i++) {
  431. int bc = wca [ i ];
  432. if (bc == BN) {
  433. wca [ i ] = bcNew;
  434. } else {
  435. break;
  436. }
  437. }
  438. }
  439. }
  440. private static void resolveImplicit(int[] wca, int defaultLevel, int[] ea, int[] la, int start, int end, int level, int sor, int eor) {
  441. for (int i = start, n = end; i < n; i++) {
  442. int bc = wca [ i ]; // bidi class
  443. int el = la [ i ]; // embedding level
  444. int ed = 0; // embedding level delta
  445. if ((el & 1) == 0) { // even
  446. if (bc == R) {
  447. ed = 1;
  448. } else if (bc == AN) {
  449. ed = 2;
  450. } else if (bc == EN) {
  451. ed = 2;
  452. }
  453. } else { // odd
  454. if (bc == L) {
  455. ed = 1;
  456. } else if (bc == EN) {
  457. ed = 1;
  458. } else if (bc == AN) {
  459. ed = 1;
  460. }
  461. }
  462. la [ i ] = el + ed;
  463. }
  464. }
  465. /**
  466. * Resolve separators and boundary neutral levels to account for UAX#9 3.4 L1 while taking into
  467. * account retention of formatting codes (5.2).
  468. * @param ica original input class array (sequence)
  469. * @param wca working copy of original intput class array (sequence), as modified by prior steps
  470. * @param dl default paragraph level
  471. * @param la array of output levels to be adjusted, as produced by bidi algorithm
  472. */
  473. private static void resolveSeparators(int[] ica, int[] wca, int dl, int[] la) {
  474. // steps (1) through (3)
  475. for (int i = 0, n = ica.length; i < n; i++) {
  476. int ic = ica[i];
  477. if ((ic == BidiConstants.S) || (ic == BidiConstants.B)) {
  478. la[i] = dl;
  479. for (int k = i - 1; k >= 0; k--) {
  480. int pc = ica[k];
  481. if (isRetainedFormatting(pc)) {
  482. continue;
  483. } else if (pc == BidiConstants.WS) {
  484. la[k] = dl;
  485. } else {
  486. break;
  487. }
  488. }
  489. }
  490. }
  491. // step (4) - consider end of input sequence to be end of line, but skip any trailing boundary neutrals and retained formatting codes
  492. for (int i = ica.length; i > 0; i--) {
  493. int k = i - 1;
  494. int ic = ica[k];
  495. if (isRetainedFormatting(ic)) {
  496. continue;
  497. } else if (ic == BidiConstants.WS) {
  498. la[k] = dl;
  499. } else {
  500. break;
  501. }
  502. }
  503. // step (5) - per section 5.2
  504. for (int i = 0, n = ica.length; i < n; i++) {
  505. int ic = ica[i];
  506. if (isRetainedFormatting(ic)) {
  507. if (i == 0) {
  508. la[i] = dl;
  509. } else {
  510. la[i] = la [ i - 1 ];
  511. }
  512. }
  513. }
  514. }
  515. private static boolean isStrong(int bc) {
  516. switch (bc) {
  517. case L:
  518. case R:
  519. case AL:
  520. return true;
  521. default:
  522. return false;
  523. }
  524. }
  525. private static boolean isNeutral(int bc) {
  526. switch (bc) {
  527. case WS:
  528. case ON:
  529. case S:
  530. case B:
  531. return true;
  532. default:
  533. return false;
  534. }
  535. }
  536. private static boolean isRetainedFormatting(int bc) {
  537. switch (bc) {
  538. case LRE:
  539. case LRO:
  540. case RLE:
  541. case RLO:
  542. case PDF:
  543. case BN:
  544. return true;
  545. default:
  546. return false;
  547. }
  548. }
  549. private static boolean isRetainedFormatting(int[] ca, int s, int e) {
  550. for (int i = s; i < e; i++) {
  551. if (!isRetainedFormatting(ca[i])) {
  552. return false;
  553. }
  554. }
  555. return true;
  556. }
  557. private static int max(int x, int y) {
  558. if (x > y) {
  559. return x;
  560. } else {
  561. return y;
  562. }
  563. }
  564. private static int[] getClasses(int[] chars) {
  565. int[] classes = new int [ chars.length ];
  566. int bc;
  567. for (int i = 0, n = chars.length; i < n; i++) {
  568. int ch = chars [ i ];
  569. if (ch >= 0) {
  570. bc = BidiClass.getBidiClass(chars [ i ]);
  571. } else {
  572. bc = SURROGATE;
  573. }
  574. classes [ i ] = bc;
  575. }
  576. return classes;
  577. }
  578. /**
  579. * Convert character sequence (a UTF-16 encoded string) to an array of unicode scalar values
  580. * expressed as integers. If a valid UTF-16 surrogate pair is encountered, it is converted to
  581. * two integers, the first being the equivalent unicode scalar value, and the second being
  582. * negative one (-1). This special mechanism is used to track the use of surrogate pairs while
  583. * working with unicode scalar values, and permits maintaining indices that apply both to the
  584. * input UTF-16 and out scalar value sequences.
  585. * @return a boolean indicating that content is present that triggers bidirectional processing
  586. * @param cs a UTF-16 encoded character sequence
  587. * @param chars an integer array to accept the converted scalar values, where the length of the
  588. * array must be the same as the length of the input character sequence
  589. * @throws IllegalArgumentException if the input sequence is not a valid UTF-16 string, e.g.,
  590. * if it contains an isolated UTF-16 surrogate
  591. */
  592. private static boolean convertToScalar(CharSequence cs, int[] chars) throws IllegalArgumentException {
  593. boolean triggered = false;
  594. if (chars.length != cs.length()) {
  595. throw new IllegalArgumentException("characters array length must match input sequence length");
  596. }
  597. for (int i = 0, n = chars.length; i < n; ) {
  598. int chIn = cs.charAt(i);
  599. int chOut;
  600. if (chIn < 0xD800) {
  601. chOut = chIn;
  602. } else if (chIn < 0xDC00) {
  603. int chHi = chIn;
  604. int chLo;
  605. if ((i + 1) < n) {
  606. chLo = cs.charAt(i + 1);
  607. if ((chLo >= 0xDC00) && (chLo <= 0xDFFF)) {
  608. chOut = convertToScalar(chHi, chLo);
  609. } else {
  610. throw new IllegalArgumentException("isolated high surrogate");
  611. }
  612. } else {
  613. throw new IllegalArgumentException("truncated surrogate pair");
  614. }
  615. } else if (chIn < 0xE000) {
  616. throw new IllegalArgumentException("isolated low surrogate");
  617. } else {
  618. chOut = chIn;
  619. }
  620. if (!triggered && triggersBidi(chOut)) {
  621. triggered = true;
  622. }
  623. if ((chOut & 0xFF0000) == 0) {
  624. chars [ i++ ] = chOut;
  625. } else {
  626. chars [ i++ ] = chOut;
  627. chars [ i++ ] = -1;
  628. }
  629. }
  630. return triggered;
  631. }
  632. /**
  633. * Convert UTF-16 surrogate pair to unicode scalar valuee.
  634. * @return a unicode scalar value
  635. * @param chHi high (most significant or first) surrogate
  636. * @param chLo low (least significant or second) surrogate
  637. * @throws IllegalArgumentException if one of the input surrogates is not valid
  638. */
  639. private static int convertToScalar(int chHi, int chLo) {
  640. if ((chHi < 0xD800) || (chHi > 0xDBFF)) {
  641. throw new IllegalArgumentException("bad high surrogate");
  642. } else if ((chLo < 0xDC00) || (chLo > 0xDFFF)) {
  643. throw new IllegalArgumentException("bad low surrogate");
  644. } else {
  645. return (((chHi & 0x03FF) << 10) | (chLo & 0x03FF)) + 0x10000;
  646. }
  647. }
  648. /**
  649. * Determine of character CH triggers bidirectional processing. Bidirectional
  650. * processing is deemed triggerable if CH is a strong right-to-left character,
  651. * an arabic letter or number, or is a right-to-left embedding or override
  652. * character.
  653. * @return true if character triggers bidirectional processing
  654. * @param ch a unicode scalar value
  655. */
  656. private static boolean triggersBidi(int ch) {
  657. switch (BidiClass.getBidiClass(ch)) {
  658. case R:
  659. case AL:
  660. case AN:
  661. case RLE:
  662. case RLO:
  663. return true;
  664. default:
  665. return false;
  666. }
  667. }
  668. private static void dump(String header, int[] chars, int[] classes, int defaultLevel, int[] levels) {
  669. log.debug(header);
  670. log.debug("BD: default level(" + defaultLevel + ")");
  671. StringBuffer sb = new StringBuffer();
  672. if (chars != null) {
  673. for (int i = 0, n = chars.length; i < n; i++) {
  674. int ch = chars [ i ];
  675. sb.setLength(0);
  676. if ((ch > 0x20) && (ch < 0x7F)) {
  677. sb.append((char) ch);
  678. } else {
  679. sb.append(CharUtilities.charToNCRef(ch));
  680. }
  681. for (int k = sb.length(); k < 12; k++) {
  682. sb.append(' ');
  683. }
  684. sb.append(": " + padRight(getClassName(classes[i]), 4) + " " + levels[i]);
  685. log.debug(sb);
  686. }
  687. } else {
  688. for (int i = 0, n = classes.length; i < n; i++) {
  689. sb.setLength(0);
  690. for (int k = sb.length(); k < 12; k++) {
  691. sb.append(' ');
  692. }
  693. sb.append(": " + padRight(getClassName(classes[i]), 4) + " " + levels[i]);
  694. log.debug(sb);
  695. }
  696. }
  697. }
  698. private static String getClassName(int bc) {
  699. switch (bc) {
  700. case L: // left-to-right
  701. return "L";
  702. case LRE: // left-to-right embedding
  703. return "LRE";
  704. case LRO: // left-to-right override
  705. return "LRO";
  706. case R: // right-to-left
  707. return "R";
  708. case AL: // right-to-left arabic
  709. return "AL";
  710. case RLE: // right-to-left embedding
  711. return "RLE";
  712. case RLO: // right-to-left override
  713. return "RLO";
  714. case PDF: // pop directional formatting
  715. return "PDF";
  716. case EN: // european number
  717. return "EN";
  718. case ES: // european number separator
  719. return "ES";
  720. case ET: // european number terminator
  721. return "ET";
  722. case AN: // arabic number
  723. return "AN";
  724. case CS: // common number separator
  725. return "CS";
  726. case NSM: // non-spacing mark
  727. return "NSM";
  728. case BN: // boundary neutral
  729. return "BN";
  730. case B: // paragraph separator
  731. return "B";
  732. case S: // segment separator
  733. return "S";
  734. case WS: // whitespace
  735. return "WS";
  736. case ON: // other neutrals
  737. return "ON";
  738. case SURROGATE: // placeholder for low surrogate
  739. return "SUR";
  740. default:
  741. return "?";
  742. }
  743. }
  744. private static String padLeft(int n, int width) {
  745. return padLeft(Integer.toString(n), width);
  746. }
  747. private static String padLeft(String s, int width) {
  748. StringBuffer sb = new StringBuffer();
  749. for (int i = s.length(); i < width; i++) {
  750. sb.append(' ');
  751. }
  752. sb.append(s);
  753. return sb.toString();
  754. }
  755. /* not used yet
  756. private static String padRight ( int n, int width ) {
  757. return padRight ( Integer.toString ( n ), width );
  758. }
  759. */
  760. private static String padRight(String s, int width) {
  761. StringBuffer sb = new StringBuffer(s);
  762. for (int i = sb.length(); i < width; i++) {
  763. sb.append(' ');
  764. }
  765. return sb.toString();
  766. }
  767. }