Ejemplo n.º 1
0
    def text2svg(self):
        """Convert the text to SVG using Pango."""
        size = self.size * 10
        line_spacing = self.line_spacing * 10
        dir_name = config.get_dir("text_dir")
        disable_liga = self.disable_ligatures
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)
        hash_name = self.text2hash()
        file_name = os.path.join(dir_name, hash_name) + ".svg"
        if os.path.exists(file_name):
            return file_name

        logger.debug(f"Setting Text {self.text}")
        return MarkupUtils.text2svg(
            f'<span foreground="{self.color}">{self.text}</span>',
            self.font,
            self.slant,
            self.weight,
            size,
            line_spacing,
            disable_liga,
            file_name,
            START_X,
            START_Y,
            600,  # width
            400,  # height
            justify=self.justify,
            pango_width=500,
        )
Ejemplo n.º 2
0
    def markup_to_svg(self, markup_str, file_name):
        # `manimpango` is under construction,
        # so the following code is intended to suit its interface
        alignment = _Alignment(self.alignment)
        if self.line_width_factor is None:
            pango_width = -1
        else:
            pango_width = self.line_width_factor * DEFAULT_PIXEL_WIDTH

        return MarkupUtils.text2svg(
            text=markup_str,
            font="",  # Already handled
            slant="NORMAL",  # Already handled
            weight="NORMAL",  # Already handled
            size=1,  # Already handled
            _=0,  # Empty parameter
            disable_liga=False,  # Already handled
            file_name=file_name,
            START_X=0,
            START_Y=0,
            width=DEFAULT_PIXEL_WIDTH,
            height=DEFAULT_PIXEL_HEIGHT,
            justify=self.justify,
            indent=self.indent,
            line_spacing=None,  # Already handled
            alignment=alignment,
            pango_width=pango_width)
Ejemplo n.º 3
0
    def text2svg(self):
        """Convert the text to SVG using Pango."""
        size = self._font_size
        line_spacing = self.line_spacing
        size /= TEXT2SVG_ADJUSTMENT_FACTOR
        line_spacing /= TEXT2SVG_ADJUSTMENT_FACTOR

        dir_name = config.get_dir("text_dir")
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)
        hash_name = self.text2hash()
        file_name = os.path.join(dir_name, hash_name) + ".svg"
        if os.path.exists(file_name):
            svg_file = file_name
        else:
            logger.debug(f"Setting Text {self.text}")
            svg_file = MarkupUtils.text2svg(
                f'<span foreground="{self.color}">{self.text}</span>',
                self.font,
                self.slant,
                self.weight,
                size,
                line_spacing,
                self.disable_ligatures,
                file_name,
                START_X,
                START_Y,
                600,  # width
                400,  # height
                justify=self.justify,
                pango_width=500,
            )
        return svg_file
Ejemplo n.º 4
0
    def text2svg(self):
        """Convert the text to SVG using Pango."""
        size = self.font_size
        dir_name = get_text_dir()
        disable_liga = self.disable_ligatures
        if not os.path.exists(dir_name):
            os.makedirs(dir_name)
        hash_name = self.text2hash()
        file_name = os.path.join(dir_name, hash_name) + ".svg"
        if os.path.exists(file_name):
            return file_name

        extra_kwargs = {}
        extra_kwargs['justify'] = self.justify
        extra_kwargs['pango_width'] = DEFAULT_PIXEL_WIDTH - 100
        if self.lsh:
            extra_kwargs['line_spacing'] = self.lsh
        return MarkupUtils.text2svg(
            f'<span foreground="{self.color}">{self.text}</span>',
            self.font,
            self.slant,
            self.weight,
            size,
            0,  # empty parameter
            disable_liga,
            file_name,
            START_X,
            START_Y,
            DEFAULT_PIXEL_WIDTH,  # width
            DEFAULT_PIXEL_HEIGHT,  # height
            **extra_kwargs)
Ejemplo n.º 5
0
    def __init__(self, text, **kwargs):
        self.full2short(kwargs)
        digest_config(self, kwargs)
        validate_error = MarkupUtils.validate(text)
        if validate_error:
            raise ValueError(validate_error)
        self.text = text
        self.parser = _TextParser(text, is_markup=self.is_markup)
        super().__init__(**kwargs)

        if self.gradient:
            self.set_color_by_gradient(*self.gradient)
        if self.height is None:
            self.scale(TEXT_MOB_SCALE_FACTOR)
