Use native heart fallback by narrowing bundled Inter coverage

Signed-off-by: Tom Brow <tomb@block.xyz>
This commit is contained in:
Tom Brow
2026-09-23 17:33:59 -07:00
parent d9a5bdd6e9
commit 965d7027c2
8 changed files with 210 additions and 27 deletions

View File

@@ -0,0 +1,46 @@
# Inter heart fallback
The two Inter 4.001 variable fonts are derived from the previously bundled
fonts by removing only U+2764 from their Unicode character maps. Flutter can
then choose a native font for heart characters, including emoji presentation
in reactions and message text. No glyphs, language coverage, other symbols,
font metrics, or variation tables are removed. The license remains in
`Inter-LICENSE.txt`.
To reproduce from the repository root:
```sh
mkdir -p /tmp/buzz-inter-source
for font in InterVariable.ttf InterVariable-Italic.ttf; do
git show ec7ea38f62ea917f15e85a678bc94f3bbee5bb64:mobile/assets/fonts/$font > /tmp/buzz-inter-source/$font
done
python3 -m venv /tmp/buzz-inter-tools
/tmp/buzz-inter-tools/bin/pip install fonttools==4.60.1
/tmp/buzz-inter-tools/bin/python mobile/scripts/prepare-inter.py /tmp/buzz-inter-source
/tmp/buzz-inter-tools/bin/python mobile/scripts/prepare-inter.py /tmp/buzz-inter-source --check
```
The script checks pristine source hashes and verifies every character mapping
and every other font table. Only the `cmap` table and the font checksum may
change. Repeated generation from the same sources produces identical bytes.
Warning signs, ©, ®, ™, arrows, math symbols, accents, and supported languages
keep their original Inter mappings.
Use `test/visual/heart_sim_app.dart` on an actual iOS simulator to compare
reactions, plain/emoji/text-presentation hearts, bold/italic message text,
warning signs, and preserved symbols. Font fallback for plain and explicit
text-presentation hearts is platform-dependent; do not infer their appearance
from a macOS widget-test renderer. On iOS 26.5, all three heart presentations
fall back to the color emoji, including explicit VS15. Message line metrics
can change with the fallback font.
The native screenshot regression check (requires Pillow) covers both reaction
states, each message-heart presentation, bold/italic text, and unchanged warning
signs and symbols:
```sh
python3 mobile/test/visual/verify_heart_screenshots.py before.png after.png
```
Use original 1206×2622 captures from the documented simulator and fixture for
this check. PR images may be cropped afterward for readability.

View File

