A community-maintained Python framework for creating mathematical animations.
fix: normalize `Code` baseline alignment in `Paragraph` (#4692)
Colin Belhomme49ed81155957
diff --git a/manim/mobject/text/code_mobject.py b/manim/mobject/text/code_mobject.pyindex 0351011a1..f2b72cd12 100644--- a/manim/mobject/text/code_mobject.py+++ b/manim/mobject/text/code_mobject.py@@ -225,8 +225,25 @@ class Code(VMobject, metaclass=ConvertToOpenGL):from manim.mobject.text.text_mobject import Paragraph+ # Paragraph cannot render input consisting entirely of whitespace, but+ # such lines contain no visible glyphs and can safely be represented as empty.+ rendered_code_lines = (+ code_lines+ if any(line.strip() for line in code_lines)+ else [""] * len(code_lines)+ )++ # Until Pango exposes baseline metrics, temporarily add glyphs with an+ # ascender and a descender to the first and last lines. This normalizes+ # the vertical bounds of code listings independently of their contents.+ alignment_suffix = " pA" + str(line_numbers_from)+ boundary_line_indices = sorted({0, len(rendered_code_lines) - 1})+ aligned_code_lines = rendered_code_lines.copy()+ for index in boundary_line_indices:+ aligned_code_lines[index] += alignment_suffix+self.code_lines = Paragraph(- *code_lines,+ *aligned_code_lines,color=foreground_color,**base_paragraph_config,)@@ -254,26 +271,41 @@ class Code(VMobject, metaclass=ConvertToOpenGL):i_char += 1if add_line_numbers:+ line_number_strings = map(+ str,+ range(+ line_numbers_from,+ line_numbers_from + len(self.code_lines),+ ),+ )line_number_config = base_paragraph_config.copy()line_number_config["alignment"] = "right"line_number_color = selected_style.line_number_colorif line_number_color == "inherit":line_number_color = foreground_colorself.line_numbers = Paragraph(- *[- str(i)- for i in range(- line_numbers_from, line_numbers_from + len(self.code_lines)- )- ],+ *line_number_strings,color=line_number_color,**line_number_config,)- self.line_numbers.next_to(self.code_lines, direction=LEFT).align_to(- self.code_lines, UP+ self.line_numbers.next_to(self.code_lines, direction=LEFT)++ line_number_reference = VGroup(+ *self.code_lines[0][-len(str(line_numbers_from)) :]+ )+ self.line_numbers.shift(+ UP * (line_number_reference.get_y() - self.line_numbers[0].get_y()))self.add(self.line_numbers)+ alignment_mobjects = VGroup(+ *(+ self.code_lines[index].submobjects.pop()+ for index in boundary_line_indices+ for _ in range(len(alignment_suffix))+ )+ ).stretch_to_fit_width(0, about_edge=LEFT)+for line in self.code_lines:line.submobjects = [c for c in line if not isinstance(c, Dot)]self.add(self.code_lines)@@ -286,6 +318,7 @@ class Code(VMobject, metaclass=ConvertToOpenGL):if background == "rectangle":self.background = SurroundingRectangle(self,+ alignment_mobjects,**background_config_base,)elif background == "window":@@ -293,9 +326,13 @@ class Code(VMobject, metaclass=ConvertToOpenGL):Dot(radius=0.1, stroke_width=0, color=button_color)for button_color in ["#ff5f56", "#ffbd2e", "#27c93f"]).arrange(RIGHT, buff=0.1)- buttons.next_to(self, UP, buff=0.1).align_to(self, LEFT).shift(LEFT * 0.1)+ code_and_alignment = VGroup(self, alignment_mobjects)+ buttons.next_to(code_and_alignment, UP, buff=0.1).align_to(+ code_and_alignment, LEFT+ ).shift(LEFT * 0.1)self.background = SurroundingRectangle(- VGroup(self, buttons),+ code_and_alignment,+ buttons,**background_config_base,)buttons.shift(UP * 0.1 + LEFT * 0.1)diff --git a/tests/test_code_mobject.py b/tests/module/mobject/text/test_code_mobject.pysimilarity index 64%rename from tests/test_code_mobject.pyrename to tests/module/mobject/text/test_code_mobject.pyindex 674ef147f..08f5ee472 100644--- a/tests/test_code_mobject.py+++ b/tests/module/mobject/text/test_code_mobject.py@@ -23,6 +23,21 @@ class FadeInSquare(Scene):assert len(rendered_code.line_numbers) == num_lines+ ("code_string", "num_lines"),+ [("pass", 1), (" ", 1), (" \n ", 2)],+)+def test_code_initialization_without_line_numbers(code_string, num_lines):+ rendered_code = Code(+ code_string=code_string,+ language="python",+ add_line_numbers=False,+ )++ assert len(rendered_code.code_lines) == num_lines+ assert not hasattr(rendered_code, "line_numbers")++def test_code_initialization_from_file():rendered_code = Code(code_file="example_scenes/basic.py",@@ -131,6 +146,69 @@ for _ in range(42):)[email protected]("line_numbers_from", [1, 10, -2])+def test_code_baseline_alignment(line_numbers_from):+ baseline_offsets = []+ for code_string in ("pass", "pass b"):+ rendered_code = Code(+ code_string=code_string,+ language="python",+ line_numbers_from=line_numbers_from,+ )+ baseline_offsets.append(+ rendered_code.code_lines[0].get_bottom()[1]+ - rendered_code.line_numbers[0].get_bottom()[1]+ )++ np.testing.assert_allclose(baseline_offsets[0], baseline_offsets[1], atol=1e-6)++[email protected]("background", ["rectangle", "window"])[email protected]("add_line_numbers", [True, False])+def test_code_height_is_independent_of_boundary_glyphs(+ background,+ add_line_numbers,+):+ code_strings = (+ "AAA\nppp",+ "ppp\nAAA",+ "AAA\nAAA",+ "ppp\nppp",+ "---\n---",+ )+ background_heights = [+ Code(+ code_string=code_string,+ language="python",+ background=background,+ add_line_numbers=add_line_numbers,+ ).background.height+ for code_string in code_strings+ ]++ np.testing.assert_allclose(background_heights, background_heights[0], atol=1e-6)+++def test_code_syntax_highlighting_colors():+ code_string = "pass\n# comment"+ rendered_code = Code(+ code_string=code_string,+ language="python",+ formatter_style="vim",+ )++ assert {char.color for char in rendered_code.code_lines[0]} == {+ ManimColor("#CDCD00")+ }+ assert {char.color for char in rendered_code.code_lines[1]} == {+ ManimColor("#000080")+ }+ assert [len(line) for line in rendered_code.code_lines] == [+ sum(not char.isspace() for char in line) for line in code_string.splitlines()+ ]+ assert len(rendered_code.code_lines) == len(rendered_code.code_lines.chars)++def test_code_initialization_style_correct_color():for style in Code.get_styles_list():try: