Update and improve BBCode in RichTextlabel documentation for Godot 4.0

- Update screenshots for Godot 4.0.
- Document RichTextLabel having its own vertical scrollbar.
- Document `push_[tag]()` and `pop()` functions as a faster alternative
  to BBCode.
- Document threading support and when to use it.
- Document how to escape user input to prevent it from having its
  BBCode tags parsed.
- Document stripping BBCode tags from the text.
- Mention entangled tags not being supported.
- Mention faux bold/italic versus real bold/italic fonts.
- Document `[hint]` and `[dropcap]` BBCode tags.
- Mention animated RichTextEffects pausing when the scene tree is paused
  and how to control this behavior.
- Modify RichTextEffect examples to use the actual default values.
- Add screenshot showcasing how to add a RichTextEffect to the
  Custom Effects inspector property.
- Fix and improve `[pulse]` custom RichTextEffect. This adds an easing parameter
  and makes the target color a multiplier, so that colored text keeps its original
  color while fading in and out.
This commit is contained in:
Hugo Locurcio
2023-03-14 18:44:12 +01:00
parent e61ad46a09
commit 38aea06740
12 changed files with 273 additions and 59 deletions

View File

@@ -9,54 +9,211 @@ Introduction
:ref:`class_Label` nodes are great for displaying basic text, but they have limitations.
If you want to change the color of the text, or its alignment, you can only do that to
the entire label. You can't make a part of the text have another color, or have a part
of the text centered. To get around these limitations you would use a :ref:`class_RichTextLabel`.
of the text centered. To get around these limitations, you would use a :ref:`class_RichTextLabel`.
:ref:`class_RichTextLabel` allows for complex formatting of text using a markup syntax or
the built-in API. It uses BBCodes for the markup syntax, a system of tags that designate
formatting rules for a part of the text. You may be familiar with them if you ever used
forums (also known as `bulletin boards`, hence the "BB" in "BBCode").
Note that the BBCode tags can also be used, to some extent, in the XML source of
Unlike Label, RichTextLabel also comes with its own vertical scrollbar. This
scrollbar is automatically displayed if the text does not fit within the
control's size. The scrollbar can be disabled by unchecking the
**Scroll Active** property in the RichTextLabel inspector.
Note that the BBCode tags can also be used to some extent in the XML source of
the class reference. For more information, see :ref:`doc_class_reference_primer`.
.. seealso::
You can see how BBCode in RichTextLabel works in action using the
`Rich Text Label with BBCode demo project <https://github.com/godotengine/godot-demo-projects/tree/master/gui/rich_text_bbcode>`__.
Using BBCode
------------
By default :ref:`class_RichTextLabel` functions exactly the same as the normal label. It
has the :ref:`property_text <class_RichTextLabel_property_text>` property, which you can
edit to have uniformly formatted text. To be able to use BBCodes and rich text formatting
By default, :ref:`class_RichTextLabel` functions like a normal :ref:`class_Label`.
It has the :ref:`property_text <class_RichTextLabel_property_text>` property, which you can
edit to have uniformly formatted text. To be able to use BBCode for rich text formatting,
you need to turn on the BBCode mode by setting :ref:`bbcode_enabled <class_RichTextLabel_property_bbcode_enabled>`.
After that you can edit the :ref:`text <class_RichTextLabel_property_text>`
property using available tags. Both properties are located in the "Bb Code" section of
the Inspector.
After that, you can edit the :ref:`text <class_RichTextLabel_property_text>`
property using available tags. Both properties are located at the top of the inspector
after selecting a RichTextLabel node.
.. image:: img/bbcodeText.png
.. image:: img/bbcode_in_richtextlabel_inspector.webp
For example, ``BBCode [color=blue]blue[/color]`` would render the word "blue" with
a blue color.
For example, ``BBCode [color=green]test[/color]`` would render the word "test" with
a green color.
.. image:: img/bbcodeDemo.png
.. image:: img/bbcode_in_richtextlabel_basic_example.webp
Most BBCodes consist of 3 parts: the opening tag, the content and the closing tag. The
opening tag delimits the start of the formatted part, and can also carry some
configuration options. Some opening tags, like the ``color`` one shown above, also require
a value to work. The closing tag delimits the end of the formatted part. In some cases
both the closing tag and the content can be omitted.
Most BBCodes consist of 3 parts: the opening tag, the content and the closing
tag. The opening tag delimits the start of the formatted part, and can also
carry some configuration options. Some opening tags, like the ``color`` one
shown above, also require a value to work. Other opening tags may accept
multiple options (separated by spaces within the opening tag). The closing tag
delimits the end of the formatted part. In some cases, both the closing tag and
the content can be omitted.
.. code-block:: none
[tag]content[/tag]
[tag=value]content[/tag]
[tag options]content[/tag]
[tag option1=value1 option2=value2]content[/tag]
[tag][/tag]
[tag]
.. note::
In the Inspector you may notice that after writing in the "BBCode Text" property the
regular "Text" property now has the same text but without BBCodes. Take care not to
edit the regular "Text" property! You will lose the BBCode markup if you do. All changes
to the text must be done using the "BBCode Text".
RichTextLabel doesn't support entangled BBCode tags. For example, instead of
using:
::
[b]bold[i]bold italic[/b]italic[/i]
Use:
::
[b]bold[i]bold italic[/i][/b][i]italic[/i]
.. _doc_bbcode_in_richtextlabel_handling_user_input_safely:
Handling user input safely
--------------------------
In a scenario where users may freely input text (such as chat in a multiplayer
game), you should make sure users cannot use arbitrary BBCode tags that will be
parsed by RichTextLabel. This is to avoid inappropriate use of formatting, which
can be problematic if ``[url]`` tags are handled by your RichTextLabel (as players
may be able to create clickable links to phishing sites or similar).
Using RichTextLabel's ``[lb]`` and/or ``[rb]`` tags, we can replace the opening and/or
closing brackets of any BBCode tag in a message with those escaped tags. This
prevents users from using BBCode that will be parsed as tags  instead, the
BBCode will be displayed as text.
.. figure:: img/bbcode_in_richtextlabel_escaping_user_input.webp
:align: center
:alt: Example of unescaped user input resulting in BBCode injection (2nd line) and escaped user input (3rd line)
Example of unescaped user input resulting in BBCode injection (2nd line) and escaped user input (3rd line)
The above image was created using the following script:
::
extends RichTextLabel
func _ready():
append_chat_line("Player 1", "Hello world!")
append_chat_line("Player 2", "Hello [color=red]BBCode injection[/color] (no escaping)!")
append_chat_line_escaped("Player 2", "Hello [color=red]BBCode injection[/color] (with escaping)!")
# Returns escaped BBCode that won't be parsed by RichTextLabel as tags.
func escape_bbcode(bbcode_text):
# We only need to replace opening brackets to prevent tags from being parsed.
return bbcode_text.replace("[", "[lb]")
# Appends the user's message as-is, without escaping. This is dangerous!
func append_chat_line(username, message):
append_text("%s: [color=green]%s[/color]\n" % [username, message])
# Appends the user's message with escaping.
# Remember to escape both the player name and message contents.
func append_chat_line_escaped(username, message):
append_text("%s: [color=green]%s[/color]\n" % [escape_bbcode(username), escape_bbcode(message)])
Stripping BBCode tags
---------------------
For certain use cases, it can be desired to remove BBCode tags from the string.
This is useful when displaying the RichTextLabel's text in another Control that
does not support BBCode (such as a tooltip):
.. code::
extends RichTextLabel
func _ready():
var regex = RegEx.new()
regex.compile("\\[.*?\\]")
var text_without_tags = regex.sub(text, "", true)
# `text_without_tags` contains the text with all BBCode tags removed.
.. note::
Removing BBCode tags entirely isn't advised for user input, as it can
modify the displayed text without users understanding why part of their
message was removed.
:ref:`Escaping user input <doc_bbcode_in_richtextlabel_handling_user_input_safely>`
should be preferred instead.
Performance
-----------
In most cases, you can use BBCode directly as-is since text formatting is rarely
a heavy task. However, with particularly large RichTextLabels (such as console
logs spanning thousands of lines), you may encounter stuttering during gameplay
when the RichTextLabel's text is updated.
There are several ways to alleviate this:
- Use the ``append_text()`` function instead of appending to the ``text``
property. This function will only parse BBCode for the added text, rather than
parsing BBCode from the entire ``text`` property.
- Use ``push_[tag]()`` and ``pop()`` functions to add tags to RichTextLabel instead of
using BBCode.
- Enable the **Threading > Threaded** property in RichTextLabel. This won't
speed up processing, but it will prevent the main thread from blocking, which
avoids stuttering during gameplay. Only enable threading if it's actually
needed in your project, as threading has some overhead.
.. _doc_bbcode_in_richtextlabel_use_functions:
Using push_[tag]() and pop() functions instead of BBCode
--------------------------------------------------------
If you don't want to use BBCode for performance reasons, you can use functions
provided by RichTextLabel to create formatting tags without writing BBCode in
the text.
Every BBCode tag (including effects) has a ``push_[tag]()`` function (where
``[tag]`` is the tag's name). There are also a few convenience functions
available, such as ``push_bold_italics()`` that combines both ``push_bold()``
and ``push_italics()`` into a single tag. See the
:ref:`RichTextLabel class reference <class_RichTextLabel>` for a complete list of
``push_[tag]()`` functions.
The ``pop()`` function is used to end *any* tag. Since BBCode is a tag *stack*,
using ``pop()`` will close the most recently started tags first.
The following script will result in the same visual output as using
``BBCode [color=green]test [i]example[/i][/color]``:
::
extends RichTextLabel
func _ready():
append_text("BBCode ") # Trailing space separates words from each other.
push_color(Color.GREEN)
append_text("test ") # Trailing space separates words from each other.
push_italics()
append_text("example")
pop() # Ends the tag opened by `push_italics()`.
pop() # Ends the tag opened by `push_color()`.
.. warning::
Do **not** set the ``text`` property directly when using formatting functions.
Appending to the ``text`` property will erase all modifications made to the
RichTextLabel using the ``append_text()``, ``push_[tag]()`` and ``pop()``
functions.
Reference
---------
@@ -138,6 +295,11 @@ Reference
- | ``[url]{link}[/url]``
| ``[url={link}]{text}[/url]``
* - | **hint**
| Creates a tooltip hint that is displayed when hovering the text with the mouse.
Tooltip text should not be quoted (quotes will appear as-is in the tooltip otherwise).
- | ``[hint={tooltip text displayed on hover}]{text}[/hint]``
* - | **img**
| Inserts an image from the ``{path}`` (can be any valid image resource).
| If ``{width}`` is provided, the image will try to fit that width maintaining
@@ -166,6 +328,17 @@ Reference
- ``[font_size={size}]{text}[/font_size]``
* - | **dropcap**
| Use a different font size and color for ``{text}``, while making the tag's contents
span multiple lines if it's large enough.
| A `drop cap <https://www.computerhope.com/jargon/d/dropcap.htm>`__ is typically one
uppercase character, but ``[dropcap]`` supports containing multiple characters.
``margins`` values are comma-separated and can be positive, zero or negative.
Negative top and bottom margins are particularly useful to allow the rest of
the paragraph to display below the dropcap.
- ``[dropcap font_size={size} color={color} margins={left},{top},{right},{bottom}]{text}[/dropcap]``
* - | **opentype_features**
| Enables custom OpenType font features for ``{text}``. Features must be provided as
a comma-separated ``{list}``.
@@ -182,12 +355,14 @@ Reference
- ``[color={code/name}]{text}[/color]``
* - | **bgcolor**
| Draws the color behind ``{text}``. Accepts same values as the ``color`` tag.
| Draws the color behind ``{text}``. This can be used to highlight text.
Accepts same values as the ``color`` tag.
- ``[bgcolor={code/name}]{text}[/bgcolor]``
* - | **fgcolor**
| Draws the color in front of ``{text}``. Accepts same values as the ``color`` tag.
| Draws the color in front of ``{text}``. This can be used to "redact" text by using
an opaque foreground color. Accepts same values as the ``color`` tag.
- ``[fgcolor={code/name}]{text}[/fgcolor]``
@@ -246,15 +421,19 @@ Reference
.. note::
Tags for bold (``[b]``), italics (``[i]``), and monospaced (``[code]``)
formatting only work if the appropriate custom fonts are set up for
the ``RichTextLabel`` node first.
Tags for bold (``[b]``) and italics (``[i]``) formatting work best if the
appropriate custom fonts are set up in the RichTextLabelNode's theme
overrides. If no custom bold or italic fonts are defined,
`faux bold and italic fonts <https://fonts.google.com/knowledge/glossary/faux_fake_pseudo_synthesized>`__
will be generated by Godot. These fonts rarely look good in comparison to hand-made bold/italic font variants.
The monospaced (``[code]``) tag **only** works if a custom font is set up in
the RichTextLabel node's theme overrides. Otherwise, monospaced text will use the regular font.
There are no BBCode tags to control vertical centering of text yet.
Options can be skipped for all tags.
.. _doc_bbcode_in_richtextlabel_paragraph_options:
Paragraph options
@@ -492,7 +671,6 @@ Cell options
Cell background color. For alternating odd/even row backgrounds
you can use ``bg=odd_color,even_color``.
.. _doc_bbcode_in_richtextlabel_list_types:
Ordered list types
@@ -506,48 +684,69 @@ type options:
- ``a``, ``A`` - Lower and upper case Latin letters.
- ``i``, ``I`` - Lower and upper case Roman numerals.
Text effects
------------
Animation effects
-----------------
BBCode can also be used to create different text effects that can optionally be
animated. Five customizable effects are provided out of the box, and you can
easily create your own. By default, animated effects will pause
:ref:`when the SceneTree is paused <doc_pausing_games>`. You can change this
behavior by adjusting the RichTextLabel's **Process > Mode** property.
BBCode can also be used to create different text animation effects. Five customizable
effects are provided out of the box, and you can easily create your own.
All examples below mention the default values for options in the listed tag format.
.. note::
Text effects that move characters' position may result in characters being
clipped by the RichTextLabel node bounds.
You can resolve this by disabling **Control > Layout > Clip Contents** in
the inspector after selecting the RichTextLabel node, or ensuring there is
enough margin added around the text by using line breaks above and below the
line using the effect.
Wave
~~~~
.. image:: img/wave.png
.. image:: img/bbcode_in_richtextlabel_effect_wave.webp
Wave makes the text go up and down. Its tag format is ``[wave amp=50 freq=2][/wave]``.
``amp`` controls how high and low the effect goes, and ``freq`` controls how fast the
text goes up and down.
Wave makes the text go up and down. Its tag format is
``[wave amp=50.0 freq=5.0]{text}[/wave]``.
``amp`` controls how high and low the effect goes, and ``freq`` controls how
fast the text goes up and down. A ``freq`` value of ``0`` will result in no
visible waves, and negative ``freq`` values won't display any waves either.
Tornado
~~~~~~~
.. image:: img/tornado.png
.. image:: img/bbcode_in_richtextlabel_effect_tornado.webp
Tornao makes the text move around in a circle. Its tag format is
``[tornado radius=5 freq=2][/tornado]``.
``[tornado radius=10.0 freq=1.0]{text}[/tornado]``.
``radius`` is the radius of the circle that controls the offset, ``freq`` is how
fast the text moves in a circle.
fast the text moves in a circle. A ``freq`` value of ``0`` will pause the
animation, while negative ``freq`` will play the animation backwards.
Shake
~~~~~
.. image:: img/shake.png
.. image:: img/bbcode_in_richtextlabel_effect_shake.webp
Shake makes the text shake. Its tag format is ``[shake rate=20.0 level=5]{text}[/shake]``.
Shake makes the text shake. Its tag format is ``[shake rate=5 level=10][/shake]``.
``rate`` controls how fast the text shakes, ``level`` controls how far the text is
offset from the origin.
Fade
~~~~
.. image:: img/fade.png
.. image:: img/bbcode_in_richtextlabel_effect_fade.webp
Fade creates a static fade effect that multiplies each character's opacity.
Its tag format is ``[fade start=4 length=14]{text}[/fade]``.
Fade creates a fade effect over the text that is not animated. Its tag format is
``[fade start=4 length=14][/fade]``.
``start`` controls the starting position of the falloff relative to where the fade
command is inserted, ``length`` controls over how many characters should the fade
out take place.
@@ -555,12 +754,20 @@ out take place.
Rainbow
~~~~~~~
.. image:: img/rainbow.png
.. image:: img/bbcode_in_richtextlabel_effect_rainbow.webp
Rainbow gives the text a rainbow color that changes over time. Its tag format is
``[rainbow freq=0.2 sat=10 val=20][/rainbow]``.
``freq`` is the number of full rainbow cycles per second, ``sat`` is the saturation
of the rainbow, ``val`` is the value of the rainbow.
``[rainbow freq=1.0 sat=0.8 val=0.8]{text}[/rainbow]``.
``freq`` is the number of full rainbow cycles per second, ``sat`` is the
saturation of the rainbow, ``val`` is the value of the rainbow. A ``freq`` value
of ``0`` will pause the animation, while negative ``freq`` will play the
animation backwards.
Font outlines are *not* affected by the rainbow effect (they keep their original color).
Existing font colors are overridden by the rainbow effect. However, CanvasItem's
**Modulate** and **Self Modulate** properties will affect how the rainbow effect
looks, as modulation multiplies its final colors.
Custom BBCode tags and text effects
-----------------------------------
@@ -571,13 +778,19 @@ and give the script a ``class_name`` so that the effect can be selected in the i
Add the ``@tool`` annotation to your GDScript file if you wish to have these custom effects
run within the editor itself. The RichTextLabel does not need to have a script attached,
nor does it need to be running in ``tool`` mode. The new effect can be registered in
the Inspector by adding it to the **Custom Effects** array, or in code with the
:ref:`install_effect() <class_RichTextLabel_method_install_effect>` method.
the Inspector by adding it to the **Markup > Custom Effects** array, or in code with the
:ref:`install_effect() <class_RichTextLabel_method_install_effect>` method:
.. figure:: img/bbcode_in_richtextlabel_selecting_custom_richtexteffect.webp
:align: center
:alt: Selecting a custom RichTextEffect after saving a script that extends RichTextEffect with a ``class_name``
Selecting a custom RichTextEffect after saving a script that extends RichTextEffect with a ``class_name``
.. warning::
If the custom effect is not registered within the RichTextLabel's
**Custom Effects** property, no effect will be visible and the original
**Markup > Custom Effects** property, no effect will be visible and the original
tag will be left as-is.
There is only one function that you need to extend: ``_process_custom_fx(char_fx)``.
@@ -649,24 +862,25 @@ Pulse
extends RichTextEffect
class_name RichTextPulse
# Syntax: [pulse color=#00FFAA height=0.0 freq=2.0][/pulse]
# Syntax: [pulse color=#ffffff33 freq=1.0 ease=-2.0 height=0][/pulse]
# Define the tag name.
var bbcode = "pulse"
func _process_custom_fx(char_fx):
# Get parameters, or use the provided default value if missing.
var color = char_fx.env.get("color", char_fx.color)
var height = char_fx.env.get("height", 0.0)
var freq = char_fx.env.get("freq", 2.0)
var color = Color(char_fx.env.get("color", Color(1, 1, 1, 0.2)))
var freq = char_fx.env.get("freq", 1.0)
var param_ease = char_fx.env.get("ease", -2.0)
var height = char_fx.env.get("height", 0)
var sined_time = (sin(char_fx.elapsed_time * freq) + 1.0) / 2.0
var sined_time = (ease(pingpong(char_fx.elapsed_time, 1.0 / freq) * freq, param_ease))
var y_off = sined_time * height
color.a = 1.0
char_fx.color = char_fx.color.lerp(color, sined_time)
char_fx.color = char_fx.color.lerp(char_fx.color * color, sined_time)
char_fx.offset = Vector2(0, -1) * y_off
return true
Matrix
~~~~~~

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 950 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 684 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB