Skip to content

Commit 8cdacd0

Browse files
pvcravenPaul V Cravenclaude
authored
Fix UIFlatButton border gap, single-style error, and UITextArea styles (#2946)
- UIFlatButton drew its border outline inset by a full border width, but outlines are centered on their rectangle, leaving a gap of half the border width at the edge (also on UIDropdown) (#2868). - Passing a single style to a styled widget raised a confusing TypeError from DictProperty. It now says a dict of styles per state is needed, and how to start from DEFAULT_STYLE (#2817). - UITextArea set its font and color over the whole document, replacing styles set in ATTRIBUTED and HTML text. Those now win, and the arguments fill in the rest, also replacing the HTML decoder's own defaults (#2441). bold and italic set keys pyglet 3 doesn't read, so they now set weight and style. The 2_widgets example's attributed text used the old bold key too. Co-authored-by: Paul V Craven <paul.craven@optimizley.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 306885b commit 8cdacd0

8 files changed

Lines changed: 153 additions & 27 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ Arcade [PyPi Release History](https://pypi.org/project/arcade/#history) page.
66
## Unreleased
77

88
### Fixes
9+
- GUI: Fixed a gap between `UIFlatButton`'s border and the edge of the button, half the border's width, which also showed on `UIDropdown` ([#2868](https://github.com/pythonarcade/arcade/issues/2868)).
10+
- GUI: Passing a single style such as `UIFlatButton.UIStyle()` as a widget's `style` raised a confusing `TypeError` about attribute names. It now raises a `TypeError` saying a dict of styles for each state is needed, and how to start from the widget's `DEFAULT_STYLE` ([#2817](https://github.com/pythonarcade/arcade/issues/2817)).
11+
- GUI: Fixed `UITextArea`:
12+
- With `document_mode="ATTRIBUTED"` or `"HTML"`, the widget's font and color replaced every style set in the text. Styles set in the text now win, and the widget's arguments apply to the rest. In HTML mode they also replace the decoder's own defaults, such as Times New Roman ([#2441](https://github.com/pythonarcade/arcade/issues/2441)).
13+
- `bold` and `italic` had no effect, because pyglet 3 reads the `weight` and `style` keys instead.
14+
- The text widgets page of the `gui/2_widgets` example now shows its labels in bold.
915
- Fixed `arcade.math.rand_vec_spread_deg()` returning vectors in random directions. It passed the angle in degrees to a function that expects radians, so for example the spread emitters in the `particle_systems` example sprayed everywhere ([#2648](https://github.com/pythonarcade/arcade/issues/2648)).
1016
- Fixed reading 2 GB or more from an OpenGL texture, texture array, framebuffer or buffer on Windows, which failed because `ctypes.string_at` takes its size as a 32-bit C long there ([#2836](https://github.com/pythonarcade/arcade/issues/2836)).
1117
- Fixed a player in `PhysicsEnginePlatformer` sliding along when standing across two moving platforms. It moved by both platforms' speeds added together, so it slid until it stood on only one. It now moves with the platform it stands on the most, and isn't moved by a platform it only touches the edge of while standing mostly on something still ([#2782](https://github.com/pythonarcade/arcade/issues/2782)).

‎arcade/examples/gui/2_widgets.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -85,13 +85,13 @@
8585
Arcade GUI provides three types of text widgets:
8686
8787
88-
- {bold True}UILabel{bold False}:
88+
- {weight "bold"}UILabel{weight "normal"}:
8989
A simple text widget that can be used to display text.
9090
91-
- {bold True}UIInputText{bold False}:
91+
- {weight "bold"}UIInputText{weight "normal"}:
9292
A text widget that can be used to get text input from the user.
9393
94-
- {bold True}UITextArea{bold False}:
94+
- {weight "bold"}UITextArea{weight "normal"}:
9595
A text widget that can be used to display text that is too long for a label.
9696
9797
@@ -101,18 +101,18 @@
101101
A few hints regarding the usage of the text widgets:
102102
103103
104-
{bold True}UILabel{bold False}:
104+
{weight "bold"}UILabel{weight "normal"}:
105105
106106
If you want to display frequently changing text,
107107
setting a background color will improve performance.
108108
109109
110-
{bold True}UIInputText{bold False}:
110+
{weight "bold"}UIInputText{weight "normal"}:
111111
112112
UIInputText dispatches an event on_change, when the text changes.
113113
114114
115-
{bold True}UITextArea{bold False}:
115+
{weight "bold"}UITextArea{weight "normal"}:
116116
117117
While the widget supports scrolling, there is no scrollbar provided yet.
118118
Users might oversee content.

‎arcade/gui/style.py‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,15 @@ class UIStyledWidget(UIWidget, Generic[StyleRef]):
5757
style = DictProperty[str, StyleRef]()
5858

5959
def __init__(self, *, style: dict[str, StyleRef], **kwargs):
60+
if isinstance(style, UIStyleBase):
61+
# A single style would otherwise fail deep inside DictProperty
62+
name = type(self).__name__
63+
raise TypeError(
64+
f"{name} style must be a dict of styles for each state, such as "
65+
'{"normal": style, "hover": ..., "press": ..., "disabled": ...}, '
66+
f"not a single {type(style).__name__}. To change only some states, "
67+
f'start from the defaults: {{**{name}.DEFAULT_STYLE, "normal": style}}'
68+
)
6069
self.style = style
6170
super().__init__(**kwargs)
6271

‎arcade/gui/widgets/buttons.py‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -369,11 +369,13 @@ def do_render(self, surface: Surface):
369369

370370
# render button border (which is not the widgets border)
371371
if border_color and border_width:
372+
# The outline is centered on the rectangle's edge, so inset it by
373+
# half its width to draw it right up to the button's edge
372374
arcade.draw_lbwh_rectangle_outline(
373-
border_width,
374-
border_width,
375-
self.content_width - 2 * border_width,
376-
self.content_height - 2 * border_width,
375+
border_width / 2,
376+
border_width / 2,
377+
self.content_width - border_width,
378+
self.content_height - border_width,
377379
color=border_color,
378380
border_width=border_width,
379381
)

‎arcade/gui/widgets/text.py‎

Lines changed: 31 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
from pyglet.text import LinearGradient
99
from pyglet.text.caret import Caret
1010
from pyglet.text.document import AbstractDocument
11+
from pyglet.text.formats.html import HTMLDecoder
1112
from typing_extensions import override
1213

1314
import arcade
@@ -31,7 +32,7 @@
3132
from arcade.gui.surface import Surface
3233
from arcade.gui.widgets import UIInteractiveWidget, UIWidget
3334
from arcade.gui.widgets.layout import UIAnchorLayout
34-
from arcade.text import FontNameOrNames, _to_text_color
35+
from arcade.text import FontNameOrNames, _to_text_color, _to_weight
3536
from arcade.types import LBWH, RGBA255, Color, RGBOrA255
3637

3738

@@ -825,6 +826,8 @@ class UITextArea(UIWidget):
825826
PLAIN will decode the text as plain text, ATTRIBUTED and HTML will
826827
decode the text as pyglet documents here
827828
https://pyglet.readthedocs.io/en/latest/programming_guide/text.html
829+
With ATTRIBUTED and HTML, styles set in the text win, and the font,
830+
color, bold and italic arguments apply to the rest of it.
828831
**kwargs: passed to :py:class:`~arcade.gui.UIWidget`.
829832
"""
830833

@@ -864,25 +867,36 @@ def __init__(
864867
# Measured in pixels per 'click'
865868
self.scroll_speed = scroll_speed if scroll_speed is not None else font_size
866869

870+
# pyglet 3 reads "weight" and "style", not "bold" and "italic"
871+
text_style = dict(
872+
font_name=font_name,
873+
font_size=font_size,
874+
color=Color.from_iterable(text_color),
875+
weight=_to_weight(bold),
876+
style="italic" if italic else "normal",
877+
)
878+
867879
self.doc: AbstractDocument
868880
if document_mode == "PLAIN":
869881
self.doc = pyglet.text.decode_text(text)
870-
elif document_mode == "ATTRIBUTED":
871-
self.doc = pyglet.text.decode_attributed(text)
872-
elif document_mode == "HTML":
873-
self.doc = pyglet.text.decode_html(text)
874-
875-
self.doc.set_style(
876-
0,
877-
len(text),
878-
dict(
879-
font_name=font_name,
880-
font_size=font_size,
881-
color=Color.from_iterable(text_color),
882-
bold=bold,
883-
italic=italic,
884-
),
885-
)
882+
self.doc.set_style(0, len(self.doc.text), text_style)
883+
else:
884+
if document_mode == "ATTRIBUTED":
885+
self.doc = pyglet.text.decode_attributed(text)
886+
elif document_mode == "HTML":
887+
# The decoder's own defaults (such as Times New Roman) would
888+
# otherwise apply wherever the HTML doesn't set a style
889+
class _Decoder(HTMLDecoder):
890+
default_style = {**HTMLDecoder.default_style, **text_style}
891+
892+
self.doc = _Decoder().decode(text)
893+
else:
894+
raise ValueError(f"Unknown document_mode: {document_mode!r}")
895+
# Styles set in the text win. Only fill in the rest.
896+
for attribute, value in text_style.items():
897+
runs = self.doc.get_style_runs(attribute).ranges(0, len(self.doc.text))
898+
for start, end in [(start, end) for start, end, run in runs if run is None]:
899+
self.doc.set_style(start, end, {attribute: value})
886900

887901
self.layout = pyglet.text.layout.IncrementalTextLayout(
888902
self.doc,
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""A UIFlatButton's border reaches the edge of the button, with no gap (#2868)."""
2+
3+
import pytest
4+
5+
from arcade.gui import Surface, UIFlatButton
6+
7+
BG = (0, 0, 255, 255)
8+
BORDER = (255, 0, 0, 255)
9+
10+
11+
@pytest.mark.parametrize("border_width", [2, 4])
12+
def test_border_has_no_gap(window, border_width):
13+
style = UIFlatButton.UIStyle(bg=BG, border=BORDER, border_width=border_width)
14+
button = UIFlatButton(x=0, y=0, width=100, height=40, style={"normal": style})
15+
surface = Surface(size=(100, 40))
16+
with surface.activate():
17+
button._do_render(surface, force=True)
18+
19+
# One pixel wide column through the middle of the button, from the left edge
20+
data = surface.fbo.read(components=4, viewport=(0, 20, 100, 1))
21+
row = [tuple(data[i : i + 4]) for i in range(0, len(data), 4)]
22+
assert row[:border_width] == [BORDER] * border_width
23+
assert row[border_width] == BG
24+
assert row[-border_width:] == [BORDER] * border_width
25+
assert row[-border_width - 1] == BG

‎tests/unit/gui/test_uistyle.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
from dataclasses import dataclass
22

3+
import pytest
4+
35
import arcade
6+
from arcade.gui import UIFlatButton
47
from arcade.gui.style import UIStyleBase
58
from arcade.types import Color
69

@@ -59,3 +62,15 @@ class DefaultStyleSubclass(DefaultStyle):
5962
assert subject.some_color == arcade.color.GREEN
6063
assert subject.some_str == "Arcade"
6164
assert subject.some_other_str == "is awesome!"
65+
66+
67+
def test_single_style_instead_of_dict_gives_clear_error(window):
68+
# A style for each state is needed, so a single style is rejected clearly (#2817)
69+
with pytest.raises(TypeError, match="dict of styles for each state"):
70+
UIFlatButton(style=UIFlatButton.UIStyle())
71+
72+
73+
def test_suggested_fix_for_single_style_works(window):
74+
normal = UIFlatButton.UIStyle(font_size=20)
75+
button = UIFlatButton(style={**UIFlatButton.DEFAULT_STYLE, "normal": normal})
76+
assert button.get_current_style() is normal
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""UITextArea's style arguments, and styles set in ATTRIBUTED and HTML text (#2441)."""
2+
3+
import arcade
4+
from arcade.gui import UITextArea
5+
6+
RED = arcade.types.Color(255, 0, 0, 255)
7+
BLUE = arcade.types.Color(0, 0, 255, 255)
8+
9+
10+
def test_bold_and_italic(window):
11+
area = UITextArea(text="hello", bold=True, italic=True)
12+
assert area.doc.get_style("weight", 0) == "bold"
13+
assert area.doc.get_style("style", 0) == "italic"
14+
font = area.doc.get_font(0)
15+
assert font.weight == "bold"
16+
assert font.style == "italic"
17+
18+
19+
def test_plain_text_uses_the_arguments(window):
20+
area = UITextArea(text="hello", font_size=20, text_color=BLUE)
21+
assert area.doc.get_style("font_size", 4) == 20
22+
assert area.doc.get_style("color", 4) == BLUE
23+
24+
25+
def test_attributed_text_keeps_its_styles(window):
26+
area = UITextArea(
27+
text="{color (255, 0, 0, 255)}red{color None} blue",
28+
document_mode="ATTRIBUTED",
29+
text_color=BLUE,
30+
font_size=20,
31+
)
32+
assert area.doc.text == "red blue"
33+
# Set in the text
34+
assert area.doc.get_style("color", 0) == RED
35+
# Not set in the text, so the arguments apply
36+
assert area.doc.get_style("color", 5) == BLUE
37+
assert area.doc.get_style("font_size", 0) == 20
38+
39+
40+
def test_html_text_keeps_its_styles(window):
41+
area = UITextArea(
42+
text='<b>bold</b> plain <font color="#ff0000">red</font>',
43+
document_mode="HTML",
44+
font_name=("Arial",),
45+
font_size=20,
46+
text_color=BLUE,
47+
)
48+
assert area.doc.get_style("weight", 0) == "bold"
49+
assert area.doc.get_style("weight", 6) == "normal"
50+
# The arguments replace the HTML decoder's own defaults
51+
assert area.doc.get_style("font_name", 6) == ("Arial",)
52+
assert area.doc.get_style("font_size", 6) == 20
53+
assert area.doc.get_style("color", 6) == BLUE
54+
# A color set in the HTML wins
55+
assert tuple(area.doc.get_style("color", 12)) == tuple(RED)

0 commit comments

Comments
 (0)