Files
romm/backend/utils/images.py
Sam Dornan 6d9438b456 Add an opt-in setting to show the game logo in place of the title on the v2 game page (#4888)
* Show the scraped game logo in place of the title on the v2 game page

When a ROM has a ScreenScraper wheel (ss_metadata.logo_path), the details
header renders it inside the h1, with the game name as alt text, and falls
back to the text title when there is no logo or it fails to load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Trim the transparent border off stored game logos

ScreenScraper wheels often sit on a padded 1024x512 canvas, so a logo shown
in place of the game title looked indented and smaller than its neighbours.
store_metadata_media now crops each logo to its visible pixels, including
logos already on disk, so a rescan fixes existing libraries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Put the logo-as-title display behind a UI setting, off by default

Adds a showLogoTitle entry to useUISettings (synced to the user's
ui_settings like the other display preferences) and a 'Show logo as
title' toggle in the Gallery section of the User Interface settings, with
the new strings translated in every locale. GameHeader shows the logo only
when the setting is on. Also clears the existing em-dashes from
UserInterface.vue comments, which the lint rule flags once the file changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Outline the title logo so dark or light lettering stays readable

Some ScreenScraper wheels carry thin black text (A Link to the Past's
subtitle) that vanished on the dark theme, and white lettering has the same
problem on the light one. The logo now gets a 1px rim in the theme's text
colour, replacing the soft drop shadow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Size the title logo by area so square logos match wide ones

A shared 128px height cap left near-square wheels (A Link to the Past,
Aria of Sorrow) with about half the area of wide ones. Once the logo loads,
GameHeader now sets its width so every logo covers roughly the same area
(40,000 px, 22,000 on phones), within a 176px (120px) height cap and the
existing 420px width cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* pr-ready step 2 (code-review): harden logo trimming and logo retry

- Share one IMAGE_DECODE_ERRORS tuple (adds SyntaxError and
  DecompressionBombError) across the image helpers, so a broken or
  oversized logo no longer aborts store_metadata_media.
- Trim under the per-file lock and replace the file atomically, so a failed
  save keeps the original and a hardlinked source is never cropped.
- Skip every multi-frame image, and crop in the image's own mode so palette
  logos stay compact.
- Reset the header's logo failure and ratio whenever the logo URL changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* pr-ready step 3 (simplify): share the resource URL helper, trim dead code

- Add versionedResourceUrl to v2/utils/romFiles and use it from GameHeader,
  romArtwork and ManualSubtab, so the scraped-media cache-bust rule has one
  home.
- Key the header's logo load state on the URL (failedSrc, loadedLogo)
  instead of resetting two refs from a watch; hoist the shared 420px cap.
- Drop logo CSS the inline sizing made dead (display, height, object-fit,
  object-position).
- Read the alpha bbox with getbbox instead of a full RGBA copy, and check
  transparency before counting frames.
- Use a handler fixture in TestTrimTransparentBorder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* pr-ready step 4 (review-polish): drop a filler comment

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* pr-ready step 5 (humanizer): state three comments directly

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

* Bound logo trimming by pixel count and test phone logo sizing

- Skip trimming a logo above MAX_TRIM_PIXELS (16M), checked from the image
  header before any pixel is decoded, so a large download under Pillow's
  decompression-bomb threshold can't exhaust worker memory mid-scan.
- Cover the xs area and height cap in GameHeader's sizing tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015vP3HFKWQsJZv9F9SKeAWu

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 15:01:30 -05:00

76 lines
2.5 KiB
Python

from collections.abc import Callable
from PIL import Image, ImageSequence
# Multi-frame formats browsers play as animations (MPO/TIFF pages are not)
ANIMATED_FORMATS = frozenset({"GIF", "PNG", "WEBP"})
# Pixels decoded across all frames past which an animation keeps only its
# first frame, since re-encoding one holds every frame in memory.
MAX_ANIMATION_PIXELS = 100_000_000
# Largest image a logo trim decodes; real wheels are about half a million pixels.
MAX_TRIM_PIXELS = 16_000_000
# Largest loop count a WebP animation can store
_MAX_WEBP_LOOP = 0xFFFF
# What Pillow raises for an undecodable image: a broken PNG chunk is a
# SyntaxError, and an oversized canvas is refused before any pixel is read.
IMAGE_DECODE_ERRORS = (OSError, SyntaxError, ValueError, Image.DecompressionBombError)
def is_animated(img: Image.Image) -> bool:
"""True for a multi-frame image that browsers play as an animation."""
n_frames = getattr(img, "n_frames", 1)
return (
img.format in ANIMATED_FORMATS
and 1 < n_frames
and n_frames * img.width * img.height <= MAX_ANIMATION_PIXELS
)
def frame_durations(
img: Image.Image, on_frame: Callable[[Image.Image], None] | None = None
) -> list[float] | None:
"""Display time in milliseconds of each frame, leaving img on its first frame.
Args:
on_frame: Called with each frame once decoded.
Returns:
None for a still image, or an animation that fails to decode or
outgrows MAX_ANIMATION_PIXELS.
"""
if not is_animated(img):
return None
durations: list[float] = []
pixels = 0
try:
for frame in ImageSequence.Iterator(img):
# Counted per frame since a GIF canvas can grow mid-animation
pixels += frame.width * frame.height
if pixels > MAX_ANIMATION_PIXELS:
return None
# WebP only fills in a frame's duration once the frame is decoded
frame.load()
if on_frame:
on_frame(frame)
durations.append(frame.info.get("duration", 0))
except IMAGE_DECODE_ERRORS:
return None
finally:
img.seek(0)
return durations
def webp_loop(img: Image.Image) -> int:
"""WebP loop count (0 is forever) that plays img as often as browsers do."""
loop = img.info.get("loop")
if img.format != "GIF":
return loop or 0
# A GIF counts replays after the first play, and plays once without a count
if loop is None:
return 1
return min(loop + 1, _MAX_WEBP_LOOP) if loop else 0