algorithm.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. # This file is part of python-bidi
  2. #
  3. # python-bidi is free software: you can redistribute it and/or modify
  4. # it under the terms of the GNU Lesser General Public License as published by
  5. # the Free Software Foundation, either version 3 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU Lesser General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU Lesser General Public License
  14. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. # Copyright (C) 2008-2010 Yaacov Zamir <kzamir_a_walla.co.il>,
  16. # Copyright (C) 2010-2015 Meir kriheli <mkriheli@gmail.com>.
  17. "bidirectional algorithm implementation"
  18. import inspect
  19. import sys
  20. from collections import deque
  21. from typing import Optional, Union
  22. from unicodedata import bidirectional, mirrored
  23. from .mirror import MIRRORED
  24. StrOrBytes = Union[str, bytes]
  25. # Some definitions
  26. PARAGRAPH_LEVELS = {"L": 0, "AL": 1, "R": 1}
  27. EXPLICIT_LEVEL_LIMIT = 62
  28. def _LEAST_GREATER_ODD(x):
  29. return (x + 1) | 1
  30. def _LEAST_GREATER_EVEN(x):
  31. return (x + 2) & ~1
  32. X2_X5_MAPPINGS = {
  33. "RLE": (_LEAST_GREATER_ODD, "N"),
  34. "LRE": (_LEAST_GREATER_EVEN, "N"),
  35. "RLO": (_LEAST_GREATER_ODD, "R"),
  36. "LRO": (_LEAST_GREATER_EVEN, "L"),
  37. }
  38. # Added 'B' so X6 won't execute in that case and X8 will run it's course
  39. X6_IGNORED = list(X2_X5_MAPPINGS.keys()) + ["BN", "PDF", "B"]
  40. X9_REMOVED = list(X2_X5_MAPPINGS.keys()) + ["BN", "PDF"]
  41. def _embedding_direction(x):
  42. return ("L", "R")[x % 2]
  43. _IS_UCS2 = sys.maxunicode == 65535
  44. _SURROGATE_MIN, _SURROGATE_MAX = 55296, 56319 # D800, DBFF
  45. def debug_storage(storage, base_info=False, chars=True, runs=False):
  46. "Display debug information for the storage"
  47. stderr = sys.stderr
  48. caller = inspect.stack()[1][3]
  49. stderr.write(f"in {caller}\n")
  50. if base_info:
  51. stderr.write(" base level : %d\n" % storage["base_level"])
  52. stderr.write(" base dir : {}\n".format(storage["base_dir"]))
  53. if runs:
  54. stderr.write(" runs : {}\n".format(list(storage["runs"])))
  55. if chars:
  56. output = " Chars : "
  57. for _ch in storage["chars"]:
  58. if _ch != "\n":
  59. output += _ch["ch"]
  60. else:
  61. output += "C"
  62. stderr.write(output + "\n")
  63. output = " Res. levels : {}\n".format("".join(
  64. [str(_ch["level"]) for _ch in storage["chars"]]
  65. ))
  66. stderr.write(output)
  67. _types = [_ch["type"].ljust(3) for _ch in storage["chars"]]
  68. for i in range(3):
  69. output = " %s\n" if i else " Res. types : %s\n"
  70. stderr.write(output % "".join([_t[i] for _t in _types]))
  71. def get_base_level(text, upper_is_rtl=False) -> int:
  72. """Get the paragraph base embedding level. Returns 0 for LTR,
  73. 1 for RTL.
  74. `text` a unicode object.
  75. Set `upper_is_rtl` to True to treat upper case chars as strong 'R'
  76. for debugging (default: False).
  77. """
  78. base_level = None
  79. prev_surrogate = False
  80. # P2
  81. for _ch in text:
  82. # surrogate in case of ucs2
  83. if _IS_UCS2 and (_SURROGATE_MIN <= ord(_ch) <= _SURROGATE_MAX):
  84. prev_surrogate = _ch
  85. continue
  86. elif prev_surrogate:
  87. _ch = prev_surrogate + _ch
  88. prev_surrogate = False
  89. # treat upper as RTL ?
  90. if upper_is_rtl and _ch.isupper():
  91. base_level = 1
  92. break
  93. bidi_type = bidirectional(_ch)
  94. if bidi_type in ("AL", "R"):
  95. base_level = 1
  96. break
  97. elif bidi_type == "L":
  98. base_level = 0
  99. break
  100. # P3
  101. if base_level is None:
  102. base_level = 0
  103. return base_level
  104. def get_embedding_levels(text, storage, upper_is_rtl=False, debug=False):
  105. """Get the paragraph base embedding level and direction,
  106. set the storage to the array of chars"""
  107. prev_surrogate = False
  108. base_level = storage["base_level"]
  109. # preset the storage's chars
  110. for _ch in text:
  111. if _IS_UCS2 and (_SURROGATE_MIN <= ord(_ch) <= _SURROGATE_MAX):
  112. prev_surrogate = _ch
  113. continue
  114. elif prev_surrogate:
  115. _ch = prev_surrogate + _ch
  116. prev_surrogate = False
  117. bidi_type = "R" if upper_is_rtl and _ch.isupper() else bidirectional(_ch)
  118. storage["chars"].append(
  119. {"ch": _ch, "level": base_level, "type": bidi_type, "orig": bidi_type}
  120. )
  121. if debug:
  122. debug_storage(storage, base_info=True)
  123. def explicit_embed_and_overrides(storage, debug=False):
  124. """Apply X1 to X9 rules of the unicode algorithm.
  125. See http://unicode.org/reports/tr9/#Explicit_Levels_and_Directions
  126. """
  127. overflow_counter = almost_overflow_counter = 0
  128. directional_override = "N"
  129. levels = deque()
  130. # X1
  131. embedding_level = storage["base_level"]
  132. for _ch in storage["chars"]:
  133. bidi_type = _ch["type"]
  134. level_func, override = X2_X5_MAPPINGS.get(bidi_type, (None, None))
  135. if level_func:
  136. # So this is X2 to X5
  137. # if we've past EXPLICIT_LEVEL_LIMIT, note it and do nothing
  138. if overflow_counter != 0:
  139. overflow_counter += 1
  140. continue
  141. new_level = level_func(embedding_level)
  142. if new_level < EXPLICIT_LEVEL_LIMIT:
  143. levels.append((embedding_level, directional_override))
  144. embedding_level, directional_override = new_level, override
  145. elif embedding_level == EXPLICIT_LEVEL_LIMIT - 2:
  146. # The new level is invalid, but a valid level can still be
  147. # achieved if this level is 60 and we encounter an RLE or
  148. # RLO further on. So record that we 'almost' overflowed.
  149. almost_overflow_counter += 1
  150. else:
  151. overflow_counter += 1
  152. else:
  153. # X6
  154. if bidi_type not in X6_IGNORED:
  155. _ch["level"] = embedding_level
  156. if directional_override != "N":
  157. _ch["type"] = directional_override
  158. # X7
  159. elif bidi_type == "PDF":
  160. if overflow_counter:
  161. overflow_counter -= 1
  162. elif (
  163. almost_overflow_counter
  164. and embedding_level != EXPLICIT_LEVEL_LIMIT - 1
  165. ):
  166. almost_overflow_counter -= 1
  167. elif levels:
  168. embedding_level, directional_override = levels.pop()
  169. # X8
  170. elif bidi_type == "B":
  171. levels.clear()
  172. overflow_counter = almost_overflow_counter = 0
  173. embedding_level = _ch["level"] = storage["base_level"]
  174. directional_override = "N"
  175. # Removes the explicit embeds and overrides of types
  176. # RLE, LRE, RLO, LRO, PDF, and BN. Adjusts extended chars
  177. # next and prev as well
  178. # Applies X9. See http://unicode.org/reports/tr9/#X9
  179. storage["chars"] = [
  180. _ch for _ch in storage["chars"] if _ch["type"] not in X9_REMOVED
  181. ]
  182. calc_level_runs(storage)
  183. if debug:
  184. debug_storage(storage, runs=True)
  185. def calc_level_runs(storage):
  186. """Split the storage to run of char types at the same level.
  187. Applies X10. See http://unicode.org/reports/tr9/#X10
  188. """
  189. # run level depends on the higher of the two levels on either side of
  190. # the boundary If the higher level is odd, the type is R; otherwise,
  191. # it is L
  192. storage["runs"].clear()
  193. chars = storage["chars"]
  194. # empty string ?
  195. if not chars:
  196. return
  197. def calc_level_run(b_l, b_r):
  198. return ["L", "R"][max(b_l, b_r) % 2]
  199. first_char = chars[0]
  200. sor = calc_level_run(storage["base_level"], first_char["level"])
  201. eor = None
  202. run_start = run_length = 0
  203. curr_level, curr_type = 0, ""
  204. prev_level, prev_type = first_char["level"], first_char["type"]
  205. for _ch in chars:
  206. curr_level, curr_type = _ch["level"], _ch["type"]
  207. if curr_level == prev_level:
  208. run_length += 1
  209. else:
  210. eor = calc_level_run(prev_level, curr_level)
  211. storage["runs"].append(
  212. {
  213. "sor": sor,
  214. "eor": eor,
  215. "start": run_start,
  216. "type": prev_type,
  217. "length": run_length,
  218. }
  219. )
  220. sor = eor
  221. run_start += run_length
  222. run_length = 1
  223. prev_level, prev_type = curr_level, curr_type
  224. # for the last char/runlevel
  225. eor = calc_level_run(curr_level, storage["base_level"])
  226. storage["runs"].append(
  227. {
  228. "sor": sor,
  229. "eor": eor,
  230. "start": run_start,
  231. "type": curr_type,
  232. "length": run_length,
  233. }
  234. )
  235. def resolve_weak_types(storage, debug=False):
  236. """Resolve weak type rules W1 - W3.
  237. See: http://unicode.org/reports/tr9/#Resolving_Weak_Types
  238. """
  239. for run in storage["runs"]:
  240. prev_strong = prev_type = run["sor"]
  241. start, length = run["start"], run["length"]
  242. chars = storage["chars"][start : start + length]
  243. for _ch in chars:
  244. # W1. Examine each nonspacing mark (NSM) in the level run, and
  245. # change the type of the NSM to the type of the previous character.
  246. # If the NSM is at the start of the level run, it will get the type
  247. # of sor.
  248. bidi_type = _ch["type"]
  249. if bidi_type == "NSM":
  250. _ch["type"] = bidi_type = prev_type
  251. # W2. Search backward from each instance of a European number until
  252. # the first strong type (R, L, AL, or sor) is found. If an AL is
  253. # found, change the type of the European number to Arabic number.
  254. if bidi_type == "EN" and prev_strong == "AL":
  255. _ch["type"] = "AN"
  256. # update prev_strong if needed
  257. if bidi_type in ("R", "L", "AL"):
  258. prev_strong = bidi_type
  259. prev_type = _ch["type"]
  260. # W3. Change all ALs to R
  261. for _ch in chars:
  262. if _ch["type"] == "AL":
  263. _ch["type"] = "R"
  264. # W4. A single European separator between two European numbers changes
  265. # to a European number. A single common separator between two numbers of
  266. # the same type changes to that type.
  267. for idx in range(1, len(chars) - 1):
  268. bidi_type = chars[idx]["type"]
  269. prev_type = chars[idx - 1]["type"]
  270. next_type = chars[idx + 1]["type"]
  271. if bidi_type == "ES" and (prev_type == next_type == "EN"):
  272. chars[idx]["type"] = "EN"
  273. if (
  274. bidi_type == "CS"
  275. and prev_type == next_type
  276. and prev_type in ("AN", "EN")
  277. ):
  278. chars[idx]["type"] = prev_type
  279. # W5. A sequence of European terminators adjacent to European numbers
  280. # changes to all European numbers.
  281. for idx in range(len(chars)):
  282. if chars[idx]["type"] == "EN":
  283. for et_idx in range(idx - 1, -1, -1):
  284. if chars[et_idx]["type"] == "ET":
  285. chars[et_idx]["type"] = "EN"
  286. else:
  287. break
  288. for et_idx in range(idx + 1, len(chars)):
  289. if chars[et_idx]["type"] == "ET":
  290. chars[et_idx]["type"] = "EN"
  291. else:
  292. break
  293. # W6. Otherwise, separators and terminators change to Other Neutral.
  294. for _ch in chars:
  295. if _ch["type"] in ("ET", "ES", "CS"):
  296. _ch["type"] = "ON"
  297. # W7. Search backward from each instance of a European number until the
  298. # first strong type (R, L, or sor) is found. If an L is found, then
  299. # change the type of the European number to L.
  300. prev_strong = run["sor"]
  301. for _ch in chars:
  302. if _ch["type"] == "EN" and prev_strong == "L":
  303. _ch["type"] = "L"
  304. if _ch["type"] in ("L", "R"):
  305. prev_strong = _ch["type"]
  306. if debug:
  307. debug_storage(storage, runs=True)
  308. def resolve_neutral_types(storage, debug):
  309. """Resolving neutral types. Implements N1 and N2
  310. See: http://unicode.org/reports/tr9/#Resolving_Neutral_Types
  311. """
  312. prev_bidi_type = ""
  313. for run in storage["runs"]:
  314. start, length = run["start"], run["length"]
  315. # use sor and eor
  316. chars = (
  317. [{"type": run["sor"]}]
  318. + storage["chars"][start : start + length]
  319. + [{"type": run["eor"]}]
  320. )
  321. total_chars = len(chars)
  322. seq_start = None
  323. for idx in range(total_chars):
  324. _ch = chars[idx]
  325. if _ch["type"] in ("B", "S", "WS", "ON"):
  326. # N1. A sequence of neutrals takes the direction of the
  327. # surrounding strong text if the text on both sides has the same
  328. # direction. European and Arabic numbers act as if they were R
  329. # in terms of their influence on neutrals. Start-of-level-run
  330. # (sor) and end-of-level-run (eor) are used at level run
  331. # boundaries.
  332. if seq_start is None:
  333. seq_start = idx
  334. prev_bidi_type = chars[idx - 1]["type"]
  335. else:
  336. if seq_start is not None:
  337. next_bidi_type = chars[idx]["type"]
  338. if prev_bidi_type in ("AN", "EN"):
  339. prev_bidi_type = "R"
  340. if next_bidi_type in ("AN", "EN"):
  341. next_bidi_type = "R"
  342. for seq_idx in range(seq_start, idx):
  343. if prev_bidi_type == next_bidi_type:
  344. chars[seq_idx]["type"] = prev_bidi_type
  345. else:
  346. # N2. Any remaining neutrals take the embedding
  347. # direction. The embedding direction for the given
  348. # neutral character is derived from its embedding
  349. # level: L if the character is set to an even level,
  350. # and R if the level is odd.
  351. chars[seq_idx]["type"] = _embedding_direction(
  352. chars[seq_idx]["level"]
  353. )
  354. seq_start = None
  355. if debug:
  356. debug_storage(storage)
  357. def resolve_implicit_levels(storage, debug):
  358. """Resolving implicit levels (I1, I2)
  359. See: http://unicode.org/reports/tr9/#Resolving_Implicit_Levels
  360. """
  361. for run in storage["runs"]:
  362. start, length = run["start"], run["length"]
  363. chars = storage["chars"][start : start + length]
  364. for _ch in chars:
  365. # only those types are allowed at this stage
  366. assert _ch["type"] in ("L", "R", "EN", "AN"), (
  367. "{} not allowed here".format(_ch["type"])
  368. )
  369. if _embedding_direction(_ch["level"]) == "L":
  370. # I1. For all characters with an even (left-to-right) embedding
  371. # direction, those of type R go up one level and those of type
  372. # AN or EN go up two levels.
  373. if _ch["type"] == "R":
  374. _ch["level"] += 1
  375. elif _ch["type"] != "L":
  376. _ch["level"] += 2
  377. else:
  378. # I2. For all characters with an odd (right-to-left) embedding
  379. # direction, those of type L, EN or AN go up one level.
  380. if _ch["type"] != "R":
  381. _ch["level"] += 1
  382. if debug:
  383. debug_storage(storage, runs=True)
  384. def reverse_contiguous_sequence(
  385. chars, line_start, line_end, highest_level, lowest_odd_level
  386. ):
  387. """L2. From the highest level found in the text to the lowest odd
  388. level on each line, including intermediate levels not actually
  389. present in the text, reverse any contiguous sequence of characters
  390. that are at that level or higher.
  391. """
  392. for level in range(highest_level, lowest_odd_level - 1, -1):
  393. _start = _end = None
  394. for run_idx in range(line_start, line_end + 1):
  395. run_ch = chars[run_idx]
  396. if run_ch["level"] >= level:
  397. if _start is None:
  398. _start = _end = run_idx
  399. else:
  400. _end = run_idx
  401. else:
  402. if _end is not None:
  403. chars[_start : +_end + 1] = reversed(chars[_start : +_end + 1])
  404. _start = _end = None
  405. # anything remaining ?
  406. if _start is not None and _end is not None:
  407. chars[_start : +_end + 1] = reversed(chars[_start : +_end + 1])
  408. def reorder_resolved_levels(storage, debug):
  409. """L1 and L2 rules"""
  410. # Applies L1.
  411. should_reset = True
  412. chars = storage["chars"]
  413. for _ch in chars[::-1]:
  414. # L1. On each line, reset the embedding level of the following
  415. # characters to the paragraph embedding level:
  416. if _ch["orig"] in ("B", "S"):
  417. # 1. Segment separators,
  418. # 2. Paragraph separators,
  419. _ch["level"] = storage["base_level"]
  420. should_reset = True
  421. elif should_reset and _ch["orig"] in ("BN", "WS"):
  422. # 3. Any sequence of whitespace characters preceding a segment
  423. # separator or paragraph separator
  424. # 4. Any sequence of white space characters at the end of the
  425. # line.
  426. _ch["level"] = storage["base_level"]
  427. else:
  428. should_reset = False
  429. max_len = len(chars)
  430. # L2 should be per line
  431. # Calculates highest level and lowest odd level on the fly.
  432. line_start = line_end = 0
  433. highest_level = 0
  434. lowest_odd_level = EXPLICIT_LEVEL_LIMIT
  435. for idx in range(max_len):
  436. _ch = chars[idx]
  437. # calc the levels
  438. char_level = _ch["level"]
  439. if char_level > highest_level:
  440. highest_level = char_level
  441. if char_level % 2 and char_level < lowest_odd_level:
  442. lowest_odd_level = char_level
  443. if _ch["orig"] == "B" or idx == max_len - 1:
  444. line_end = idx
  445. # omit line breaks
  446. if _ch["orig"] == "B":
  447. line_end -= 1
  448. reverse_contiguous_sequence(
  449. chars, line_start, line_end, highest_level, lowest_odd_level
  450. )
  451. # reset for next line run
  452. line_start = idx + 1
  453. highest_level = 0
  454. lowest_odd_level = EXPLICIT_LEVEL_LIMIT
  455. if debug:
  456. debug_storage(storage)
  457. def apply_mirroring(storage, debug):
  458. """Applies L4: mirroring
  459. See: http://unicode.org/reports/tr9/#L4
  460. """
  461. # L4. A character is depicted by a mirrored glyph if and only if (a) the
  462. # resolved directionality of that character is R, and (b) the
  463. # Bidi_Mirrored property value of that character is true.
  464. for _ch in storage["chars"]:
  465. unichar = _ch["ch"]
  466. if mirrored(unichar) and _embedding_direction(_ch["level"]) == "R":
  467. _ch["ch"] = MIRRORED.get(unichar, unichar)
  468. if debug:
  469. debug_storage(storage)
  470. def get_empty_storage():
  471. """Return an empty storage skeleton, usable for testing"""
  472. return {
  473. "base_level": None,
  474. "base_dir": None,
  475. "chars": [],
  476. "runs": deque(),
  477. }
  478. def get_display(
  479. str_or_bytes: StrOrBytes,
  480. encoding: str = "utf-8",
  481. upper_is_rtl: bool = False,
  482. base_dir: Optional[str] = None,
  483. debug: bool = False,
  484. ) -> StrOrBytes:
  485. """Accepts `str` or `bytes`. In case it's `bytes`, `encoding`
  486. is needed as the algorithm works on `str` (default:"utf-8").
  487. Set `upper_is_rtl` to True to treat upper case chars as strong 'R'
  488. for debugging (default: False).
  489. Set `base_dir` to 'L' or 'R' to override the calculated base_level.
  490. Set `debug` to True to display (using sys.stderr) the steps taken with the
  491. algorithm.
  492. Returns the display layout, either as unicode or `encoding` encoded
  493. string.
  494. """
  495. storage = get_empty_storage()
  496. # utf-8 ? we need unicode
  497. if isinstance(str_or_bytes, bytes):
  498. text = str_or_bytes.decode(encoding)
  499. was_decoded = True
  500. else:
  501. text = str_or_bytes
  502. was_decoded = False
  503. if base_dir is None:
  504. base_level = get_base_level(text, upper_is_rtl)
  505. else:
  506. base_level = PARAGRAPH_LEVELS[base_dir]
  507. storage["base_level"] = base_level
  508. storage["base_dir"] = ("L", "R")[base_level]
  509. get_embedding_levels(text, storage, upper_is_rtl, debug)
  510. explicit_embed_and_overrides(storage, debug)
  511. resolve_weak_types(storage, debug)
  512. resolve_neutral_types(storage, debug)
  513. resolve_implicit_levels(storage, debug)
  514. reorder_resolved_levels(storage, debug)
  515. apply_mirroring(storage, debug)
  516. chars = storage["chars"]
  517. display = "".join([_ch["ch"] for _ch in chars])
  518. if was_decoded:
  519. display = display.encode(encoding)
  520. return display