bidi-std.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. // Extracted from Bidi.cpp - version 26
  2. // Reference implementation for Unicode Bidirectional Algorithm
  3. // Bidi include file
  4. #include "mupdf/fitz.h"
  5. #include "bidi-imp.h"
  6. #include <assert.h>
  7. #ifndef TRUE
  8. #define TRUE (1)
  9. #endif
  10. #ifndef FALSE
  11. #define FALSE (0)
  12. #endif
  13. /*------------------------------------------------------------------------
  14. File: Bidi.Cpp
  15. Description
  16. -----------
  17. Sample Implementation of the Unicode Bidirectional Algorithm as it
  18. was revised by Revision 5 of the Unicode Technical Report # 9
  19. (1999-8-17)
  20. Verified for changes to the algorithm up through Unicode 5.2.0 (2009).
  21. This implementation is organized into several passes, each implemen-
  22. ting one or more of the rules of the Unicode Bidi Algorithm. The
  23. resolution of Weak Types and of Neutrals each use a state table
  24. approach.
  25. Both a printf based interface and a Windows DlgProc are provided for
  26. interactive testing.
  27. A stress harness comparing this implementation (v24) to a Java based
  28. implementation was used by Doug Felt to verify that the two
  29. implementations produce identical results for all strings up to six
  30. bidi classes and stochastic strings up to length 20.
  31. Version 26 was verified by the author against the Unicode 5.2.0
  32. file BidiTest.txt, which provides an exhaustive text of strings of
  33. length 4 or less, but covers some important cases where the language
  34. in UAX#9 had been clarified.
  35. To see this code running in an actual Windows program,
  36. download the free Unibook utility from http://unicode.org/unibook
  37. The bidi demo is executed from the tools menu. It is build from
  38. this source file.
  39. Build Notes
  40. -----------
  41. To compile the sample implementation please set the #define
  42. directives above so the correct headers get included. Not all the
  43. files are needed for all purposes. For the commandline version
  44. only bidi.h and bidi.cpp are needed.
  45. The Win32 version is provided as a dialog procedure. To use as a
  46. standalone program compile with the lbmain.cpp file. If all you
  47. need is the ability to run the code "as is", you can instead download
  48. the unibook utility from http://uincode.org/unibook/ which contains
  49. the bidi demo compiled from this source file.
  50. This code uses an extension to C++ that gives variables declared in
  51. a for() statement function the same scope as the for() statement.
  52. If your compiler does not support this extension, you may need to
  53. move the declaration, e.g. int ich = 0; in front of the for statement.
  54. Implementation Note
  55. -------------------
  56. NOTE: The Unicode Bidirectional Algorithm removes all explicit
  57. formatting codes in rule X9, but states that this can be
  58. simulated by conformant implementations. This implementation
  59. attempts to demonstrate such a simulation
  60. To demonstrate this, the current implementation does the
  61. following:
  62. in resolveExplicit()
  63. - change LRE, LRO, RLE, RLO, PDF to BN
  64. - assign nested levels to BN
  65. in resolveWeak and resolveNeutrals
  66. - assign L and R to BN's where they exist in place of
  67. sor and eor by changing the last BN in front of a
  68. level change to a strong type
  69. - skip over BN's for the purpose of determining actions
  70. - include BN in the count of deferred runs
  71. which will resolve some of them to EN, AN and N
  72. in resolveWhiteSpace
  73. - set the level of any surviving BN to the base level,
  74. or the level of the preceding character
  75. - include LRE,LRO, RLE, RLO, PDF and BN in the count
  76. whitespace to be reset
  77. This will result in the same order for non-BN characters as
  78. if the BN characters had been removed.
  79. The clean() function can be used to remove boundary marks for
  80. verification purposes.
  81. Notation
  82. --------
  83. Pointer variables generally start with the letter p
  84. Counter variables generally start with the letter c
  85. Index variables generally start with the letter i
  86. Boolean variables generally start with the letter f
  87. The enumerated bidirectional types have the same name as in the
  88. description for the Unicode Bidirectional Algorithm
  89. Using this code outside a demo context
  90. --------------------------------------
  91. The way the functions are broken down in this demo code is based
  92. on the needs of the demo to show the evolution in internal state
  93. as the algorithm proceeds. This obscures how the algorithm would
  94. be used in practice. These are the steps:
  95. 1. Allocate a pair of arrays large enough to hold bidi class
  96. and calculated levels (one for each input character)
  97. 2. Provide your own function to assign directional types (bidi
  98. classes) corresponding to each character in the input,
  99. conflating ON, WS, S to N. Unlike the classify function in this
  100. demo, the input would be actual Unicode characters.
  101. 3. Process the first paragraph by calling BidiParagraph. That
  102. function changes B into BN and returns a length including the
  103. paragraph separator. (The iteration over multiple paragraphs
  104. is left as exercise for the reader).
  105. 4. Assign directional types again, but now assign specific types
  106. to whitespace characters.
  107. 5. Instead of reordering the input in place it is often desirable
  108. to calculate an array of offsets indicating the reordering.
  109. To that end, allocate such an array here and use it instead
  110. of the input array in the next step.
  111. 6. Resolve and reorder the lines by calling BidiLines. That
  112. function 'breaks' lines on LS characters. Provide an optional
  113. array of flags indicating the location of other line breaks as
  114. needed.
  115. Update History
  116. --------------
  117. Version 24 is the initial published and verified version of this
  118. reference implementation. Version 25 and its updates fix various
  119. minor issues with the scaffolding used for demonstrating the
  120. algorithm using pseudo-alphabets from the command line or dialog
  121. box. No changes to the implementation of the actual bidi algorithm
  122. are made in any of the minor updates to version 25. Version 26
  123. also makes no change to the actual algorithm but was verified
  124. against the official BidiTest.txt file for Unicode 5.2.0.
  125. - updated pseudo-alphabet
  126. - Last Revised 12-10-99 (25)
  127. - enable demo mode for release builds - no other changes
  128. - Last Revised 12-10-00 (25a)
  129. - fix regression in pseudo alphabet use for Windows UI
  130. - Last Revised 02-01-01 (25b)
  131. - fixed a few comments, renamed a variable
  132. - Last Revised 03-04-01 (25c)
  133. - make base level settable, enable mirror by default,
  134. fix dialog size
  135. - Last Revised 06-02-01 (25e)
  136. - fixed some comments
  137. - Last Revised 09-29-01 (25f)
  138. - fixed classification for LS,RLM,LRM in pseudo alphabet,
  139. focus issues in UI, regression fix to commandline from 25(e)
  140. fix DEMO switch
  141. - Last Revised 11-07-01 (25g)
  142. - fixed classification for plus/minus in pseudo alphabet
  143. to track changes made in Unicode 4.0.1
  144. - Last Revised 12-03-04 (25h)
  145. - now compiles as dialog-only program for WINDOWS_UI==1
  146. using new bidimain.cpp
  147. - Last Revised 12-02-07 (25i)
  148. - cleaned up whitespace and indenting in the source,
  149. fixed two comments (table headers)
  150. - Last Revised 15-03-07 (25j)
  151. - named enumerations
  152. - Last Revised 30-05-07 (25k)
  153. - added usage notes, minor edits to comments, indentation, etc
  154. throughout. Added the bidiParagraph function. Checked against
  155. changes in the Unicode Bidi Algorithm for Unicode 5.2.0. No
  156. changes needed to this implementation to match the values in
  157. the BidiTest.txt file in the Unicode Character Database.
  158. Minor fixes to dialog/windows proc, updated preprocessor directives.
  159. - Last Revised 03-08-09 (26)
  160. Credits:
  161. -------
  162. Written by: Asmus Freytag
  163. Command line interface by: Rick McGowan
  164. Verification (v24): Doug Felt
  165. Disclaimer and legal rights:
  166. ---------------------------
  167. Copyright (C) 1999-2009, ASMUS, Inc. All Rights Reserved.
  168. Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
  169. THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  170. OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  171. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
  172. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
  173. BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
  174. OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
  175. WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
  176. ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE SOFTWARE.
  177. The file bid.rc is included in the software covered by the above.
  178. ------------------------------------------------------------------------*/
  179. /* === HELPER FUNCTIONS AND DECLARATIONS ================================= */
  180. #define odd(x) ((x) & 1)
  181. /*----------------------------------------------------------------------
  182. The following array maps character codes to types for the purpose of
  183. this sample implementation. The legend string gives a human readable
  184. explanation of the pseudo alphabet.
  185. For simplicity, characters entered by buttons are given a 1:1 mapping
  186. between their type and pseudo character value. Pseudo characters that
  187. can be typed from the keyboard are explained in the legend string.
  188. Use the Unicode Character Database for the real values in real use.
  189. ---------------------------------------------------------------------*/
  190. enum
  191. {
  192. chLS = 0x15
  193. };
  194. #if 0
  195. static const fz_bidi_chartype types_from_char[] =
  196. {
  197. // 0 1 2 3 4 5 6 7 8 9 a b c d e f
  198. BDI_BN, BDI_BN, BDI_BN, BDI_BN, BDI_L, BDI_R, BDI_BN, BDI_BN, BDI_BN, BDI_S, BDI_B, BDI_S, BDI_WS, BDI_B, BDI_BN, BDI_BN, /*00-0f*/
  199. BDI_LRO,BDI_LRE,BDI_PDF,BDI_RLO,BDI_RLE,BDI_WS, BDI_L, BDI_R, BDI_BN, BDI_BN, BDI_BN, BDI_BN, BDI_B, BDI_B, BDI_B, BDI_S, /*10-1f*/
  200. BDI_WS, BDI_ON, BDI_ON, BDI_ET, BDI_ET, BDI_ET, BDI_ON, BDI_ON, BDI_ON, BDI_ON, BDI_ON, BDI_ES, BDI_CS, BDI_ES, BDI_CS, BDI_ES, /*20-2f*/
  201. BDI_EN, BDI_EN, BDI_EN, BDI_EN, BDI_EN, BDI_EN, BDI_AN, BDI_AN, BDI_AN, BDI_AN, BDI_CS, BDI_ON, BDI_ON, BDI_ON, BDI_ON, BDI_ON, /*30-3f*/
  202. BDI_ON, BDI_AL, BDI_AL, BDI_AL, BDI_AL, BDI_AL, BDI_AL, BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, /*40-4f*/
  203. BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, BDI_R, BDI_LRE,BDI_ON, BDI_RLE,BDI_PDF,BDI_S, /*50-5f*/
  204. BDI_NSM,BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, /*60-6f*/
  205. BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_L, BDI_LRO,BDI_B, BDI_RLO,BDI_BN, BDI_ON, /*70-7f*/
  206. };
  207. #endif
  208. /***************************************
  209. Reverse, human readable reference:
  210. LRM: 0x4
  211. RLM: 0x5
  212. L: 0x16,a-z
  213. LRE: 0x11,[
  214. LRO: 0x10,{
  215. R: 0x17,G-Z
  216. AL: A-F
  217. RLE: 0x14,]
  218. RLO: 0x13,}
  219. PDF: 0x12,^
  220. EN: 0-5
  221. ES: /,+,[hyphen]
  222. ET: #,$,%
  223. AN: 6-9
  224. CS: [comma],.,:
  225. NSM: `
  226. BN: 0x0-0x8,0xe,0xf,0x18-0x1b,~
  227. B: 0xa,0xd,0x1c-0x1e,|
  228. S: 0x9,0xb,0x1f,_
  229. WS: 0xc,0x15,[space]
  230. ON: !,",&,',(,),*,;,<,=,>,?,@,\,0x7f
  231. ****************************************/
  232. // === HELPER FUNCTIONS ================================================
  233. #ifdef BIDI_LINE_AT_A_TIME
  234. // reverse cch characters
  235. static
  236. void reverse(uint32_t *psz, int cch)
  237. {
  238. uint32_t ch_temp;
  239. int ich;
  240. for (ich = 0; ich < --cch; ich++)
  241. {
  242. ch_temp = psz[ich];
  243. psz[ich] = psz[cch];
  244. psz[cch] = ch_temp;
  245. }
  246. }
  247. #endif
  248. // Set a run of cval values at locations all prior to, but not including
  249. // iStart, to the new value nval.
  250. static
  251. void set_deferred_run(fz_bidi_chartype *pval, size_t cval, size_t iStart, fz_bidi_chartype nval)
  252. {
  253. size_t i;
  254. for (i = iStart; i > iStart - cval; )
  255. {
  256. pval[--i] = nval;
  257. }
  258. }
  259. static
  260. void set_deferred_level_run(fz_bidi_level *pval, size_t cval, size_t iStart, fz_bidi_level nval)
  261. {
  262. size_t i;
  263. for (i = iStart; i > iStart - cval; )
  264. {
  265. pval[--i] = nval;
  266. }
  267. }
  268. // === ASSIGNING BIDI CLASSES ============================================
  269. // === THE PARAGRAPH LEVEL ===============================================
  270. /*------------------------------------------------------------------------
  271. Function: resolve_paragraphs
  272. Resolves the input strings into blocks over which the algorithm
  273. is then applied.
  274. Implements Rule P1 of the Unicode Bidi Algorithm
  275. Input: Text string
  276. Character count
  277. Output: revised character count
  278. Note: This is a very simplistic function. In effect it restricts
  279. the action of the algorithm to the first paragraph in the input
  280. where a paragraph ends at the end of the first block separator
  281. or at the end of the input text.
  282. ------------------------------------------------------------------------*/
  283. size_t fz_bidi_resolve_paragraphs(fz_bidi_chartype *types, size_t cch)
  284. {
  285. size_t ich;
  286. // skip characters not of type B
  287. for(ich = 0; ich < cch && types[ich] != BDI_B; ich++)
  288. ;
  289. // stop after first B, make it a BN for use in the next steps
  290. if (ich < cch && types[ich] == BDI_B)
  291. types[ich++] = BDI_BN;
  292. return ich;
  293. }
  294. #if 0
  295. /*------------------------------------------------------------------------
  296. Function: base_level
  297. Determines the base level
  298. Implements rule P2 of the Unicode Bidi Algorithm.
  299. Input: Array of directional classes
  300. Character count
  301. Note: Ignores explicit embeddings
  302. ------------------------------------------------------------------------*/
  303. static int base_level(const fz_bidi_chartype *pcls, int cch)
  304. {
  305. int ich;
  306. for (ich = 0; ich < cch; ich++)
  307. {
  308. switch (pcls[ich])
  309. {
  310. // strong left
  311. case BDI_L:
  312. return 0;
  313. // strong right
  314. case BDI_R:
  315. case BDI_AL:
  316. return 1;
  317. }
  318. }
  319. return 0;
  320. }
  321. #endif
  322. //====== RESOLVE EXPLICIT ================================================
  323. static fz_bidi_level greater_even(fz_bidi_level i)
  324. {
  325. return odd(i) ? i + 1 : i + 2;
  326. }
  327. static fz_bidi_level greater_odd(fz_bidi_level i)
  328. {
  329. return odd(i) ? i + 2 : i + 1;
  330. }
  331. static fz_bidi_chartype embedding_direction(fz_bidi_chartype level)
  332. {
  333. return odd(level) ? BDI_R : BDI_L;
  334. }
  335. /*------------------------------------------------------------------------
  336. Function: resolveExplicit
  337. Recursively resolves explicit embedding levels and overrides.
  338. Implements rules X1-X9, of the Unicode Bidirectional Algorithm.
  339. Input: Base embedding level and direction
  340. Character count
  341. Output: Array of embedding levels
  342. Caller must allocate (one level per input character)
  343. In/Out: Array of direction classes
  344. Note: The function uses two simple counters to keep track of
  345. matching explicit codes and PDF. Use the default argument for
  346. the outermost call. The nesting counter counts the recursion
  347. depth and not the embedding level.
  348. ------------------------------------------------------------------------*/
  349. size_t fz_bidi_resolve_explicit(fz_bidi_level level, fz_bidi_chartype dir, fz_bidi_chartype *pcls, fz_bidi_level *plevel, size_t cch,
  350. fz_bidi_level n_nest)
  351. {
  352. size_t ich;
  353. // always called with a valid nesting level
  354. // nesting levels are != embedding levels
  355. int nLastValid = n_nest;
  356. // check input values
  357. assert(n_nest >= 0 && level >= 0 && level <= BIDI_LEVEL_MAX);
  358. // process the text
  359. for (ich = 0; ich < cch; ich++)
  360. {
  361. fz_bidi_chartype cls = pcls[ich];
  362. switch (cls)
  363. {
  364. case BDI_LRO:
  365. case BDI_LRE:
  366. n_nest++;
  367. if (greater_even(level) <= BIDI_LEVEL_MAX)
  368. {
  369. plevel[ich] = greater_even(level);
  370. pcls[ich] = BDI_BN;
  371. ich += fz_bidi_resolve_explicit(plevel[ich], (cls == BDI_LRE ? BDI_N : BDI_L),
  372. &pcls[ich+1], &plevel[ich+1],
  373. cch - (ich+1), n_nest);
  374. n_nest--;
  375. continue;
  376. }
  377. cls = pcls[ich] = BDI_BN;
  378. break;
  379. case BDI_RLO:
  380. case BDI_RLE:
  381. n_nest++;
  382. if (greater_odd(level) <= BIDI_LEVEL_MAX)
  383. {
  384. plevel[ich] = greater_odd(level);
  385. pcls[ich] = BDI_BN;
  386. ich += fz_bidi_resolve_explicit(plevel[ich], (cls == BDI_RLE ? BDI_N : BDI_R),
  387. &pcls[ich+1], &plevel[ich+1],
  388. cch - (ich+1), n_nest);
  389. n_nest--;
  390. continue;
  391. }
  392. cls = pcls[ich] = BDI_BN;
  393. break;
  394. case BDI_PDF:
  395. cls = pcls[ich] = BDI_BN;
  396. if (n_nest)
  397. {
  398. if (nLastValid < n_nest)
  399. {
  400. n_nest--;
  401. }
  402. else
  403. {
  404. cch = ich; // break the loop, but complete body
  405. }
  406. }
  407. break;
  408. }
  409. // Apply the override
  410. if (dir != BDI_N)
  411. {
  412. cls = dir;
  413. }
  414. plevel[ich] = level;
  415. if (pcls[ich] != BDI_BN)
  416. pcls[ich] = cls;
  417. }
  418. return ich;
  419. }
  420. // === RESOLVE WEAK TYPES ================================================
  421. enum bidi_state // possible states
  422. {
  423. xa, // arabic letter
  424. xr, // right letter
  425. xl, // left letter
  426. ao, // arabic lett. foll by ON
  427. ro, // right lett. foll by ON
  428. lo, // left lett. foll by ON
  429. rt, // ET following R
  430. lt, // ET following L
  431. cn, // EN, AN following AL
  432. ra, // arabic number foll R
  433. re, // european number foll R
  434. la, // arabic number foll L
  435. le, // european number foll L
  436. ac, // CS following cn
  437. rc, // CS following ra
  438. rs, // CS,ES following re
  439. lc, // CS following la
  440. ls, // CS,ES following le
  441. ret, // ET following re
  442. let // ET following le
  443. } ;
  444. static const unsigned char state_weak[][10] =
  445. {
  446. // N, L, R, AN, EN, AL,NSM, CS, ES, ET,
  447. /*xa*/ { ao, xl, xr, cn, cn, xa, xa, ao, ao, ao }, /* arabic letter */
  448. /*xr*/ { ro, xl, xr, ra, re, xa, xr, ro, ro, rt }, /* right letter */
  449. /*xl*/ { lo, xl, xr, la, le, xa, xl, lo, lo, lt }, /* left letter */
  450. /*ao*/ { ao, xl, xr, cn, cn, xa, ao, ao, ao, ao }, /* arabic lett. foll by ON*/
  451. /*ro*/ { ro, xl, xr, ra, re, xa, ro, ro, ro, rt }, /* right lett. foll by ON */
  452. /*lo*/ { lo, xl, xr, la, le, xa, lo, lo, lo, lt }, /* left lett. foll by ON */
  453. /*rt*/ { ro, xl, xr, ra, re, xa, rt, ro, ro, rt }, /* ET following R */
  454. /*lt*/ { lo, xl, xr, la, le, xa, lt, lo, lo, lt }, /* ET following L */
  455. /*cn*/ { ao, xl, xr, cn, cn, xa, cn, ac, ao, ao }, /* EN, AN following AL */
  456. /*ra*/ { ro, xl, xr, ra, re, xa, ra, rc, ro, rt }, /* arabic number foll R */
  457. /*re*/ { ro, xl, xr, ra, re, xa, re, rs, rs,ret }, /* european number foll R */
  458. /*la*/ { lo, xl, xr, la, le, xa, la, lc, lo, lt }, /* arabic number foll L */
  459. /*le*/ { lo, xl, xr, la, le, xa, le, ls, ls,let }, /* european number foll L */
  460. /*ac*/ { ao, xl, xr, cn, cn, xa, ao, ao, ao, ao }, /* CS following cn */
  461. /*rc*/ { ro, xl, xr, ra, re, xa, ro, ro, ro, rt }, /* CS following ra */
  462. /*rs*/ { ro, xl, xr, ra, re, xa, ro, ro, ro, rt }, /* CS,ES following re */
  463. /*lc*/ { lo, xl, xr, la, le, xa, lo, lo, lo, lt }, /* CS following la */
  464. /*ls*/ { lo, xl, xr, la, le, xa, lo, lo, lo, lt }, /* CS,ES following le */
  465. /*ret*/ { ro, xl, xr, ra, re, xa,ret, ro, ro,ret }, /* ET following re */
  466. /*let*/ { lo, xl, xr, la, le, xa,let, lo, lo,let } /* ET following le */
  467. };
  468. enum bidi_action // possible actions
  469. {
  470. // primitives
  471. IX = 0x100, // increment
  472. XX = 0xF, // no-op
  473. // actions
  474. xxx = (XX << 4) + XX, // no-op
  475. xIx = IX + xxx, // increment run
  476. xxN = (XX << 4) + BDI_ON, // set current to N
  477. xxE = (XX << 4) + BDI_EN, // set current to EN
  478. xxA = (XX << 4) + BDI_AN, // set current to AN
  479. xxR = (XX << 4) + BDI_R, // set current to R
  480. xxL = (XX << 4) + BDI_L, // set current to L
  481. Nxx = (BDI_ON << 4) + 0xF, // set run to neutral
  482. Axx = (BDI_AN << 4) + 0xF, // set run to AN
  483. ExE = (BDI_EN << 4) + BDI_EN, // set run to EN, set current to EN
  484. NIx = (BDI_ON << 4) + 0xF + IX, // set run to N, increment
  485. NxN = (BDI_ON << 4) + BDI_ON, // set run to N, set current to N
  486. NxR = (BDI_ON << 4) + BDI_R, // set run to N, set current to R
  487. NxE = (BDI_ON << 4) + BDI_EN, // set run to N, set current to EN
  488. AxA = (BDI_AN << 4) + BDI_AN, // set run to AN, set current to AN
  489. NxL = (BDI_ON << 4) + BDI_L, // set run to N, set current to L
  490. LxL = (BDI_L << 4) + BDI_L // set run to L, set current to L
  491. };
  492. typedef uint16_t fz_bidi_action;
  493. static const fz_bidi_action action_weak[][10] =
  494. {
  495. // N,.. L, R, AN, EN, AL, NSM, CS,..ES, ET,
  496. /*xa*/ { xxx, xxx, xxx, xxx, xxA, xxR, xxR, xxN, xxN, xxN }, /* arabic letter */
  497. /*xr*/ { xxx, xxx, xxx, xxx, xxE, xxR, xxR, xxN, xxN, xIx }, /* right letter */
  498. /*xl*/ { xxx, xxx, xxx, xxx, xxL, xxR, xxL, xxN, xxN, xIx }, /* left letter */
  499. /*ao*/ { xxx, xxx, xxx, xxx, xxA, xxR, xxN, xxN, xxN, xxN }, /* arabic lett. foll by ON */
  500. /*ro*/ { xxx, xxx, xxx, xxx, xxE, xxR, xxN, xxN, xxN, xIx }, /* right lett. foll by ON */
  501. /*lo*/ { xxx, xxx, xxx, xxx, xxL, xxR, xxN, xxN, xxN, xIx }, /* left lett. foll by ON */
  502. /*rt*/ { Nxx, Nxx, Nxx, Nxx, ExE, NxR, xIx, NxN, NxN, xIx }, /* ET following R */
  503. /*lt*/ { Nxx, Nxx, Nxx, Nxx, LxL, NxR, xIx, NxN, NxN, xIx }, /* ET following L */
  504. /*cn*/ { xxx, xxx, xxx, xxx, xxA, xxR, xxA, xIx, xxN, xxN }, /* EN, AN following AL */
  505. /*ra*/ { xxx, xxx, xxx, xxx, xxE, xxR, xxA, xIx, xxN, xIx }, /* arabic number foll R */
  506. /*re*/ { xxx, xxx, xxx, xxx, xxE, xxR, xxE, xIx, xIx, xxE }, /* european number foll R */
  507. /*la*/ { xxx, xxx, xxx, xxx, xxL, xxR, xxA, xIx, xxN, xIx }, /* arabic number foll L */
  508. /*le*/ { xxx, xxx, xxx, xxx, xxL, xxR, xxL, xIx, xIx, xxL }, /* european number foll L */
  509. /*ac*/ { Nxx, Nxx, Nxx, Axx, AxA, NxR, NxN, NxN, NxN, NxN }, /* CS following cn */
  510. /*rc*/ { Nxx, Nxx, Nxx, Axx, NxE, NxR, NxN, NxN, NxN, NIx }, /* CS following ra */
  511. /*rs*/ { Nxx, Nxx, Nxx, Nxx, ExE, NxR, NxN, NxN, NxN, NIx }, /* CS,ES following re */
  512. /*lc*/ { Nxx, Nxx, Nxx, Axx, NxL, NxR, NxN, NxN, NxN, NIx }, /* CS following la */
  513. /*ls*/ { Nxx, Nxx, Nxx, Nxx, LxL, NxR, NxN, NxN, NxN, NIx }, /* CS,ES following le */
  514. /*ret*/{ xxx, xxx, xxx, xxx, xxE, xxR, xxE, xxN, xxN, xxE }, /* ET following re */
  515. /*let*/{ xxx, xxx, xxx, xxx, xxL, xxR, xxL, xxN, xxN, xxL } /* ET following le */
  516. };
  517. static
  518. fz_bidi_chartype get_deferred_type(fz_bidi_action action)
  519. {
  520. return (action >> 4) & 0xF;
  521. }
  522. static
  523. fz_bidi_chartype get_resolved_type(fz_bidi_action action)
  524. {
  525. return action & 0xF;
  526. }
  527. /* Note on action table:
  528. States can be of two kinds:
  529. - Immediate Resolution State, where each input token
  530. is resolved as soon as it is seen. These states have
  531. only single action codes (xxN) or the no-op (xxx)
  532. for static input tokens.
  533. - Deferred Resolution State, where input tokens either
  534. either extend the run (xIx) or resolve its Type (e.g. Nxx).
  535. Input classes are of three kinds
  536. - Static Input Token, where the class of the token remains
  537. unchanged on output (AN, L, N, R)
  538. - Replaced Input Token, where the class of the token is
  539. always replaced on output (AL, BDI_BN, NSM, CS, ES, ET)
  540. - Conditional Input Token, where the class of the token is
  541. changed on output in some but not all cases (EN)
  542. Where tokens are subject to change, a double action
  543. (e.g. NxA, or NxN) is _required_ after deferred states,
  544. resolving both the deferred state and changing the current token.
  545. These properties of the table are verified by assertions below.
  546. This code is needed only during debugging and maintenance
  547. */
  548. /*------------------------------------------------------------------------
  549. Function: resolveWeak
  550. Resolves the directionality of numeric and other weak character types
  551. Implements rules X10 and W1-W6 of the Unicode Bidirectional Algorithm.
  552. Input: Array of embedding levels
  553. Character count
  554. In/Out: Array of directional classes
  555. Note: On input only these directional classes are expected
  556. AL, HL, R, L, ON, BDI_BN, NSM, AN, EN, ES, ET, CS,
  557. ------------------------------------------------------------------------*/
  558. void fz_bidi_resolve_weak(fz_context *ctx, fz_bidi_level baselevel, fz_bidi_chartype *pcls, fz_bidi_level *plevel, size_t cch)
  559. {
  560. int state = odd(baselevel) ? xr : xl;
  561. fz_bidi_chartype cls;
  562. size_t ich;
  563. fz_bidi_action action;
  564. fz_bidi_chartype cls_run;
  565. fz_bidi_chartype cls_new;
  566. fz_bidi_level level = baselevel;
  567. size_t cch_run = 0;
  568. for (ich = 0; ich < cch; ich++)
  569. {
  570. if (pcls[ich] > BDI_BN) {
  571. fz_warn(ctx, "error: pcls[%zu] > BN (%d)\n", ich, pcls[ich]);
  572. }
  573. // ignore boundary neutrals
  574. if (pcls[ich] == BDI_BN)
  575. {
  576. // must flatten levels unless at a level change;
  577. plevel[ich] = level;
  578. // lookahead for level changes
  579. if (ich + 1 == cch && level != baselevel)
  580. {
  581. // have to fixup last BN before end of the loop, since
  582. // its fix-upped value will be needed below the assert
  583. pcls[ich] = embedding_direction(level);
  584. }
  585. else if (ich + 1 < cch && level != plevel[ich+1] && pcls[ich+1] != BDI_BN)
  586. {
  587. // fixup LAST BN in front / after a level run to make
  588. // it act like the SOR/EOR in rule X10
  589. int newlevel = plevel[ich+1];
  590. if (level > newlevel) {
  591. newlevel = level;
  592. }
  593. plevel[ich] = newlevel;
  594. // must match assigned level
  595. pcls[ich] = embedding_direction(newlevel);
  596. level = plevel[ich+1];
  597. }
  598. else
  599. {
  600. // don't interrupt runs
  601. if (cch_run)
  602. {
  603. cch_run++;
  604. }
  605. continue;
  606. }
  607. }
  608. assert(pcls[ich] <= BDI_BN);
  609. cls = pcls[ich];
  610. action = action_weak[state][cls];
  611. // resolve the directionality for deferred runs
  612. cls_run = get_deferred_type(action);
  613. if (cls_run != XX)
  614. {
  615. set_deferred_run(pcls, cch_run, ich, cls_run);
  616. cch_run = 0;
  617. }
  618. // resolve the directionality class at the current location
  619. cls_new = get_resolved_type(action);
  620. if (cls_new != XX)
  621. pcls[ich] = cls_new;
  622. // increment a deferred run
  623. if (IX & action)
  624. cch_run++;
  625. state = state_weak[state][cls];
  626. }
  627. // resolve any deferred runs
  628. // use the direction of the current level to emulate PDF
  629. cls = embedding_direction(level);
  630. // resolve the directionality for deferred runs
  631. cls_run = get_deferred_type(action_weak[state][cls]);
  632. if (cls_run != XX)
  633. set_deferred_run(pcls, cch_run, ich, cls_run);
  634. }
  635. // === RESOLVE NEUTRAL TYPES ==============================================
  636. // action values
  637. enum neutral_action
  638. {
  639. // action to resolve previous input
  640. nL = BDI_L, // resolve EN to L
  641. En = 3 << 4, // resolve neutrals run to embedding level direction
  642. Rn = BDI_R << 4, // resolve neutrals run to strong right
  643. Ln = BDI_L << 4, // resolved neutrals run to strong left
  644. In = (1<<8), // increment count of deferred neutrals
  645. LnL = (1<<4)+BDI_L // set run and EN to L
  646. };
  647. static fz_bidi_chartype
  648. get_deferred_neutrals(fz_bidi_action action, fz_bidi_level level)
  649. {
  650. action = (action >> 4) & 0xF;
  651. if (action == (En >> 4))
  652. return embedding_direction(level);
  653. else
  654. return action;
  655. }
  656. static fz_bidi_chartype get_resolved_neutrals(fz_bidi_action action)
  657. {
  658. action = action & 0xF;
  659. /* RJW: The original code does:
  660. * if (action == In)
  661. * return 0;
  662. * else
  663. * return action;
  664. * BUT, this can never be true, as In == 256.
  665. * This upsets coverity. We fix this here, but include this note
  666. * so that we understand what changed in case we ever update to
  667. * a newer release of the bidirectional code.
  668. */
  669. return action;
  670. }
  671. // state values
  672. enum neutral_state
  673. {
  674. // new temporary class
  675. r, // R and characters resolved to R
  676. l, // L and characters resolved to L
  677. rn, // N preceded by right
  678. ln, // N preceded by left
  679. a, // AN preceded by left (the abbrev 'la' is used up above)
  680. na // N preceded by a
  681. } ;
  682. /*------------------------------------------------------------------------
  683. Notes:
  684. By rule W7, whenever a EN is 'dominated' by an L (including start of
  685. run with embedding direction = L) it is resolved to, and further treated
  686. as L.
  687. This leads to the need for 'a' and 'na' states.
  688. ------------------------------------------------------------------------*/
  689. static const int action_neutrals[][5] =
  690. {
  691. // N, L, R, AN, EN, = cls
  692. // state =
  693. {In, 0, 0, 0, 0}, // r right
  694. {In, 0, 0, 0, BDI_L}, // l left
  695. {In, En, Rn, Rn, Rn}, // rn N preceded by right
  696. {In, Ln, En, En, LnL}, // ln N preceded by left
  697. {In, 0, 0, 0, BDI_L}, // a AN preceded by left
  698. {In, En, Rn, Rn, En} // na N preceded by a
  699. } ;
  700. static const int state_neutrals[][5] =
  701. {
  702. // N, L, R, AN, EN = cls
  703. // state =
  704. {rn, l, r, r, r}, // r right
  705. {ln, l, r, a, l}, // l left
  706. {rn, l, r, r, r}, // rn N preceded by right
  707. {ln, l, r, a, l}, // ln N preceded by left
  708. {na, l, r, a, l}, // a AN preceded by left
  709. {na, l, r, a, l} // na N preceded by la
  710. } ;
  711. /*------------------------------------------------------------------------
  712. Function: resolveNeutrals
  713. Resolves the directionality of neutral character types.
  714. Implements rules W7, N1 and N2 of the Unicode Bidi Algorithm.
  715. Input: Array of embedding levels
  716. Character count
  717. Baselevel
  718. In/Out: Array of directional classes
  719. Note: On input only these directional classes are expected
  720. R, L, N, AN, EN and BN
  721. W8 resolves a number of ENs to L
  722. ------------------------------------------------------------------------*/
  723. void fz_bidi_resolve_neutrals(fz_bidi_level baselevel, fz_bidi_chartype *pcls, const fz_bidi_level *plevel, size_t cch)
  724. {
  725. // the state at the start of text depends on the base level
  726. int state = odd(baselevel) ? r : l;
  727. fz_bidi_chartype cls;
  728. size_t ich;
  729. fz_bidi_chartype cls_run;
  730. size_t cch_run = 0;
  731. fz_bidi_level level = baselevel;
  732. for (ich = 0; ich < cch; ich++)
  733. {
  734. int action;
  735. fz_bidi_chartype cls_new;
  736. // ignore boundary neutrals
  737. if (pcls[ich] == BDI_BN)
  738. {
  739. // include in the count for a deferred run
  740. if (cch_run)
  741. cch_run++;
  742. // skip any further processing
  743. continue;
  744. }
  745. assert(pcls[ich] < 5); // "Only N, L, R, AN, EN are allowed"
  746. cls = pcls[ich];
  747. action = action_neutrals[state][cls];
  748. // resolve the directionality for deferred runs
  749. cls_run = get_deferred_neutrals(action, level);
  750. if (cls_run != BDI_N)
  751. {
  752. set_deferred_run(pcls, cch_run, ich, cls_run);
  753. cch_run = 0;
  754. }
  755. // resolve the directionality class at the current location
  756. cls_new = get_resolved_neutrals(action);
  757. if (cls_new != BDI_N)
  758. pcls[ich] = cls_new;
  759. if (In & action)
  760. cch_run++;
  761. state = state_neutrals[state][cls];
  762. level = plevel[ich];
  763. }
  764. // resolve any deferred runs
  765. cls = embedding_direction(level); // eor has type of current level
  766. // resolve the directionality for deferred runs
  767. cls_run = get_deferred_neutrals(action_neutrals[state][cls], level);
  768. if (cls_run != BDI_N)
  769. set_deferred_run(pcls, cch_run, ich, cls_run);
  770. }
  771. // === RESOLVE IMPLICITLY =================================================
  772. /*------------------------------------------------------------------------
  773. Function: resolveImplicit
  774. Recursively resolves implicit embedding levels.
  775. Implements rules I1 and I2 of the Unicode Bidirectional Algorithm.
  776. Input: Array of direction classes
  777. Character count
  778. Base level
  779. In/Out: Array of embedding levels
  780. Note: levels may exceed 15 on output.
  781. Accepted subset of direction classes
  782. R, L, AN, EN
  783. ------------------------------------------------------------------------*/
  784. static const fz_bidi_level add_level[][4] =
  785. {
  786. // L, R, AN, EN = cls
  787. // level =
  788. /* even */ { 0, 1, 2, 2 }, // EVEN
  789. /* odd */ { 1, 0, 1, 1 } // ODD
  790. };
  791. void fz_bidi_resolve_implicit(const fz_bidi_chartype *pcls, fz_bidi_level *plevel, size_t cch)
  792. {
  793. size_t ich;
  794. for (ich = 0; ich < cch; ich++)
  795. {
  796. // cannot resolve bn here, since some bn were resolved to strong
  797. // types in resolveWeak. To remove these we need the original
  798. // types, which are available again in resolveWhiteSpace
  799. if (pcls[ich] == BDI_BN)
  800. {
  801. continue;
  802. }
  803. assert(pcls[ich] > 0); // "No Neutrals allowed to survive here."
  804. assert(pcls[ich] < 5); // "Out of range."
  805. plevel[ich] += add_level[odd(plevel[ich])][pcls[ich] - 1];
  806. }
  807. }
  808. #if 0
  809. // === REORDER ===========================================================
  810. /*------------------------------------------------------------------------
  811. Function: resolve_lines
  812. Breaks a paragraph into lines
  813. Input: Character count
  814. Array of line break flags
  815. In/Out: Array of characters
  816. Returns the count of characters on the first line
  817. Note: This function only breaks lines at hard line breaks. Other
  818. line breaks can be passed in. If pbrk[n] is true, then a break
  819. occurs after the character in psz_input[n]. Breaks before the first
  820. character are not allowed.
  821. ------------------------------------------------------------------------*/
  822. static int resolve_lines(uint32_t *psz_input, int *pbrk, int cch)
  823. {
  824. int ich;
  825. // skip characters not of type LS
  826. for(ich = 0; ich < cch; ich++)
  827. {
  828. if (psz_input[ich] == chLS || (pbrk && pbrk[ich]))
  829. {
  830. ich++;
  831. break;
  832. }
  833. }
  834. return ich;
  835. }
  836. #endif
  837. /*------------------------------------------------------------------------
  838. Function: fz_bidi_resolve_whitespace
  839. Resolves levels for WS and S
  840. Implements rule L1 of the Unicode bidi Algorithm.
  841. Input: Base embedding level
  842. Character count
  843. Array of direction classes (for one line of text)
  844. In/Out: Array of embedding levels (for one line of text)
  845. Note: this should be applied a line at a time. The default driver
  846. code supplied in this file assumes a single line of text; for
  847. a real implementation, cch and the initial pointer values
  848. would have to be adjusted.
  849. ------------------------------------------------------------------------*/
  850. void fz_bidi_resolve_whitespace(fz_bidi_level baselevel, const fz_bidi_chartype *pcls, fz_bidi_level *plevel,
  851. size_t cch)
  852. {
  853. size_t cchrun = 0;
  854. fz_bidi_level oldlevel = baselevel;
  855. size_t ich;
  856. for (ich = 0; ich < cch; ich++)
  857. {
  858. switch(pcls[ich])
  859. {
  860. default:
  861. cchrun = 0; // any other character breaks the run
  862. break;
  863. case BDI_WS:
  864. cchrun++;
  865. break;
  866. case BDI_RLE:
  867. case BDI_LRE:
  868. case BDI_LRO:
  869. case BDI_RLO:
  870. case BDI_PDF:
  871. case BDI_BN:
  872. plevel[ich] = oldlevel;
  873. cchrun++;
  874. break;
  875. case BDI_S:
  876. case BDI_B:
  877. // reset levels for WS before eot
  878. set_deferred_level_run(plevel, cchrun, ich, baselevel);
  879. cchrun = 0;
  880. plevel[ich] = baselevel;
  881. break;
  882. }
  883. oldlevel = plevel[ich];
  884. }
  885. // reset level before eot
  886. set_deferred_level_run(plevel, cchrun, ich, baselevel);
  887. }
  888. #ifdef BIDI_LINE_AT_A_TIME
  889. /*------------------------------------------------------------------------
  890. Functions: reorder/reorderLevel
  891. Recursively reorders the display string
  892. "From the highest level down, reverse all characters at that level and
  893. higher, down to the lowest odd level"
  894. Implements rule L2 of the Unicode bidi Algorithm.
  895. Input: Array of embedding levels
  896. Character count
  897. Flag enabling reversal (set to false by initial caller)
  898. In/Out: Text to reorder
  899. Note: levels may exceed 15 resp. 61 on input.
  900. Rule L3 - reorder combining marks is not implemented here
  901. Rule L4 - glyph mirroring is implemented as a display option below
  902. Note: this should be applied a line at a time
  903. -------------------------------------------------------------------------*/
  904. static int reorderLevel(fz_bidi_level level, uint32_t *psz_text, const fz_bidi_level *plevel, int cch,
  905. int f_reverse)
  906. {
  907. int ich;
  908. // true as soon as first odd level encountered
  909. f_reverse = f_reverse || odd(level);
  910. for (ich = 0; ich < cch; ich++)
  911. {
  912. if (plevel[ich] < level)
  913. {
  914. break;
  915. }
  916. else if (plevel[ich] > level)
  917. {
  918. ich += reorderLevel(level + 1, psz_text + ich, plevel + ich,
  919. cch - ich, f_reverse) - 1;
  920. }
  921. }
  922. if (f_reverse)
  923. {
  924. reverse(psz_text, ich);
  925. }
  926. return ich;
  927. }
  928. int Bidi_reorder(fz_bidi_level baselevel, uint32_t *psz_text, const fz_bidi_level *plevel, int cch)
  929. {
  930. int ich = 0;
  931. while (ich < cch)
  932. {
  933. ich += reorderLevel(baselevel, psz_text + ich, plevel + ich,
  934. cch - ich, FALSE);
  935. }
  936. return ich;
  937. }
  938. #endif