Spellcheck in Build: red underlines, suggestions, spread dictionary

Titles, result text and details (card, inspector, Lore Entries) get red
wavy lines under misspelled words; right-click gives suggestions, Add to
dictionary (saved with the spread) and Ignore (this session). Uses the
Godot-Hunspell add-on's SpellChecker when it is installed; off on Android
and when the add-on is missing. English (en_US) dictionary included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
RobinFiredrake 2026-11-15 12:50:14 -06:00
parent cc7cd0f660
commit f2cd982e43
18 changed files with 48431 additions and 0 deletions

21
addons/hunspell/LICENSE Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 Bruno Brito
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,154 @@
en_US Hunspell Dictionary
Unknown Version
Thu Jul 16 09:31:00 UTC 2026
https://wordlist.aspell.net
README file for English Hunspell dictionaries derived from SCOWL.
These dictionaries are created using the speller/make-hunspell-dict
script in SCOWL.
The following dictionaries are available:
en_US (American)
en_CA (Canadian)
en_GB-ise (British with -ise/traditional spelling)
en_GB-ize (British with -ize/Oxford spelling)
en_AU (Australian)
en_US-large
en_CA-large
en_GB-large (with both -ise and -ize spelling)
en_AU-large
The default dictionaries correspond to SCOWL size 60 and, to encourage
consistent spelling, generally only include one spelling variant for a word.
The large dictionaries correspond to SCOWL size 70 and include common
spelling variants. The larger dictionaries, however, (1) have not been as
carefully checked for errors as the normal dictionaries and thus may contain
misspelled or invalid words; and (2) contain uncommon, yet valid, words that
might cause problems as they are likely to be misspellings of more common
words (for example, "ort" and "calender").
The American, Canadian, and Australian dictionaries are considered the
official version for Hunspell. The British ones are considered an
alternative version. The official ones are maintained by Marco A.G.Pinto at
https://proofingtoolgui.org.
For additional information, including information on how to contribute, see
https://wordlist.aspell.net/dicts/.
IMPORTANT CHANGES INTRODUCED ON 2026-02-22:
The Unicode "’" (U+2019) character was added to WORDCHARS so that Hunspell can
recognize words with the apostrophe. Based on testing, this should allow
Hunspell to recognize both "can't" and "can’t". The ASCII single quote at the
end of the word won't be considered part of the word, but the Unicode
character will. This means "'color'" is okay, but "‘color’" will get flagged
when Hunspell does the tokenization.
IMPORTANT CHANGES INTRODUCED IN 2016.11.20:
New Australian dictionaries thanks to the work of Benjamin Titze
(btitze@protonmail.ch).
IMPORTANT CHANGES INTRODUCED IN 2016.04.24:
The dictionaries are now in UTF-8 format instead of ISO-8859-1. This
was required to handle smart quotes correctly.
IMPORTANT CHANGES INTRODUCED IN 2016.01.19:
"SET UTF8" was changes to "SET UTF-8" in the affix file as some
versions of Hunspell do not recognize "UTF8".
ADDITIONAL NOTES:
The NOSUGGEST flag was added to certain taboo words. While I made an
honest attempt to flag the strongest taboo words with the NOSUGGEST
flag, I MAKE NO GUARANTEE THAT I FLAGGED EVERY POSSIBLE TABOO WORD.
The list was originally derived from Németh László, however I removed
some words which, while being considered taboo by some dictionaries,
are not really considered swear words in today's society.
COPYRIGHT, SOURCES, and CREDITS:
The English dictionaries come directly from SCOWL and is thus under
the same copyright terms as SCOWL. The affix file is a heavily
modified version of the original english.aff file, which was
released as part of Geoff Kuenning's Ispell and as such is covered by
his BSD license.
Copyright 2000-2026 by Kevin Atkinson
Permission to use, copy, modify, distribute, and sell any part of SCOWLv2, or
word lists created from it, is hereby granted without fee, provided that the
above copyright notice appears in all copies and that both the above
copyright notice and this notice appear in supporting documentation. Kevin
Atkinson makes no representations about the suitability of this database for
any purpose. It is provided "as is" without express or implied warranty.
SCOWL is derived from many sources, most of which are in the Public Domain.
Data from the Corpus of Contemporary American English (COCA) was also used.
All data from COCA comes from 3-gram data that is not freely available;
however, the usage is within the rights given by the NDA that was signed when
purchasing the data. More information on COCA is available at
https://www.english-corpora.org/coca/.
The primary source of words for SCOWL comes from 12dicts and ENABLE2K. Both
are in the Public Domain, but Alan Beale <biljir@pobox.com> deserves special
credit as he is the author of 12dicts and a major contributor to ENABLE2K. In
addition, he gave me an incredible amount of feedback and created a number of
special lists in order to help improve the overall quality of SCOWL.
The initial information for Australian English comes from Benjamin Titze:
Copyright 2016 by Benjamin Titze
Permission to use, copy, modify, distribute and sell this array, the
associated software, and its documentation for any purpose is hereby
granted without fee, provided that the above copyright notice appears
in all copies and that both that copyright notice and this permission
notice appear in supporting documentation. Benjamin Titze makes no
representations about the suitability of this array for any
purpose. It is provided "as is" without express or implied warranty.
Affix file Copyright:
Copyright 1993, Geoff Kuenning, Granada Hills, CA
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All modifications to the source code must be clearly marked as
such. Binary redistributions based on modified source code
must be clearly marked as modified versions in the documentation
and/or other materials provided with the distribution.
(clause 4 removed with permission from Geoff Kuenning)
5. The name of Geoff Kuenning may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY GEOFF KUENNING AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL GEOFF KUENNING OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
Build Date: Thu Jul 16 09:31:00 UTC 2026
Wordlist Command: mk-list --accents=strip en_US 60

