This commit is contained in:
wittmannzl103469 committed 2026-11-05 15:08:42 +01:00
1 parent de41a02749
commit 9af09cebd3
764 files changed
+54218 -78859

No files matched your search

@@ -1,4 +1,4 @@
# pygame-ce - Python Game Library
# pygame - Python Game Library
# Copyright (C) 2000-2003 Pete Shinners
#
# This library is free software; you can redistribute it and/or
@@ -19,16 +19,19 @@
# pete@shinners.org
"""sysfont, used in the font module to find system fonts"""
import difflib
import itertools
import os
import sys
import warnings
from os.path import basename, dirname, exists, join, splitext
from pygame import __file__ as pygame_main_file
from pygame.font import Font
if sys.platform != "emscripten":
if os.name == "nt":
import winreg as _winreg
import subprocess
OpenType_extensions = frozenset((".ttf", ".ttc", ".otf"))
Sysfonts = {}
Sysalias = {}
@@ -51,7 +54,6 @@ def _addfont(name, bold, italic, font, fontdict):
def initsysfonts_win32():
"""initialize fonts dictionary on Windows"""
import winreg as _winreg
fontdir = join(os.environ.get("WINDIR", "C:\\Windows"), "Fonts")
fonts = {}
@@ -77,12 +79,6 @@ def initsysfonts_win32():
except OSError:
break
# https://github.com/pygame-community/pygame-ce/issues/3742
# Registry values could be other types besides strings.
# Lets skip those.
if not isinstance(font, str):
continue
if splitext(font)[1].lower() not in OpenType_extensions:
continue
if not dirname(font):
@@ -91,8 +87,7 @@ def initsysfonts_win32():
# Some are named A & B, both names should be processed separately
# Ex: the main Cambria file is marked as "Cambria & Cambria Math"
for name in name.split("&"):
if os.path.exists(font): # check if the file actually exists
_parse_font_entry_win(name, font, fonts)
_parse_font_entry_win(name, font, fonts)
return fonts
@@ -104,8 +99,6 @@ def _parse_font_entry_win(name, font, fonts):
:param name: The font name
:param font: The font file path
:param fonts: The pygame font dictionary
:return: Tuple of (bold, italic, name)
"""
true_type_suffix = "(TrueType)"
mods = ("demibold", "narrow", "light", "unicode", "bt", "mt")
@@ -164,14 +157,13 @@ def _font_finder_darwin():
"/System/Library/Fonts/Supplemental",
]
if username := os.getenv("USER"):
username = os.getenv("USER")
if username:
locations.append(f"/Users/{username}/Library/Fonts")
strange_root = "/System/Library/Assets/com_apple_MobileAsset_Font3"
if exists(strange_root):
locations += [
f"{strange_root}/{loc}/AssetData" for loc in os.listdir(strange_root)
]
locations += [f"{strange_root}/{loc}" for loc in os.listdir(strange_root)]
fonts = {}
@@ -189,17 +181,20 @@ def _font_finder_darwin():
def initsysfonts_darwin():
"""Read the fonts on macOS, and OS X."""
# if the X11 binary exists... try to use that.
# Not likely to be there on pre 10.4.x ... or macOS 10.10+
if exists("/usr/X11/bin/fc-list"):
fonts = initsysfonts_unix("/usr/X11/bin/fc-list")
# This fc-list path will work with the X11 from the OS X 10.3 installation
# disc
elif exists("/usr/X11R6/bin/fc-list"):
fonts = initsysfonts_unix("/usr/X11R6/bin/fc-list")
else:
# eventually this should probably be the preferred solution
"""Read the fonts on MacOS, and OS X."""
# fc-list is not likely to be there on pre 10.4.x, or MacOS 10.10+
fonts = {}
fclist_locations = [
"/usr/X11/bin/fc-list", # apple x11
"/usr/X11R6/bin/fc-list", # apple x11
]
for bin_location in fclist_locations:
if exists(bin_location):
fonts = initsysfonts_unix(bin_location)
break
if len(fonts) == 0:
fonts = _font_finder_darwin()
return fonts
@@ -213,8 +208,6 @@ def initsysfonts_unix(path="fc-list"):
if sys.platform == "emscripten":
return fonts
import subprocess
try:
proc = subprocess.run(
[path, ":", "file", "family", "style"],
@@ -245,7 +238,7 @@ def initsysfonts_unix(path="fc-list"):
for entry in proc.stdout.decode("ascii", "ignore").splitlines():
try:
_parse_font_entry_unix(entry, fonts)
except ValueError:
except ValueError: # noqa: PERF203
# try the next one.
pass
@@ -257,7 +250,7 @@ def _parse_font_entry_unix(entry, fonts):
Parses an entry in the unix font data to add to the pygame font
dictionary.
:param entry: An entry from the unix font list.
:param entry: A entry from the unix font list.
:param fonts: The pygame font dictionary to add the parsed font data to.
"""
@@ -365,11 +358,6 @@ def initsysfonts():
else:
fonts = initsysfonts_unix()
# Try to add the default font to sys fonts
pygame_folder = os.path.dirname(os.path.abspath(pygame_main_file))
default_font_path = os.path.join(pygame_folder, "freesansbold.ttf")
_addfont("freesansbold", True, False, default_font_path, fonts)
Sysfonts.update(fonts)
create_aliases()
is_init = True
@@ -396,37 +384,6 @@ def font_constructor(fontpath, size, bold, italic):
return font
def _load_single_font(name, bold=False, italic=False):
fontname = None
gotbold = False
gotitalic = False
single_name = _simplename(name)
styles = Sysfonts.get(single_name)
if not styles:
styles = Sysalias.get(single_name)
if styles:
plainname = styles.get((False, False))
fontname = styles.get((bold, italic))
if not (fontname or plainname):
# Neither requested style, nor plain font exists, so
# return a font with the name requested, but an
# arbitrary style.
(style, fontname) = list(styles.items())[0]
# Attempt to style it as requested. This can't
# unbold or unitalicize anything, but it can
# fake bold and/or fake italicize.
if bold and style[0]:
gotbold = True
if italic and style[1]:
gotitalic = True
elif not fontname:
fontname = plainname
elif plainname != fontname:
gotbold = bold
gotitalic = italic
return fontname, gotbold, gotitalic
# the exported functions
@@ -439,16 +396,15 @@ def SysFont(name, size, bold=False, italic=False, constructor=None):
the appropriate system font will be selected if available.
This will always return a valid Font object, and will
fall back on the builtin pygame font if the given font
fallback on the builtin pygame font if the given font
is not found.
Name shall be supplied as the plain font name without
file extensions. Name can also be an iterable of font names,
a string of comma-separated font names, or a bytes of
comma-separated font names, in which case the set of names
will be searched in order. Pygame uses a small set of common
font aliases. If the specific font you ask for is not available,
a reasonable alternative may be used.
Name can also be an iterable of font names, a string of
comma-separated font names, or a bytes of comma-separated
font names, in which case the set of names will be searched
in order. Pygame uses a small set of common font aliases. If the
specific font you ask for is not available, a reasonable
alternative may be used.
If optional constructor is provided, it must be a function with
signature constructor(fontpath, size, bold, italic) which returns
@@ -460,51 +416,41 @@ def SysFont(name, size, bold=False, italic=False, constructor=None):
initsysfonts()
gotbold = gotitalic = False
fontname = None
if name:
if isinstance(name, (str, bytes)):
name = name.split(b"," if isinstance(name, bytes) else ",")
else:
name = list(name)
for idx, single_name in enumerate(name):
if isinstance(single_name, bytes):
name[idx] = single_name.decode()
for single_name in name:
fontname, gotbold, gotitalic = _load_single_font(single_name, bold, italic)
if isinstance(single_name, bytes):
single_name = single_name.decode()
single_name = _simplename(single_name)
styles = Sysfonts.get(single_name)
if not styles:
styles = Sysalias.get(single_name)
if styles:
plainname = styles.get((False, False))
fontname = styles.get((bold, italic))
if not (fontname or plainname):
# Neither requested style, nor plain font exists, so
# return a font with the name requested, but an
# arbitrary style.
(style, fontname) = list(styles.items())[0]
# Attempt to style it as requested. This can't
# unbold or unitalicize anything, but it can
# fake bold and/or fake italicize.
if bold and style[0]:
gotbold = True
if italic and style[1]:
gotitalic = True
elif not fontname:
fontname = plainname
elif plainname != fontname:
gotbold = bold
gotitalic = italic
if fontname:
break
else:
font_verification_message = (
"Verify your font name input. Using the default font instead."
)
if len(name) > 1:
names = "', '".join(name)
warnings.warn(
"None of the specified system fonts "
f"('{names}') could be found. "
f"{font_verification_message}"
)
else:
# Identifies the closest matches to the font provided by
# the user from the list of available fonts.
matches = difflib.get_close_matches(
_simplename(name[0]), itertools.chain(Sysfonts, Sysalias), 3
)
if matches:
match_text = "Did you mean: '" + "', '".join(matches) + "'? "
else:
match_text = ""
warnings.warn(
f"The system font '{name[0]}' couldn't be "
f"found. {match_text}"
f"{font_verification_message}"
)
else:
fontname = None
set_bold = set_italic = False
if bold and not gotbold:
set_bold = True
@@ -528,7 +474,7 @@ def get_fonts():
def match_font(name, bold=False, italic=False):
"""pygame.font.match_font(name, bold=False, italic=False) -> name
"""pygame.font.match_font(name, bold=0, italic=0) -> name
find the filename for the named system font
This performs the same font search as the SysFont()