-
-
Notifications
You must be signed in to change notification settings - Fork 799
Add ICU word segmentation backend for browse mode word navigation #20379
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
LeonarddeR
wants to merge
14
commits into
nvaccess:master
Choose a base branch
from
LeonarddeR:icu-word
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+599
−43
Open
Changes from 7 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
fca75b7
Add ICU word segmentation backend
LeonarddeR 4ab9acc
Add emoji test
LeonarddeR 6369257
Simplification
LeonarddeR 0392c08
Fix copyright
LeonarddeR fc2173c
Cleanup
LeonarddeR c398a1a
Update changes
LeonarddeR 2c43e83
Fix user guide
LeonarddeR 939d489
Copilot review actions
LeonarddeR f8952d8
Merge remote-tracking branch 'origin/master' into icu-word
LeonarddeR 98a1f38
Apply suggestions from code review
LeonarddeR 86d4bca
Review actions
LeonarddeR 75c068e
Fix user guide
LeonarddeR f4612ba
Merge remote-tracking branch 'origin/master' into icu-word
LeonarddeR cd06242
Fix system tests
LeonarddeR File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -1,7 +1,7 @@ | ||||||
| # A part of NonVisual Desktop Access (NVDA) | ||||||
| # Copyright (C) 2022-2026 NV Access Limited, Bill Dengler, Rob Meredith, Leonard de Ruijter, Wang Chong | ||||||
| # This file is covered by the GNU General Public License. | ||||||
| # See the file COPYING for more details. | ||||||
| # This file may be used under the terms of the GNU General Public License, version 2 or later, as modified by the NVDA license. | ||||||
| # For full terms and any additional permissions, see the NVDA license file: https://github.com/nvaccess/nvda/blob/master/copying.txt | ||||||
|
|
||||||
| """ | ||||||
| Feature flag value enumerations. | ||||||
|
|
@@ -146,16 +146,19 @@ class WordNavigationUnitFlag(DisplayStringEnum): | |||||
| AUTO = enum.auto() | ||||||
| UNISCRIBE = enum.auto() | ||||||
| CHINESE = enum.auto() | ||||||
| ICU = enum.auto() | ||||||
|
|
||||||
| @property | ||||||
| def _displayStringLabels(self) -> dict["WordNavigationUnitFlag", str]: | ||||||
| return { | ||||||
| # Translators: Label for a method of word segmentation. | ||||||
| self.AUTO: _("Auto"), | ||||||
|
LeonarddeR marked this conversation as resolved.
Outdated
|
||||||
| # Translators: Label for a method of word segmentation. | ||||||
| self.UNISCRIBE: _("Standard"), | ||||||
| self.UNISCRIBE: _("Windows (legacy)"), | ||||||
|
LeonarddeR marked this conversation as resolved.
Outdated
|
||||||
| # Translators: Label for a method of word segmentation. | ||||||
| self.CHINESE: _("Chinese"), | ||||||
| # Translators: Label for a method of word segmentation. | ||||||
| self.ICU: _("Windows Unicode (ICU)"), | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| } | ||||||
|
|
||||||
|
|
||||||
|
|
||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| # A part of NonVisual Desktop Access (NVDA) | ||
| # Copyright (C) 2026 NV Access Limited, Leonard de Ruijter | ||
| # This file may be used under the terms of the GNU General Public License, version 2 or later, as modified by the NVDA license. | ||
| # For full terms and any additional permissions, see the NVDA license file: https://github.com/nvaccess/nvda/blob/master/copying.txt | ||
|
|
||
| """ICU-based text boundary utilities using the Windows built-in ICU library. | ||
|
|
||
| Requires Windows 10 version 1703 (Creators Update) or later. | ||
| """ | ||
|
|
||
| import ctypes | ||
| from contextlib import contextmanager | ||
|
|
||
| import winBindings.icu as _icu | ||
|
LeonarddeR marked this conversation as resolved.
Outdated
|
||
| from logHandler import log | ||
|
|
||
| _ROOT_LOCALE: bytes = b"" | ||
| """ICU root locale. Word and character segmentation are script-driven, not | ||
| locale-driven (see calculateWordOffsets), so the root locale is always used. | ||
| """ | ||
|
|
||
|
|
||
| @contextmanager | ||
| def _breakIterator(kind: int, locale: bytes, buf: ctypes.Array[ctypes.c_wchar]): | ||
| """Context manager that opens an ICU BreakIterator, yields it, then closes it. | ||
|
|
||
| The caller owns the text buffer and must keep it alive for the duration of the | ||
| block, satisfying ICU's requirement that the text pointer remains valid while | ||
| the iterator is in use. | ||
|
|
||
| :param kind: One of the UBRK_* constants from winBindings.icu. | ||
| :param locale: ICU locale byte string (the root locale, _ROOT_LOCALE). | ||
| :param buf: NUL-terminated UTF-16 buffer (ctypes.create_unicode_buffer) to analyze. | ||
| :raises RuntimeError: If ICU reports an error opening the iterator. | ||
| """ | ||
| textLength = len(buf) - 1 | ||
| status = _icu.UErrorCode(0) | ||
| bi = _icu.ubrk_open(kind, locale, buf, textLength, ctypes.byref(status)) | ||
| if _icu.U_FAILURE(status.value) or not bi: | ||
| raise RuntimeError(f"ubrk_open failed with status {status.value}") | ||
| try: | ||
| yield bi | ||
| finally: | ||
| _icu.ubrk_close(bi) | ||
|
|
||
|
|
||
| def calculateWordOffsets( | ||
| text: str, | ||
| offset: int, | ||
| ) -> tuple[int, int] | None: | ||
| """Calculate the UTF-16 start and end offsets of the word at the given offset. | ||
|
|
||
| Word boundaries follow Unicode Standard Annex #29 default rules plus automatic | ||
| dictionary-based segmentation for scripts such as Thai, Lao, Khmer, and CJK | ||
| ideographs. ICU selects the dictionary by the script of the characters, not by | ||
| the locale, so no language is passed: any locale (including unrecognised codes) | ||
| would yield identical word boundaries and ICU never errors on an unknown locale | ||
| (it silently falls back to the root locale). The root locale is therefore used | ||
| unconditionally. (Locale-sensitive break types such as line and sentence | ||
| breaking would need a locale, but those are not used here.) | ||
|
|
||
| Trailing whitespace is included in the preceding word segment, matching the | ||
| behaviour of NVDA's Uniscribe implementation (textUtils.cpp). When the offset | ||
| falls inside a whitespace run, the returned segment is the preceding word plus | ||
| the whitespace. | ||
|
|
||
| Note: ICU coalesces a run of identical whitespace into one segment but splits | ||
| mixed whitespace (e.g. space + tab) into separate segments, so a mixed run is | ||
| not merged into a single word. This is not worth special-casing: the legacy | ||
| Uniscribe/Notepad behaviour for mixed whitespace runs is itself inconsistent. | ||
|
|
||
| :param text: The line text as a Python str. | ||
| :param offset: UTF-16 code unit offset within text at which to find the boundary. | ||
| :return: (startOffset, endOffset) as UTF-16 code unit indices (endOffset exclusive), | ||
| or None if the ICU call failed. | ||
| """ | ||
| # A c_wchar buffer is UTF-16 code-unit indexed on Windows, so buf[a:b] is exactly | ||
| # the segment ICU's offsets refer to (lone surrogates decode as non-space). | ||
| buf = ctypes.create_unicode_buffer(text) | ||
| textLength = len(buf) - 1 | ||
| if offset >= textLength: | ||
| return (offset, offset + 1) | ||
|
|
||
|
LeonarddeR marked this conversation as resolved.
|
||
| try: | ||
| with _breakIterator(_icu.UBRK_WORD, _ROOT_LOCALE, buf) as bi: | ||
| # Find [start, end) — the ICU segment containing offset. | ||
| # ICU offsets are code-point indexed, so anchor on the boundary following | ||
| # offset and take the boundary preceding that. (ubrk_preceding(offset + 1) | ||
| # would snap back for multi-unit segments.) | ||
| end = _icu.ubrk_following(bi, offset) | ||
|
LeonarddeR marked this conversation as resolved.
Outdated
|
||
| if end == _icu.UBRK_DONE: | ||
| end = textLength | ||
| start = _icu.ubrk_preceding(bi, end) | ||
| if start == _icu.UBRK_DONE: | ||
| start = 0 | ||
|
|
||
| if buf[start:end].isspace(): | ||
| # Offset is inside a whitespace run. Attach this run to the | ||
| # preceding segment (mirroring the Uniscribe trailing-space rule). | ||
| if start > 0: | ||
| wordStart = _icu.ubrk_preceding(bi, start) | ||
| if wordStart == _icu.UBRK_DONE: | ||
| wordStart = 0 | ||
| return (wordStart, end) | ||
| else: | ||
| # Offset is inside a word/punctuation segment. Extend the end | ||
| # through any immediately following whitespace run. | ||
| nextEnd = _icu.ubrk_following(bi, end) | ||
| if nextEnd != _icu.UBRK_DONE and buf[end:nextEnd].isspace(): | ||
| return (start, nextEnd) | ||
|
|
||
| return (start, end) | ||
| except RuntimeError: | ||
| log.debugWarning("ICU word break iterator failed", exc_info=True) | ||
| return None | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.