View file

@ -0,0 +1,213 @@
# Affix file for en_US Hunspell Dictionary.
#
# Unknown Version
# Thu Jul 16 09:31:00 UTC 2026
#
# https://wordlist.aspell.net
#
SET UTF-8
TRY esianrtolcdugmphbyfvkwzESIANRTOLCDUGMPHBYFVKWZ'
ICONV 1
ICONV ’ '
NOSUGGEST !
# ordinal numbers
COMPOUNDMIN 1
# only in compounds: 1th, 2th, 3th
ONLYINCOMPOUND c
# compound rules:
# 1. [0-9]*1[0-9]th (10th, 11th, 12th, 56714th, etc.)
# 2. [0-9]*[02-9](1st|2nd|3rd|[4-9]th) (21st, 22nd, 123rd, 1234th, etc.)
COMPOUNDRULE 2
COMPOUNDRULE n*1t
COMPOUNDRULE n*mp
WORDCHARS 0123456789’
PFX A Y 1
PFX A 0 re .
PFX I Y 1
PFX I 0 in .
PFX U Y 1
PFX U 0 un .
PFX C Y 1
PFX C 0 de .
PFX E Y 1
PFX E 0 dis .
PFX F Y 1
PFX F 0 con .
PFX K Y 1
PFX K 0 pro .
SFX V N 2
SFX V e ive e
SFX V 0 ive [^e]
SFX N Y 3
SFX N e ion e
SFX N y ication y
SFX N 0 en [^ey]
SFX X Y 3
SFX X e ions e
SFX X y ications y
SFX X 0 ens [^ey]
SFX H N 2
SFX H y ieth y
SFX H 0 th [^y]
SFX Y Y 1
SFX Y 0 ly .
SFX G Y 2
SFX G e ing e
SFX G 0 ing [^e]
SFX J Y 2
SFX J e ings e
SFX J 0 ings [^e]
SFX D Y 4
SFX D 0 d e
SFX D y ied [^aeiou]y
SFX D 0 ed [^ey]
SFX D 0 ed [aeiou]y
SFX T N 4
SFX T 0 st e
SFX T y iest [^aeiou]y
SFX T 0 est [aeiou]y
SFX T 0 est [^ey]
SFX R Y 4
SFX R 0 r e
SFX R y ier [^aeiou]y
SFX R 0 er [aeiou]y
SFX R 0 er [^ey]
SFX Z Y 4
SFX Z 0 rs e
SFX Z y iers [^aeiou]y
SFX Z 0 ers [aeiou]y
SFX Z 0 ers [^ey]
SFX S Y 4
SFX S y ies [^aeiou]y
SFX S 0 s [aeiou]y
SFX S 0 es [sxzh]
SFX S 0 s [^sxzhy]
SFX P Y 3
SFX P y iness [^aeiou]y
SFX P 0 ness [aeiou]y
SFX P 0 ness [^y]
SFX M Y 1
SFX M 0 's .
SFX B Y 3
SFX B 0 able [^aeiou]
SFX B 0 able ee
SFX B e able [^aeiou]e
SFX L Y 1
SFX L 0 ment .
REP 90
REP a ei
REP ei a
REP a ey
REP ey a
REP ai ie
REP ie ai
REP alot a_lot
REP are air
REP are ear
REP are eir
REP air are
REP air ere
REP ere air
REP ere ear
REP ere eir
REP ear are
REP ear air
REP ear ere
REP eir are
REP eir ere
REP ch te
REP te ch
REP ch ti
REP ti ch
REP ch tu
REP tu ch
REP ch s
REP s ch
REP ch k
REP k ch
REP f ph
REP ph f
REP gh f
REP f gh
REP i igh
REP igh i
REP i uy
REP uy i
REP i ee
REP ee i
REP j di
REP di j
REP j gg
REP gg j
REP j ge
REP ge j
REP s ti
REP ti s
REP s ci
REP ci s
REP k cc
REP cc k
REP k qu
REP qu k
REP kw qu
REP o eau
REP eau o
REP o ew
REP ew o
REP oo ew
REP ew oo
REP ew ui
REP ui ew
REP oo ui
REP ui oo
REP ew u
REP u ew
REP oo u
REP u oo
REP u oe
REP oe u
REP u ieu
REP ieu u
REP ue ew
REP ew ue
REP uff ough
REP oo ieu
REP ieu oo
REP ier ear
REP ear ier
REP ear air
REP air ear
REP w qu
REP qu w
REP z ss
REP ss z
REP shun tion
REP shun sion
REP shun cion
REP size cise

