Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Add custom font files support (#939)

Naveen M Kfc754fa7f60a
diff --git a/manim/_config/utils.py b/manim/_config/utils.py
index 1382a5443..ae85527f0 100644
--- a/manim/_config/utils.py
+++ b/manim/_config/utils.py
@@ -592,7 +592,7 @@ class ManimConfig(MutableMapping):
if args.config_file:
self.digest_file(args.config_file)
- self.input_file = args.file
+ self.input_file = Path(args.file).absolute()
self.scene_names = args.scene_names if args.scene_names is not None else []
self.output_file = args.output_file
diff --git a/manim/mobject/svg/text_mobject.py b/manim/mobject/svg/text_mobject.py
index 5896fbe60..ccc2086fa 100644
--- a/manim/mobject/svg/text_mobject.py
+++ b/manim/mobject/svg/text_mobject.py
@@ -42,21 +42,26 @@ Examples
"""
-__all__ = ["Text", "Paragraph", "CairoText", "MarkupText"]
+__all__ = ["Text", "Paragraph", "CairoText", "MarkupText", "register_font"]
import copy
import hashlib
import os
import re
+import sys
+import typing
+from contextlib import contextmanager
+from pathlib import Path
from typing import Dict
from xml.sax.saxutils import escape
import cairo
import manimpango
-from manimpango import PangoUtils, TextSetting, MarkupUtils
+from manimpango import MarkupUtils, PangoUtils, TextSetting
from ... import config, logger
+from ..._config.utils import ManimConfig
from ...constants import *
from ...mobject.geometry import Dot
from ...mobject.svg.svg_mobject import SVGMobject
@@ -712,11 +717,6 @@ class Text(SVGMobject):
disable_ligatures: bool = False,
**kwargs,
):
-
- logger.info(
- "Text now uses Pango for rendering. "
- "In case of problems, the old implementation is available as CairoText."
- )
self.size = size
self.line_spacing = line_spacing
self.font = font
@@ -1387,3 +1387,74 @@ class MarkupText(SVGMobject):
def __repr__(self):
return f"MarkupText({repr(self.original_text)})"
+
+
+@contextmanager
+def register_font(font_file: typing.Union[str, Path]):
+ """Temporarily add a font file to Pango's search path.
+
+ This searches for the font_file at various places. The order it searches it described below.
+
+ 1. Absolute path.
+ 2. In ``assets/fonts`` folder.
+ 3. In ``font/`` folder.
+ 4. In the same directory.
+
+ Parameters
+ ----------
+ font_file :
+ The font file to add.
+
+ Examples
+ --------
+ Use ``with register_font(...)`` to add a font file to search
+ path.
+
+ .. code-block:: python
+
+ with register_font("path/to/font_file.ttf"):
+ a = Text("Hello", font="Custom Font Name")
+
+ Raises
+ ------
+ FileNotFoundError:
+ If the font doesn't exists.
+
+ AttributeError:
+ If this method is used on macOS.
+
+ Notes
+ -----
+ This method of adding font files also works with :class:`CairoText`.
+
+ .. important ::
+
+ This method isn't available for macOS. Using this
+ method on macOS will raise an :class:`AttributeError`.
+ """
+
+ input_folder = Path(config.input_file).parent.resolve()
+ possible_paths = [
+ Path(font_file),
+ input_folder / "assets/fonts" / font_file,
+ input_folder / "fonts" / font_file,
+ input_folder / font_file,
+ ]
+ for path in possible_paths:
+ path = path.resolve()
+ if path.exists():
+ file_path = path
+ logger.debug("Found file at %s", file_path.absolute())
+ break
+ else:
+ error = f"Can't find {font_file}." f"Tried these : {possible_paths}"
+ raise FileNotFoundError(error)
+
+ try:
+ assert manimpango.register_font(str(file_path))
+ yield
+ finally:
+ if sys.platform.startswith("linux"):
+ manimpango.unregister_font()
+ else:
+ manimpango.unregister_font(str(file_path))
diff --git a/poetry.lock b/poetry.lock
index 8c30fa586..7eaffdc71 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -793,7 +793,7 @@ js_renderer = ["grpcio", "grpcio-tools", "watchdog"]
[metadata]
lock-version = "1.1"
python-versions = "^3.6"
-content-hash = "af98b54d9cd5f91415486f64c21093ef124aeff9634e593237effefd8dd4114a"
+content-hash = "5a0c8d8c8c581f09f6a663c3d793a85673d6897e4cd2778b42bd44ba6e65e189"
[metadata.files]
alabaster = [
diff --git a/pyproject.toml b/pyproject.toml
index a21aec6b3..01fc8dac6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -34,7 +34,7 @@ pydub = "*"
pygments = "*"
rich = "^6.0"
pycairo = "^1.19"
-manimpango = "^0.1.6"
+manimpango = "^0.1.7"
grpcio = { version = "1.33.*", optional = true }
grpcio-tools = { version = "1.33.*", optional = true }
watchdog = { version = "*", optional = true }