Ejemplo n.º 6
0
 def __init__(self, text, **config):
     digest_config(self, config)
     self.text = f'<span>{text}</span>'
     self.original_text = self.text
     self.text_for_parsing = self.text
     text_without_tabs = text
     if "\t" in text:
         text_without_tabs = text.replace("\t", " " * self.tab_width)
     try:
         colormap = self.extract_color_tags()
         gradientmap = self.extract_gradient_tags()
     except ET.ParseError:
         # let pango handle that error
         pass
     validate_error = MarkupUtils.validate(self.text)
     if validate_error:
         raise ValueError(validate_error)
     file_name = self.text2svg()
     PangoUtils.remove_last_M(file_name)
     super().__init__(
         file_name,
         **config,
     )
     self.chars = self.get_group_class()(*self.submobjects)
     self.text = text_without_tabs.replace(" ", "").replace("\n", "")
     if self.gradient:
         self.set_color_by_gradient(*self.gradient)
     for col in colormap:
         self.chars[col["start"] - col["start_offset"]:col["end"] -
                    col["start_offset"] - col["end_offset"]].set_color(
                        self._parse_color(col["color"]))
     for grad in gradientmap:
         self.chars[grad["start"] - grad["start_offset"]:grad["end"] -
                    grad["start_offset"] -
                    grad["end_offset"]].set_color_by_gradient(
                        *(self._parse_color(grad["from"]),
                          self._parse_color(grad["to"])))
     # anti-aliasing
     if self.height is None:
         self.scale(TEXT_MOB_SCALE_FACTOR)
Ejemplo n.º 7
0
    def __init__(self, text: str, **kwargs):
        self.full2short(kwargs)
        digest_config(self, kwargs)

        if not self.font:
            self.font = get_customization()["style"]["font"]
        if self.is_markup:
            validate_error = MarkupUtils.validate(text)
            if validate_error:
                raise ValueError(validate_error)

        self.text = text
        super().__init__(text, **kwargs)

        if self.t2g:
            log.warning(
                "Manim currently cannot parse gradient from svg. "
                "Please set gradient via `set_color_by_gradient`.", )
        if self.gradient:
            self.set_color_by_gradient(*self.gradient)
        if self.height is None:
            self.scale(TEXT_MOB_SCALE_FACTOR)
Ejemplo n.º 8
0
    def __init__(
        self,
        text: str,
        fill_opacity: int = 1,
        stroke_width: int = 0,
        color: str = WHITE,
        size: int = 1,
        line_spacing: int = -1,
        font: str = "",
        slant: str = NORMAL,
        weight: str = NORMAL,
        justify: bool = False,
        gradient: tuple = None,
        tab_width: int = 4,
        height: int = None,
        width: int = None,
        should_center: bool = True,
        unpack_groups: bool = True,
        disable_ligatures: bool = False,
        **kwargs,
    ):
        self.text = text
        self.color = color
        self.size = size
        self.line_spacing = line_spacing
        self.font = font
        self.slant = slant
        self.weight = weight
        self.gradient = gradient
        self.tab_width = tab_width
        self.justify = justify

        self.original_text = text
        self.disable_ligatures = disable_ligatures
        text_without_tabs = text
        if "\t" in text:
            text_without_tabs = text.replace("\t", " " * self.tab_width)

        colormap = self.extract_color_tags()
        if len(colormap) > 0:
            logger.warning(
                'Using <color> tags in MarkupText is deprecated. Please use <span foreground="..."> instead.'
            )
        gradientmap = self.extract_gradient_tags()
        validate_error = MarkupUtils.validate(self.text)
        if validate_error:
            raise ValueError(validate_error)

        if self.line_spacing == -1:
            self.line_spacing = self.size + self.size * 0.3
        else:
            self.line_spacing = self.size + self.size * self.line_spacing

        file_name = self.text2svg()
        PangoUtils.remove_last_M(file_name)
        super().__init__(
            file_name,
            fill_opacity=fill_opacity,
            stroke_width=stroke_width,
            height=height,
            width=width,
            should_center=should_center,
            unpack_groups=unpack_groups,
            **kwargs,
        )
        self.chars = self.get_group_class()(*self.submobjects)
        self.text = text_without_tabs.replace(" ", "").replace("\n", "")

        if config.renderer == "opengl":
            nppc = self.n_points_per_curve
        else:
            nppc = self.n_points_per_cubic_curve
        for each in self:
            if len(each.get_points()) == 0:
                continue
            points = each.get_points()
            last = points[0]
            each.clear_points()
            for index, point in enumerate(points):
                each.append_points([point])
                if (
                    index != len(points) - 1
                    and (index + 1) % nppc == 0
                    and any(point != points[index + 1])
                ):
                    each.add_line_to(last)
                    last = points[index + 1]
            each.add_line_to(last)

        if self.gradient:
            self.set_color_by_gradient(*self.gradient)
        for col in colormap:
            self.chars[
                col["start"]
                - col["start_offset"] : col["end"]
                - col["start_offset"]
                - col["end_offset"]
            ].set_color(self._parse_color(col["color"]))
        for grad in gradientmap:
            self.chars[
                grad["start"]
                - grad["start_offset"] : grad["end"]
                - grad["start_offset"]
                - grad["end_offset"]
            ].set_color_by_gradient(
                *(self._parse_color(grad["from"]), self._parse_color(grad["to"]))
            )
        # anti-aliasing
        if height is None and width is None:
            self.scale(TEXT_MOB_SCALE_FACTOR)