File diff suppressed because it is too large Load diff

47
core/spell_words.gd Normal file
View file

@ -0,0 +1,47 @@
class_name SpellWords
extends RefCounted
## Finds the words a spellchecker should look at in a field's text. Skips the
## parts that aren't prose: BBCode tags ([b], [color=#fff]), {placeholders},
## @values, [[Spread::Card]] links, numbers, dice ("2d6") and web addresses.
static var _word_re: RegEx
static var _skip_re: RegEx
static func _setup() -> void:
if _word_re != null:
return
# Letters, with inner apostrophes ("don't", "fortune-teller's" splits at -).
_word_re = RegEx.create_from_string("[\\p{L}]+(?:['’][\\p{L}]+)*")
# Spans to blank out first, so words inside them are never checked.
_skip_re = RegEx.create_from_string("\\[\\[[^\\]]*\\]\\]|\\[[^\\]\\n]*\\]|\\{[^}\\n]*\\}|@[\\w.]+|https?://\\S+|\\b\\d+d\\d+\\b|\\w*\\d\\w*")
## Vector2i(start, end) for each word to check, in text order (end exclusive).
static func ranges(text: String) -> Array[Vector2i]:
_setup()
var masked := text
for m in _skip_re.search_all(text):
var blank := " ".repeat(m.get_end() - m.get_start())
masked = masked.substr(0, m.get_start()) + blank + masked.substr(m.get_end())
var out: Array[Vector2i] = []
for m in _word_re.search_all(masked):
var word := m.get_string()
# Single letters and ALL-CAPS short forms (HP, NPC) are left alone.
if word.length() < 2 or (word.length() <= 4 and word == word.to_upper()):
continue
out.append(Vector2i(m.get_start(), m.get_end()))
return out
## The word range holding character `at`, or Vector2i(-1, -1).
static func range_at(text: String, at: int) -> Vector2i:
for r in ranges(text):
if at >= r.x and at <= r.y:
return r
return Vector2i(-1, -1)
## `text` with range `r` replaced by `word`.
static func replace(text: String, r: Vector2i, word: String) -> String:
return text.substr(0, r.x) + word + text.substr(r.y)

1
core/spell_words.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://d4ckh65ryw6rv

