ui: emoji in labels (#39370)

This commit is contained in:
Adeeb Shihadeh
2026-11-28 16:40:52 -06:00
committed by firestar5683
parent d936d2ad41
commit d6e5a2155b
9 changed files with 413 additions and 2 deletions
+1
View File
@@ -5,6 +5,7 @@
openpilot/selfdrive/modeld/models/big_*_tinygrad.pkl -text
*.svg -text
*.png -text
openpilot/selfdrive/assets/emoji.npz -text
*.gif -text
*.ttf -text
*.otf -text
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env python3
# Builds emoji.npz from Noto Color Emoji's 72px PNGs and region flags: uv run --with pillow build_emoji.py
import subprocess
import tempfile
import zipfile
from pathlib import Path
import numpy as np
from PIL import Image
NOTO_EMOJI = "https://github.com/googlefonts/noto-emoji.git"
COMMIT = "99701e07d3d1fe1bdbcdb14964547f0fd592966f"
OUT = Path(__file__).parent / "emoji.npz"
def main():
with tempfile.TemporaryDirectory() as tmp:
src = Path(tmp)
git = ["git", "-C", tmp]
subprocess.run(["git", "init", "-q", tmp], check=True)
subprocess.run([*git, "sparse-checkout", "set", "2D/png/72", "third_party/region-flags/png"], check=True)
subprocess.run([*git, "fetch", "-q", "--depth", "1", "--filter=blob:none", NOTO_EMOJI, COMMIT], check=True)
subprocess.run([*git, "checkout", "-q", "FETCH_HEAD"], check=True)
arrays: dict[str, np.ndarray] = {}
for f in sorted((src / "2D/png/72").glob("emoji_u*.png")):
key = f.stem.removeprefix("emoji_u")
codepoints = [int(c, 16) for c in key.split("_")]
# digits, # and * are always text, and only the default skin tone ships
if len(codepoints) == 1 and codepoints[0] < 0x2000 and codepoints[0] not in (0xA9, 0xAE):
continue
if any(0x1F3FB <= c <= 0x1F3FF for c in codepoints):
continue
arrays[key] = np.asarray(Image.open(f).convert("RGBA"))
# flags are pairs of regional indicators, one per letter of the country code
for f in sorted((src / "third_party/region-flags/png").glob("??.png")):
img = Image.open(f).convert("RGBA")
img = img.resize((72, max(1, round(72 * img.height / img.width))), Image.Resampling.LANCZOS)
arrays["_".join(f"{0x1F1E6 + ord(c) - ord('A'):x}" for c in f.stem)] = np.asarray(img)
# same layout as np.savez_compressed, which np.load reads one array at a time
with zipfile.ZipFile(OUT, "w", zipfile.ZIP_DEFLATED) as z:
for key, array in arrays.items():
with z.open(f"{key}.npy", "w") as f:
np.lib.format.write_array(f, array)
print(f"{len(arrays)} emoji, {OUT.stat().st_size / 1e6:.1f} MB")
if __name__ == "__main__":
main()
@@ -0,0 +1,56 @@
== Copying ==
The flags in this package were downloaded from Wikipedia and checked to be in
Public Domain or otherwise exempt from Copyright. In particular, the following
are not explicitly tagged as "public_domain" or were tagged according to some
national law which made them Public Domain in that nation (e.g. `{{PD-AM-exempt}}`)
AM https://commons.wikimedia.org/wiki/File:Flag_of_Armenia.svg
AZ https://commons.wikimedia.org/wiki/File:Flag_of_Azerbaijan.svg
JE https://commons.wikimedia.org/wiki/File:Flag_of_Jersey.svg
KG https://commons.wikimedia.org/wiki/File:Flag_of_Kyrgyzstan.svg
KZ https://commons.wikimedia.org/wiki/File:Flag_of_Kazakhstan.svg
MD https://commons.wikimedia.org/wiki/File:Flag_of_Moldova.svg
MX https://commons.wikimedia.org/wiki/File:Flag_of_Mexico.svg
MY https://commons.wikimedia.org/wiki/File:Flag_of_Malaysia.svg
RS https://commons.wikimedia.org/wiki/File:Flag_of_Serbia.svg
YT https://commons.wikimedia.org/wiki/File:Flag_of_Mayotte_(local).svg
US-SD https://commons.wikimedia.org/wiki/File:Flag_of_South_Dakota.svg
US-UT https://commons.wikimedia.org/wiki/File:Flag_of_Utah.svg
MX-AGU https://commons.wikimedia.org/wiki/File:Flag_of_Aguascalientes.svg
MX-BCN https://commons.wikimedia.org/wiki/File:Flag_of_Baja_California.svg
MX-BCS https://commons.wikimedia.org/wiki/File:Flag_of_Baja_California_Sur.svg
MX-CAM https://commons.wikimedia.org/wiki/File:Flag_of_Campeche.svg
MX-CHH https://commons.wikimedia.org/wiki/File:Flag_of_Chihuahua.svg
MX-CHP https://commons.wikimedia.org/wiki/File:Flag_of_Chiapas.svg
MX-CMX https://commons.wikimedia.org/wiki/File:Flag_of_Mexican_Federal_District.svg
MX-COA https://commons.wikimedia.org/wiki/File:Flag_of_Coahuila.svg
MX-COL https://commons.wikimedia.org/wiki/File:Flag_of_Colima.svg
MX-DUR https://commons.wikimedia.org/wiki/File:Flag_of_Durango.svg
MX-GRO https://commons.wikimedia.org/wiki/File:Flag_of_Guerrero.svg
MX-GUA https://commons.wikimedia.org/wiki/File:Flag_of_Guanajuato.svg
MX-HID https://commons.wikimedia.org/wiki/File:Flag_of_Hidalgo.svg
MX-JAL https://commons.wikimedia.org/wiki/File:Flag_of_Jalisco.svg
MX-MEX https://commons.wikimedia.org/wiki/File:Flag_of_México.svg
MX-MIC https://commons.wikimedia.org/wiki/File:Flag_of_Michoacan.svg
MX-MOR https://commons.wikimedia.org/wiki/File:Flag_of_Morelos.svg
MX-NAY https://commons.wikimedia.org/wiki/File:Flag_of_Nayarit.svg
MX-NLE https://commons.wikimedia.org/wiki/File:Flag_of_Nuevo_Leon.svg
MX-OAX https://commons.wikimedia.org/wiki/File:Flag_of_Oaxaca.svg
MX-PUE https://commons.wikimedia.org/wiki/File:Flag_of_Puebla.svg
MX-QUE https://commons.wikimedia.org/wiki/File:Flag_of_Queretaro.svg
MX-ROO https://commons.wikimedia.org/wiki/File:Flag_of_Quintana_Roo.svg
MX-SIN https://commons.wikimedia.org/wiki/File:Flag_of_Sinaloa.svg
MX-SLP https://commons.wikimedia.org/wiki/File:Flag_of_San_Luis_Potosi.svg
MX-SON https://commons.wikimedia.org/wiki/File:Flag_of_Sonora.svg
MX-TAB https://commons.wikimedia.org/wiki/File:Flag_of_Tabasco.svg
MX-TAM https://commons.wikimedia.org/wiki/File:Flag_of_Tamaulipas.svg
MX-TLA https://commons.wikimedia.org/wiki/File:Flag_of_Tlaxcala.svg
MX-VER https://commons.wikimedia.org/wiki/File:Flag_of_Veracruz.svg
MX-YUC https://commons.wikimedia.org/wiki/File:Flag_of_Yucatan.svg
MX-ZAC https://commons.wikimedia.org/wiki/File:Flag_of_Zacatecas.svg
For individual details, revision history, and information on contributors, see
files in `html/`.
@@ -0,0 +1,208 @@
Noto Emoji images in emoji.npz
Copyright Google LLC and the Noto Emoji contributors.
Source: https://github.com/googlefonts/noto-emoji/tree/99701e07d3d1fe1bdbcdb14964547f0fd592966f/2D/png/72
The images were packaged as RGBA arrays without changing the emoji artwork.
Regional flag notices are in emoji-FLAGS-LICENSE.txt.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Binary file not shown.
+6
View File
@@ -241,6 +241,7 @@ class GuiApplication:
self._fonts: dict[FontWeight, rl.Font] = {}
self._fallback_fonts: dict[str, rl.Font] = {}
self._font_chars: set[str] = set()
self._width = width if width is not None else GuiApplication._default_width()
self._height = height if height is not None else GuiApplication._default_height()
@@ -815,6 +816,10 @@ class GuiApplication:
def font(self, font_weight: FontWeight = FontWeight.NORMAL) -> rl.Font:
return self._fonts[font_weight]
@property
def font_chars(self) -> set[str]:
return self._font_chars
def fallback_font(self) -> rl.Font:
language = multilang.language
if language not in self._fallback_fonts:
@@ -848,6 +853,7 @@ class GuiApplication:
if code not in FONT_FALLBACK_LANGUAGES:
base_chars.update(TRANSLATIONS_DIR.joinpath(f"app_{code}.po").read_text(encoding="utf-8"))
self._font_chars = base_chars
for font_weight_file in FontWeight:
with as_file(FONT_DIR) as fspath:
unifont = font_weight_file == FontWeight.UNIFONT
+64
View File
@@ -0,0 +1,64 @@
import functools
from importlib.resources import as_file
import numpy as np
from openpilot.starpilot.ui.raylib import rl
from openpilot.system.ui.lib.application import ASSETS_DIR
# Noto Color Emoji at 72px (default skin tone) and region flags, as RGBA arrays keyed by codepoints ("1f468_200d_1f469").
# Built by selfdrive/assets/build_emoji.py. Fonts can't draw color, so labels draw these over placeholder characters instead
EMOJI_FILE = "emoji.npz"
PLACEHOLDER = 0xE000 # private use area
_textures: dict[str, rl.Texture] = {}
@functools.cache
def _archive() -> np.lib.npyio.NpzFile:
with as_file(ASSETS_DIR.joinpath(EMOJI_FILE)) as path:
return np.load(path) # reads each emoji on first use
@functools.cache
def _emoji() -> dict[str, str]:
return {"".join(chr(int(c, 16)) for c in key.split("_")): key for key in _archive().files}
def replace_emoji(text: str, font_chars: set[str]) -> tuple[str, dict[str, str]]:
"""Swaps each emoji for two placeholder characters, which take up about an emoji's width.
Returns the new text and the emoji to draw for each placeholder."""
if font_chars.issuperset(text):
return text, {}
emoji = _emoji()
max_len = max(map(len, emoji))
found: dict[str, str] = {}
out = []
i = 0
while i < len(text):
for n in range(min(max_len * 2, len(text) - i), 0, -1):
seq = text[i:i + n]
key = "".join(ch for ch in seq if ch != "️" and not 0x1F3FB <= ord(ch) <= 0x1F3FF)
# a character we can draw as text stays text, unless it asks for emoji style
if key in emoji and (len(key) > 1 or key not in font_chars or "️" in seq):
placeholder = chr(PLACEHOLDER + len(found))
found[placeholder] = emoji[key]
out.append(placeholder * 2)
i += n
break
else:
# skip emoji style selectors and skin tones (only the default tone ships)
if text[i] != "️" and not 0x1F3FB <= ord(text[i]) <= 0x1F3FF:
out.append(text[i])
i += 1
return "".join(out), found
def emoji_texture(key: str) -> rl.Texture:
if key not in _textures:
rgba = np.ascontiguousarray(_archive()[key])
texture = rl.load_texture_from_image(rl.Image(None, rgba.shape[1], rgba.shape[0], 1, rl.PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8))
rl.update_texture(texture, rgba)
rl.set_texture_filter(texture, rl.TextureFilter.TEXTURE_FILTER_BILINEAR)
_textures[key] = texture
return _textures[key]
+26 -1
View File
@@ -9,6 +9,7 @@ from openpilot.system.ui.lib.application import (
)
from openpilot.system.ui.widgets import Widget
from openpilot.system.ui.lib.text_measure import measure_text_cached
from openpilot.system.ui.lib.emoji import emoji_texture, replace_emoji
from openpilot.system.ui.lib.wrap_text import wrap_text
from openpilot.system.ui.lib.multilang import tr_display
from openpilot.system.ui.lib.display_translation import native_text
@@ -267,6 +268,7 @@ class UnifiedLabel(Widget):
# Cached data
self._cached_text: str | None = None
self._emoji: dict[str, str] = {}
self._cached_wrapped_lines: list[str] = []
self._cached_line_sizes: list[rl.Vector2] = []
self._cached_total_height: float | None = None
@@ -373,6 +375,7 @@ class UnifiedLabel(Widget):
self._cached_text = text
self._cached_font_id = font_id
self._cached_width = available_width
text, self._emoji = replace_emoji(text, gui_app.font_chars)
# Determine wrapping width
content_width = available_width - (self._text_padding * 2)
@@ -624,7 +627,9 @@ class UnifiedLabel(Widget):
line_x = self._rect.x + self._text_padding
line_x += self._scroll_offset + x_offset
if self._shimmer:
if self._emoji:
self._render_line_emoji(line, line_x, current_y)
elif self._shimmer:
self._render_line_shimmer(line, line_x, current_y)
else:
self._render_line_normal(line, line_x, current_y)
@@ -633,6 +638,26 @@ class UnifiedLabel(Widget):
line_pos = rl.Vector2(line_x, current_y)
rl.draw_text_ex(self._font, line, line_pos, self._font_size, self._spacing_pixels, self._text_color)
def _render_line_emoji(self, line, line_x, current_y):
# draw text runs, and each emoji centered over its two placeholders
line_height = self._font_size * FONT_SCALE
i = 0
while i < len(line):
is_emoji = line[i] in self._emoji
j = i + 1
while j < len(line) and not is_emoji and line[j] not in self._emoji:
j += 1
x = line_x + (measure_text_cached(self._font, line[:i], self._font_size, self._spacing_pixels).x + self._spacing_pixels if i else 0)
if not is_emoji:
rl.draw_text_ex(self._font, line[i:j], rl.Vector2(x, current_y), self._font_size, self._spacing_pixels, self._text_color)
elif line[i - 1:i] != line[i]:
width = measure_text_cached(self._font, line[i] * 2, self._font_size, self._spacing_pixels).x
texture = emoji_texture(self._emoji[line[i]])
scale = min(width, line_height * 0.85) / max(texture.width, texture.height)
pos = rl.Vector2(x + (width - texture.width * scale) / 2, current_y + (line_height - texture.height * scale) / 2)
rl.draw_texture_ex(texture, pos, 0.0, scale, rl.Color(255, 255, 255, self._text_color.a))
i = j
def _render_line_shimmer(self, line, line_x, current_y):
# Shimmer range based on widest line so sweep is even across all lines
max_width = self.text_width
+1 -1
View File
@@ -1 +1 @@
{"protected_inventory_sha256": "e2a86d07b2fbe2cc22601c17cc04f930a698bec511846f2996525f63c417ac9e", "schema_version": 1}
{"protected_inventory_sha256": "eb7213db70dcdcd2251b994d591c92df37423d8c09d8f8fd94e04d3c3bc1f80d", "schema_version": 1}