@@ -31,13 +31,7 @@ class NativeEmojiGlyph extends StatelessWidget {
maxLines: 1,
softWrap: false,
textScaler: TextScaler.noScaling,
// Inter contains a monochrome heart, so emoji fonts must take priority.
style: TextStyle(
fontFamily: 'Apple Color Emoji',
fontFamilyFallback: const ['Noto Color Emoji', 'Segoe UI Emoji'],
fontSize: size,
height: 1,
),
style: TextStyle(fontSize: size, height: 1),
);
if (defaultTargetPlatform == TargetPlatform.iOS) {
glyph = Transform.translate(offset: const Offset(0, -1), child: glyph);

View File

@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Remove only Inter's U+2764 mapping so hearts use native font fallback.
Requires fonttools==4.60.1. See assets/fonts/README.md for source and commands.
"""
import argparse
import hashlib
from pathlib import Path
from fontTools.ttLib import TTFont
SOURCES = {
"InterVariable.ttf": "4989b125924991b90d05b2d16e0e388c48f7d5bb8b30539bbf9c755278d0ccaf",
"InterVariable-Italic.ttf": "d6f1f6a172d9e588438db9f986fd5cfad7b30f644374080a8a9d4d91e344586f",
}
HEART = 0x2764
def verify(source: Path, output: Path) -> None:
with TTFont(source, lazy=True) as before, TTFont(output, lazy=True) as after:
if set(before.reader.keys()) != set(after.reader.keys()):
raise ValueError("Font tables changed")
for tag in before.reader.keys():
original, modified = before.reader[tag], after.reader[tag]
if tag == "cmap":
continue
if tag == "head":
# The only allowed header change is the whole-font checksum.
original = original[:8] + original[12:]
modified = modified[:8] + modified[12:]
if original != modified:
raise ValueError(f"Unexpected change to {tag}")
old_tables, new_tables = before["cmap"].tables, after["cmap"].tables
if len(old_tables) != len(new_tables):
raise ValueError("Character-map table count changed")
for old, new in zip(old_tables, new_tables, strict=True):
identity = lambda t: (t.format, t.platformID, t.platEncID, t.language)
if identity(old) != identity(new):
raise ValueError("Character-map identity changed")
expected = dict(old.cmap)
if old.isUnicode():
del expected[HEART]
if new.cmap != expected:
raise ValueError("Character mappings changed beyond U+2764")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source_dir", type=Path)
parser.add_argument("--output-dir", type=Path, default=Path(__file__).resolve().parents[1] / "assets/fonts")
parser.add_argument("--check", action="store_true", help="Verify existing output without writing")
args = parser.parse_args()
for name, digest in SOURCES.items():
source, output = args.source_dir / name, args.output_dir / name
if source.resolve() == output.resolve():
raise ValueError("Keep pristine sources separate from generated fonts")
if hashlib.sha256(source.read_bytes()).hexdigest() != digest:
raise ValueError(f"Unexpected source font: {name}")
if not args.check:
with TTFont(source, lazy=True, recalcTimestamp=False) as font:
tables = [t for t in font["cmap"].tables if t.isUnicode()]
if not tables or any(HEART not in t.cmap for t in tables):
raise ValueError(f"Expected heart mapping in {name}")
# FontTools shares dictionaries between equivalent subtables.
for cmap in {id(t.cmap): t.cmap for t in tables}.values():
del cmap[HEART]
args.output_dir.mkdir(parents=True, exist_ok=True)
font.save(output, reorderTables=False)
verify(source, output)
print(f"{name}: only U+2764 mapping removed; other mappings and glyph data unchanged")
if __name__ == "__main__":
main()

View File

@@ -95,25 +95,6 @@ class _FakeUserCacheNotifier extends UserCacheNotifier {
void main() {
group('ReactionRow', () {
testWidgets(
'heart reactions prefer a color font without recoloring counts',
(tester) async {
await _pumpRow(tester, reactions: [_reaction(emoji: '❤️', count: 5)]);
final heart = tester.widget<Text>(find.text('❤️'));
final count = tester.widget<Text>(find.text('5'));
expect(heart.style?.fontFamily, 'Apple Color Emoji');
expect(heart.style?.fontFamilyFallback, [
'Noto Color Emoji',
'Segoe UI Emoji',
]);
expect(count.style?.fontFamily, 'Inter');
expect(
tester.getSize(find.byKey(const ValueKey('reaction-pill-❤️'))).height,
28,
);
},
);
testWidgets('shows the count even at one, matching desktop', (
tester,
) async {

View File

@@ -1,3 +1,5 @@
import 'package:buzz/features/channels/message_content.dart';
import 'package:buzz/shared/custom_emoji/custom_emoji_provider.dart';
import 'package:buzz/features/channels/reaction_row.dart';
import 'package:buzz/features/channels/timeline_message.dart';
import 'package:buzz/shared/theme/theme.dart';
@@ -9,6 +11,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
// xcrun simctl io <simulator> screenshot <path>
void main() => runApp(
ProviderScope(
overrides: [customEmojiListProvider.overrideWithValue(const [])],
child: MaterialApp(
debugShowCheckedModeBanner: false,
theme: AppTheme.light(),
@@ -20,13 +23,27 @@ void main() => runApp(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 24),
const Text('Reaction rendering'),
const Text('Hearts and text rendering'),
const SizedBox(height: 24),
const Text('Selected'),
_reactions(true),
const SizedBox(height: 24),
const Text('Unselected'),
_reactions(false),
const SizedBox(height: 24),
const Text('Message text'),
const SizedBox(height: 8),
_message('Plain ❤ Emoji ❤️ Text ❤︎'),
_message('**Bold ❤️** *Italic ❤️*'),
_message('Warnings: ⚠ ⚠️ ⚠︎'),
const SizedBox(height: 16),
const Text('Preserved symbols and text'),
const SizedBox(height: 8),
_message('© ® ™ ↑ ↓ − ∕ • … café naïve'),
_message('Ελληνικά · Кириллица · Tiếng Việt'),
const SizedBox(height: 16),
const Text('Emoji-only message'),
_message('❤️'),
],
),
),
@@ -49,3 +66,8 @@ Widget _reactions(bool selected) => ReactionRow(
],
onToggle: (_) {},
);
Widget _message(String content) => MessageContent(
content: content,
channelNames: const {'general': 'general'},
);

View File

@@ -0,0 +1,64 @@
#!/usr/bin/env python3
"""Check native captures of heart_sim_app.dart on iPhone 17 Pro, iOS 26.5.
Usage: python verify_heart_screenshots.py before.png after.png
Requires Pillow. Inputs are original 1206x2622 simctl screenshots, not PR crops.
"""
import sys
from PIL import Image, ImageChops
def red_pixels(image, box):
left, top, right, bottom = box
return [
(x, y)
for y in range(top, bottom)
for x in range(left, right)
if is_red(image.getpixel((x, y)))
]
def is_red(color):
red, green, blue = color
return red > 140 and red > green * 1.5 and red > blue * 1.5
def main():
before, after = [Image.open(path).convert("RGB") for path in sys.argv[1:]]
assert before.size == after.size == (1206, 2622), "Use the documented simulator and fixture"
regions = {
"selected reaction": (95, 522, 150, 606),
"unselected reaction": (95, 744, 150, 828),
"plain message heart": (175, 980, 225, 1035),
"emoji-presentation message heart": (375, 980, 435, 1035),
# Native iOS fallback currently renders VS15 as a color heart too.
"text-presentation message heart": (550, 980, 620, 1035),
"bold message heart": (170, 1040, 220, 1090),
"italic message heart": (355, 1040, 425, 1090),
"emoji-only message": (65, 1490, 125, 1545),
}
for name, box in regions.items():
assert not red_pixels(before, box), f"{name}: original must reproduce monochrome heart"
pixels = red_pixels(after, box)
assert len(pixels) > 500, f"{name}: expected native red heart"
if "reaction" in name:
center = (min(y for _, y in pixels) + max(y for _, y in pixels)) / 2
pill_center = (box[1] + box[3] - 1) / 2
assert abs(center - pill_center) <= 1.5, f"{name}: heart is not centered"
print(f"PASS: {name}")
# The two preceding message lines gain one logical pixel each from the
# fallback font's metrics. Compare unchanged text after that translation.
for name, box in {
"warning signs": (65, 1090, 1000, 1145),
"preserved symbols and languages": (65, 1260, 1100, 1385),
}.items():
shifted = (box[0], box[1] + 6, box[2], box[3] + 6)
difference = ImageChops.difference(before.crop(box), after.crop(shifted))
assert difference.getbbox() is None, f"{name}: unexpected rendering change"
print(f"PASS: {name} is pixel-identical")
if __name__ == "__main__":
main()