View file

@ -24,6 +24,9 @@ var groups: Array[TableGroup] = []
var book: Array[BookPage] = []
## Pictures: id -> base64 data (BoardImages). Only used ones are saved.
var images: Dictionary = {}
## Words the spellchecker accepts in this spread ("Add to dictionary"): the
## setting's names and terms. Saved with the spread, so they travel with it.
var dictionary: Array[String] = []
static func new_id(prefix: String) -> String:
@ -213,6 +216,8 @@ func to_dict() -> Dictionary:
d["groups"] = gl
if not book.is_empty():
d["book"] = book_list()
if not dictionary.is_empty():
d["dictionary"] = dictionary.duplicate()
var pics := BoardImages.used(self)
if not pics.is_empty():
d["images"] = pics
@ -251,6 +256,13 @@ func load_dict(src: Dictionary) -> bool:
groups = loaded_groups
clean_groups()
load_book(d.get("book", []))
var words: Array[String] = []
var src_words: Variant = d.get("dictionary", [])
if src_words is Array:
for w: Variant in src_words:
if str(w).strip_edges() != "" and not words.has(str(w).strip_edges()):
words.append(str(w).strip_edges())
dictionary = words
# Undo snapshots carry no pictures: keep the ones already loaded.
if d.get("images") is Dictionary:
images.merge(d["images"], true)

97
tests/test_spellcheck.gd Normal file
View file

@ -0,0 +1,97 @@
extends TestBase
## Spellchecking in Build (Spellcheck, SpellWords, SpellUnderline), with a
## stand-in checker so the test needs no native add-on: which words are
## checked, underlines on card and inspector fields, suggestions replacing a
## word, the spread's own dictionary (saved with it) and Ignore.
## Run: godot --headless --path . -s res://tests/test_spellcheck.gd -- --sample
## Knows a few words; suggests from a fixed table.
class FakeChecker:
extends RefCounted
const KNOWN := ["the", "result", "work", "joe", "tinker", "bob", "workday", "job", "fixes", "press", "after", "hard", "day's", "new"]
func spell(word: String) -> bool:
return KNOWN.has(word.to_lower())
func suggest(word: String) -> PackedStringArray:
return PackedStringArray({"tinkerr": ["tinker", "tinkers"], "wrok": ["work"]}.get(word.to_lower(), []))
func _init() -> void:
_test_words()
Spellcheck.use_backend(FakeChecker.new())
_test_checking()
if not await start_main():
return
main.set_mode(Main.Mode.BUILD)
main.data.load_dict({"format_version": 2, "id": "spell-test", "name": "Spell test", "tables": [
{"id": "work", "name": "Workday Job", "x": 40, "y": 40, "entries": [
{"id": "a", "text": "Joe the tinkerr", "details": "Fixes the press after a hard day's wrok"},
{"id": "b", "text": "Vargr"}]}]})
main._rebuild_cards()
await _frames(4)
await _test_card_fields()
await _test_dictionary()
Spellcheck.use_backend(null)
finish()
func _words(text: String) -> Array:
return SpellWords.ranges(text).map(func(r: Vector2i) -> String: return text.substr(r.x, r.y - r.x))
func _test_words() -> void:
_eq(_words("[b]Joe[/b] the {option} tinker @hp [[Spread::Card]]"), ["Joe", "the", "tinker"], "tags, placeholders, values and links are skipped")
_eq(_words("Roll 2d6 for 3 HP, don't"), ["Roll", "for", "don't"], "numbers, dice and short capitals are skipped")
func _test_checking() -> void:
var board := TowerBoard.new()
var text := "Joe the tinkerr"
_eq(Spellcheck.misspelled(text, board), [Vector2i(8, 15)] as Array[Vector2i], "a misspelled word is found")
board.dictionary.append("Tinkerr")
_check(Spellcheck.misspelled(text, board).is_empty(), "the spread's dictionary accepts it, in any case")
var back := TowerBoard.new()
back.load_dict(board.to_dict())
_eq(back.dictionary, ["Tinkerr"] as Array[String], "the dictionary is saved with the spread")
func _underline(c: Control) -> SpellUnderline:
return c.get_meta("spell") if c.has_meta("spell") else null
func _test_card_fields() -> void:
var card := main.card_for("work")
var row: Control = card.rows["a"]
var edits := row.find_children("*", "LineEdit", true, false)
var u: SpellUnderline = _underline(edits[0]) if not edits.is_empty() else null
_check(u != null, "a result's text field on the card is checked")
if u == null:
return
_eq(u.bad, [Vector2i(8, 15)] as Array[Vector2i], "the misspelled word is underlined")
u.open_menu(u.bad[0], Vector2(100, 100))
_eq(u._menu.get_item_text(0), "tinker", "the menu starts with suggestions")
u._on_menu(0)
await _frames()
_eq(main.data.get_table("work").find_entry("a").text, "Joe the tinker", "picking a suggestion fixes the result")
main.select_result("work", "a")
await _frames()
var det: Control = main.inspector.fields.get("details")
_check(det != null and _underline(det) != null and _underline(det).bad.size() == 1, "the inspector's Details are checked too")
func _test_dictionary() -> void:
var card := main.card_for("work")
var edits := (card.rows["b"] as Control).find_children("*", "LineEdit", true, false)
var u: SpellUnderline = _underline(edits[0])
_eq(u.bad.size(), 1, "a setting's name is flagged at first")
u.open_menu(u.bad[0], Vector2(100, 100))
u._on_menu(SpellUnderline.ID_ADD)
_check(main.data.dictionary.has("Vargr"), "Add to dictionary saves the word in the spread")
_check(u.bad.is_empty(), "the underline goes away")
Spellcheck.ignore(main, "wrok")
_check(Spellcheck.is_ok("Wrok", main.data), "Ignore accepts the word for this session")
main.set_mode(Main.Mode.PLAY)
await _frames()
main.set_mode(Main.Mode.BUILD)