Ejemplo n.º 9
0
    def __init__(
        self,
        text: str,
        fill_opacity: int = 1,
        stroke_width: int = 0,
        color: str = WHITE,
        size: int = 1,
        line_spacing: int = -1,
        font: str = "",
        slant: str = NORMAL,
        weight: str = NORMAL,
        gradient: tuple = None,
        tab_width: int = 4,
        height: int = None,
        width: int = None,
        should_center: bool = True,
        unpack_groups: bool = True,
        disable_ligatures: bool = False,
        **kwargs,
    ):
        self.text = text
        self.size = size
        self.line_spacing = line_spacing
        self.font = font
        self.slant = slant
        self.weight = weight
        self.gradient = gradient
        self.tab_width = tab_width

        self.original_text = text
        self.disable_ligatures = disable_ligatures
        text_without_tabs = text
        if "\t" in text:
            text_without_tabs = text.replace("\t", " " * self.tab_width)

        colormap = self.extract_color_tags()
        gradientmap = self.extract_gradient_tags()

        if not MarkupUtils.validate(self.text):
            raise ValueError(
                f"Pango cannot parse your markup in {self.text}. "
                "Please check for typos, unmatched tags or unescaped "
                "special chars like < and &.")

        if self.line_spacing == -1:
            self.line_spacing = self.size + self.size * 0.3
        else:
            self.line_spacing = self.size + self.size * self.line_spacing

        file_name = self.text2svg()
        PangoUtils.remove_last_M(file_name)
        SVGMobject.__init__(
            self,
            file_name,
            color=color,
            fill_opacity=fill_opacity,
            stroke_width=stroke_width,
            height=height,
            width=width,
            should_center=should_center,
            unpack_groups=unpack_groups,
            **kwargs,
        )
        self.chars = VGroup(*self.submobjects)
        self.text = text_without_tabs.replace(" ", "").replace("\n", "")

        nppc = self.n_points_per_cubic_curve
        for each in self:
            if len(each.points) == 0:
                continue
            points = each.points
            last = points[0]
            each.clear_points()
            for index, point in enumerate(points):
                each.append_points([point])
                if (index != len(points) - 1 and (index + 1) % nppc == 0
                        and any(point != points[index + 1])):
                    each.add_line_to(last)
                    last = points[index + 1]
            each.add_line_to(last)

        if self.gradient:
            self.set_color_by_gradient(*self.gradient)
        for col in colormap:
            self.chars[col["start"] - col["start_offset"]:col["end"] -
                       col["start_offset"] - col["end_offset"]].set_color(
                           self._parse_color(col["color"]))
        for grad in gradientmap:
            self.chars[grad["start"] - grad["start_offset"]:grad["end"] -
                       grad["start_offset"] -
                       grad["end_offset"]].set_color_by_gradient(
                           *(self._parse_color(grad["from"]),
                             self._parse_color(grad["to"])))
        # anti-aliasing
        if self.height is None and self.width is None:
            self.scale(TEXT_MOB_SCALE_FACTOR)