View file

@ -0,0 +1 @@
uid://bsbhdy6i2m786

View file

@ -22,6 +22,7 @@ static func build(insp: Inspector, box: VBoxContainer, t: RollTable, with_head:
insp.apply_settings({"name": s})
)
insp.fields["name"] = name
SpellUnderline.attach(name, insp.main)
box.add_child(InspectorKit.field("Label" if t.kind == RollTable.KIND_VARIABLE else "Name", name))
match t.kind:
@ -49,6 +50,7 @@ static func build(insp: Inspector, box: VBoxContainer, t: RollTable, with_head:
InspectorKit.tag(det, "card.details")
det.text_changed.connect(func() -> void: insp.apply_settings({"details": det.text}))
insp.fields["details"] = det
SpellUnderline.attach(det, insp.main)
box.add_child(InspectorKit.field("Details", det))
var tags := InspectorKit.line(", ".join(t.tags), "e.g. loot, town")

View file

@ -78,6 +78,7 @@ static func section(insp: Inspector, t: RollTable, e: TableEntry, with_head: boo
le.text = (le.text.strip_edges() + " " + ref).strip_edges()
insp.set_entry_text(le.text)))
insp.fields["text"] = le
SpellUnderline.attach(le, insp.main)
insp._content.add_child(InspectorKit.field(Inspector._title_of(str(t.columns[0].get("name", "")), "Text") if t.has_columns() else "Text", le))
insp._content.add_child(link)
InspectorColumns.result_cells(insp, t, e)
@ -86,6 +87,7 @@ static func section(insp: Inspector, t: RollTable, e: TableEntry, with_head: boo
InspectorKit.tag(det, "res.details")
det.text_changed.connect(func() -> void: insp.set_entry_details(det.text))
insp.fields["details"] = det
SpellUnderline.attach(det, insp.main)
insp._content.add_child(InspectorKit.field("Details", det))
insp._content.add_child(InspectorKit.field("Picture", ImageField.new(insp.main, e.image, func(id: String) -> void:
e.image = id

View file

@ -35,6 +35,7 @@ func show_page(p: BookPage) -> void:
_preview.text = RichText.decorate(p.text)
_changed())
add_child(_field("Result text", text))
SpellUnderline.attach(text, m)
_preview = RichText.label(RichText.decorate(p.text), 16, Style.INK, false, true)
var pv := PanelContainer.new()
pv.add_theme_stylebox_override("panel", Style.box(Style.CARD, 6, [10, 6, 10, 6]))
@ -46,6 +47,7 @@ func show_page(p: BookPage) -> void:
det.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
det.custom_minimum_size = Vector2(0, 60)
ModalCard.style_text_edit(det)
SpellUnderline.attach(det, m)
det.text_changed.connect(func() -> void:
p.details = det.text
_changed())

216
ui/spell_underline.gd Normal file
View file

@ -0,0 +1,216 @@
class_name SpellUnderline
extends Control
## Red wavy lines under misspelled words in one LineEdit or TextEdit (Build
## only), laid over the field. Right-clicking such a word opens a menu of
## suggestions, "Add to dictionary" (the spread's own words) and "Ignore",
## then the usual Cut, Copy and Paste. Spellcheck does the checking.
const GROUP := "spell_underline"
const WAVE := 2.0
const ID_ADD := 100
const ID_IGNORE := 101
const ID_CUT := 102
const ID_COPY := 103
const ID_PASTE := 104
var field: Control
var m: Main
## Misspelled word ranges in the field's text, from the last check.
var bad: Array[Vector2i] = []
var _menu: PopupMenu
var _menu_range := Vector2i(-1, -1)
## Adds underlines to `field`, if spellchecking is available.
static func attach(field: Control, p_main: Main) -> void:
if p_main == null or field.has_meta("spell") or not Spellcheck.available():
return
var u := SpellUnderline.new()
u.field = field
u.m = p_main
field.set_meta("spell", u)
field.add_child(u)
func _ready() -> void:
set_anchors_and_offsets_preset(PRESET_FULL_RECT)
mouse_filter = MOUSE_FILTER_IGNORE
add_to_group(GROUP)
if field is LineEdit:
(field as LineEdit).text_changed.connect(func(_s: String) -> void: recheck())
else:
(field as TextEdit).text_changed.connect(recheck)
(field as TextEdit).get_v_scroll_bar().value_changed.connect(func(_v: float) -> void: queue_redraw())
field.resized.connect(queue_redraw)
field.gui_input.connect(_on_field_input)
recheck()
## The field's text scrolls as the caret moves, so a focused field redraws.
func _process(_delta: float) -> void:
if field.has_focus():
queue_redraw()
func text() -> String:
return (field as LineEdit).text if field is LineEdit else (field as TextEdit).text
func recheck() -> void:
bad = Spellcheck.misspelled(text(), m.data) if m.mode == Main.Mode.BUILD else ([] as Array[Vector2i])
queue_redraw()
func _draw() -> void:
for r in bad:
for seg in _segments(r):
_wave(seg[0], seg[1], seg[2])
## Wavy line from x0 to x1 at height y.
func _wave(x0: float, x1: float, y: float) -> void:
var pts := PackedVector2Array()
var x := x0
var up := true
while x <= x1:
pts.append(Vector2(x, y + (-WAVE if up else WAVE) * 0.5))
x += WAVE
up = not up
if pts.size() >= 2:
draw_polyline(pts, Style.DANGER, 1.2, true)
## [x0, x1, y] pieces under range `r` (one per line it covers).
func _segments(r: Vector2i) -> Array:
if field is LineEdit:
var y := size.y - _line_margin_bottom()
return [[_line_x(r.x), _line_x(r.y), y]]
var edit := field as TextEdit
var out: Array = []
for i in range(r.x, r.y):
var lc := _line_col(i)
var rect := edit.get_rect_at_line_column(lc.x, lc.y)
if rect.size.x <= 0:
continue
var y := float(rect.position.y + rect.size.y) - 1.0
if not out.is_empty() and is_equal_approx(out[-1][2], y):
out[-1][1] = float(rect.position.x + rect.size.x)
else:
out.append([float(rect.position.x), float(rect.position.x + rect.size.x), y])
return out
func _line_margin_bottom() -> float:
var sb := field.get_theme_stylebox("normal")
return maxf(3.0, sb.get_margin(SIDE_BOTTOM) * 0.6) if sb else 4.0
## LineEdit: the x of the gap before character `column`.
func _line_x(column: int) -> float:
var line := field as LineEdit
var font := line.get_theme_font("font")
var font_size := line.get_theme_font_size("font_size")
var sb := line.get_theme_stylebox("normal")
var left := sb.get_margin(SIDE_LEFT) if sb else 0.0
var scroll: float = line.call("get_scroll_offset") if line.has_method("get_scroll_offset") else 0.0
return left - scroll + font.get_string_size(line.text.substr(0, column), HORIZONTAL_ALIGNMENT_LEFT, -1, font_size).x
## TextEdit: Vector2i(line, column) of character offset `at`.
func _line_col(at: int) -> Vector2i:
var edit := field as TextEdit
var rest := at
for i in edit.get_line_count():
var n := edit.get_line(i).length()
if rest <= n:
return Vector2i(i, rest)
rest -= n + 1
return Vector2i(edit.get_line_count() - 1, 0)
## The character offset under a point in the field.
func offset_at(p: Vector2) -> int:
if field is LineEdit:
var best := 0
for column in (field as LineEdit).text.length() + 1:
if _line_x(column) <= p.x:
best = column
return best
var edit := field as TextEdit
var lc := edit.get_line_column_at_pos(Vector2i(p), false)
var offset := 0
for i in lc.y:
offset += edit.get_line(i).length() + 1
return offset + lc.x
func _on_field_input(ev: InputEvent) -> void:
var mb := ev as InputEventMouseButton
if mb == null or not mb.pressed or mb.button_index != MOUSE_BUTTON_RIGHT:
return
var at := offset_at(mb.position)
for r in bad:
if at >= r.x and at <= r.y:
field.accept_event()
open_menu(r, field.get_screen_position() + mb.position)
return
## The spelling menu for word range `r`, at a screen position.
func open_menu(r: Vector2i, at: Vector2) -> void:
if _menu == null:
_menu = PopupMenu.new()
ModalCard.style_popup(_menu)
_menu.id_pressed.connect(_on_menu)
add_child(_menu)
_menu.clear()
_menu_range = r
var word := text().substr(r.x, r.y - r.x)
var sugs := Spellcheck.suggestions(word)
for i in sugs.size():
_menu.add_item(sugs[i], i)
if sugs.is_empty():
_menu.add_item("No suggestions", 99)
_menu.set_item_disabled(_menu.get_item_index(99), true)
_menu.add_separator()
_menu.add_item("Add “%s” to dictionary" % word, ID_ADD)
_menu.set_item_tooltip(_menu.get_item_index(ID_ADD), "This spread accepts the word from now on (it travels with the spread)")
_menu.add_item("Ignore", ID_IGNORE)
_menu.set_item_tooltip(_menu.get_item_index(ID_IGNORE), "Accept it until the app closes")
_menu.add_separator()
_menu.add_item("Cut", ID_CUT)
_menu.add_item("Copy", ID_COPY)
_menu.add_item("Paste", ID_PASTE)
_menu.popup(Rect2i(Vector2i(at), Vector2i.ZERO))
func _on_menu(id: int) -> void:
var word := text().substr(_menu_range.x, _menu_range.y - _menu_range.x)
match id:
ID_ADD:
Spellcheck.add_to_dictionary(m, word)
ID_IGNORE:
Spellcheck.ignore(m, word)
ID_CUT:
field.call("menu_option", LineEdit.MENU_CUT if field is LineEdit else TextEdit.MENU_CUT)
ID_COPY:
field.call("menu_option", LineEdit.MENU_COPY if field is LineEdit else TextEdit.MENU_COPY)
ID_PASTE:
field.call("menu_option", LineEdit.MENU_PASTE if field is LineEdit else TextEdit.MENU_PASTE)
_:
if id >= 0 and id < Spellcheck.MAX_SUGGESTIONS:
replace(_menu_range, _menu.get_item_text(_menu.get_item_index(id)))
## Puts `word` in place of range `r` and tells the field's listeners.
func replace(r: Vector2i, word: String) -> void:
var new_text := SpellWords.replace(text(), r, word)
if field is LineEdit:
var line := field as LineEdit
line.text = new_text
line.caret_column = r.x + word.length()
line.text_changed.emit(line.text)
else:
var edit := field as TextEdit
edit.text = new_text
edit.text_changed.emit()

View file

@ -0,0 +1 @@
uid://2w17lsg5qyby

104
ui/spellcheck.gd Normal file
View file

@ -0,0 +1,104 @@
class_name Spellcheck
extends RefCounted
## English spellchecking for Build's prose fields (titles, result text,
## details), through Hunspell (the Godot-Hunspell add-on's SpellChecker class
## in addons/hunspell). Words the spread accepts live in TowerBoard.dictionary;
## Ignore lasts for this session. Off on Android (its keyboards check spelling)
## and whenever the add-on isn't there; then fields simply get no underlines.
const AFF := "res://addons/hunspell/dictionaries/en_US.aff"
const DIC := "res://addons/hunspell/dictionaries/en_US.dic"
const MAX_SUGGESTIONS := 5
## The checker (spell(word) -> bool, suggest(word) -> PackedStringArray), or
## null. Tests set a stand-in with use_backend().
static var backend: Object = null
static var _tried := false
static var _cache: Dictionary = {}
## Lower-case words ignored until the app closes.
static var ignored: Dictionary = {}
static func available() -> bool:
if OS.get_name() == "Android":
return false
_load()
return backend != null
static func _load() -> void:
if _tried:
return
_tried = true
if not ClassDB.class_exists("SpellChecker"):
return
var checker: Object = ClassDB.instantiate("SpellChecker")
if checker and checker.call("load_dictionary", AFF, DIC):
backend = checker
## Uses `checker` instead of Hunspell (tests); null turns spellchecking off.
static func use_backend(checker: Object) -> void:
backend = checker
_tried = true
_cache.clear()
ignored.clear()
## True when `word` is spelled right, ignored, or in the spread's dictionary.
static func is_ok(word: String, board: TowerBoard) -> bool:
if backend == null or ignored.has(word.to_lower()) or in_dictionary(board, word):
return true
if not _cache.has(word):
_cache[word] = bool(backend.call("spell", word))
return _cache[word]
## The word ranges in `text` that are spelled wrong.
static func misspelled(text: String, board: TowerBoard) -> Array[Vector2i]:
var out: Array[Vector2i] = []
if backend == null:
return out
for r in SpellWords.ranges(text):
if not is_ok(text.substr(r.x, r.y - r.x), board):
out.append(r)
return out
static func suggestions(word: String) -> PackedStringArray:
if backend == null:
return PackedStringArray()
var all: PackedStringArray = backend.call("suggest", word)
return all.slice(0, MAX_SUGGESTIONS)
static func in_dictionary(board: TowerBoard, word: String) -> bool:
if board == null:
return false
var low := word.to_lower()
for w in board.dictionary:
if w.to_lower() == low:
return true
return false
## "Add to dictionary": the spread accepts the word from now on (an undo step).
static func add_to_dictionary(m: Main, word: String) -> void:
if in_dictionary(m.data, word):
return
m.undo_redo._begin_edit()
m.data.dictionary.append(word)
m.mark_dirty()
m.undo_redo._end_edit()
recheck_all(m)
## "Ignore": accepted until the app closes, in every spread.
static func ignore(m: Main, word: String) -> void:
ignored[word.to_lower()] = true
recheck_all(m)
static func recheck_all(m: Main) -> void:
if m.is_inside_tree():
m.get_tree().call_group(SpellUnderline.GROUP, "recheck")

1
ui/spellcheck.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://cfwlxsb3mnyxm

View file

@ -21,6 +21,8 @@ func text_edit(e: TableEntry, index: int, chosen: bool) -> LineEdit:
var edit := LineEdit.new()
edit.text = e.text
FormatMenu.attach(edit)
if table.kind != RollTable.KIND_LOOP:
SpellUnderline.attach(edit, card.main)
if chosen:
edit.placeholder_text = "(the option's name)"
edit.tooltip_text = "The result text. Leave it as Chosen (or empty) to show the picked option's name; {option_label}, {option_value} and {@[option]} work"

View file

@ -76,6 +76,7 @@ func make(build: bool, ranged: bool) -> Control:
main.mark_dirty()
)
row.add_child(name_edit)
SpellUnderline.attach(name_edit, main)
row.add_child(card.edit_ui.make_card_menu())
else:
var titles := TableCard.vbox(3)