mirror of
https://github.com/3b1b/manim.git
synced 2025-08-05 16:49:03 +00:00
Merge pull request #1779 from YishiMichael/master
Refactor `LabelledString` and relevant classes
This commit is contained in:
commit
13c731e166
5 changed files with 165 additions and 172 deletions
|
@ -6,12 +6,9 @@ from manimlib.constants import *
|
||||||
from manimlib.mobject.svg.tex_mobject import SingleStringTex
|
from manimlib.mobject.svg.tex_mobject import SingleStringTex
|
||||||
from manimlib.mobject.svg.text_mobject import Text
|
from manimlib.mobject.svg.text_mobject import Text
|
||||||
from manimlib.mobject.types.vectorized_mobject import VMobject
|
from manimlib.mobject.types.vectorized_mobject import VMobject
|
||||||
from manimlib.utils.iterables import hash_obj
|
|
||||||
|
|
||||||
T = TypeVar("T", bound=VMobject)
|
T = TypeVar("T", bound=VMobject)
|
||||||
|
|
||||||
string_to_mob_map: dict[str, VMobject] = {}
|
|
||||||
|
|
||||||
|
|
||||||
class DecimalNumber(VMobject):
|
class DecimalNumber(VMobject):
|
||||||
CONFIG = {
|
CONFIG = {
|
||||||
|
@ -92,9 +89,7 @@ class DecimalNumber(VMobject):
|
||||||
return self.data["font_size"][0]
|
return self.data["font_size"][0]
|
||||||
|
|
||||||
def string_to_mob(self, string: str, mob_class: Type[T] = Text, **kwargs) -> T:
|
def string_to_mob(self, string: str, mob_class: Type[T] = Text, **kwargs) -> T:
|
||||||
if (string, hash_obj(kwargs)) not in string_to_mob_map:
|
mob = mob_class(string, font_size=1, **kwargs)
|
||||||
string_to_mob_map[(string, hash_obj(kwargs))] = mob_class(string, font_size=1, **kwargs)
|
|
||||||
mob = string_to_mob_map[(string, hash_obj(kwargs))].copy()
|
|
||||||
mob.scale(self.get_font_size())
|
mob.scale(self.get_font_size())
|
||||||
return mob
|
return mob
|
||||||
|
|
||||||
|
|
|
@ -11,7 +11,6 @@ from manimlib.mobject.svg.svg_mobject import SVGMobject
|
||||||
from manimlib.mobject.types.vectorized_mobject import VGroup
|
from manimlib.mobject.types.vectorized_mobject import VGroup
|
||||||
from manimlib.utils.color import color_to_int_rgb
|
from manimlib.utils.color import color_to_int_rgb
|
||||||
from manimlib.utils.config_ops import digest_config
|
from manimlib.utils.config_ops import digest_config
|
||||||
from manimlib.utils.iterables import adjacent_pairs
|
|
||||||
from manimlib.utils.iterables import remove_list_redundancies
|
from manimlib.utils.iterables import remove_list_redundancies
|
||||||
|
|
||||||
|
|
||||||
|
@ -40,19 +39,29 @@ class LabelledString(_StringSVG):
|
||||||
An abstract base class for `MTex` and `MarkupText`
|
An abstract base class for `MTex` and `MarkupText`
|
||||||
"""
|
"""
|
||||||
CONFIG = {
|
CONFIG = {
|
||||||
"base_color": WHITE,
|
"base_color": None,
|
||||||
"use_plain_file": False,
|
"use_plain_file": False,
|
||||||
"isolate": [],
|
"isolate": [],
|
||||||
}
|
}
|
||||||
|
|
||||||
def __init__(self, string: str, **kwargs):
|
def __init__(self, string: str, **kwargs):
|
||||||
self.string = string
|
self.string = string
|
||||||
|
reserved_svg_default = kwargs.pop("svg_default", {})
|
||||||
digest_config(self, kwargs)
|
digest_config(self, kwargs)
|
||||||
|
self.reserved_svg_default = reserved_svg_default
|
||||||
|
self.base_color = self.base_color \
|
||||||
|
or reserved_svg_default.get("color", None) \
|
||||||
|
or reserved_svg_default.get("fill_color", None) \
|
||||||
|
or WHITE
|
||||||
|
|
||||||
self.pre_parse()
|
self.pre_parse()
|
||||||
self.parse()
|
self.parse()
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
|
|
||||||
def get_file_path(self, use_plain_file: bool = False) -> str:
|
def get_file_path(self) -> str:
|
||||||
|
return self.get_file_path_(use_plain_file=False)
|
||||||
|
|
||||||
|
def get_file_path_(self, use_plain_file: bool) -> str:
|
||||||
content = self.get_decorated_string(use_plain_file=use_plain_file)
|
content = self.get_decorated_string(use_plain_file=use_plain_file)
|
||||||
return self.get_file_path_by_content(content)
|
return self.get_file_path_by_content(content)
|
||||||
|
|
||||||
|
@ -67,9 +76,17 @@ class LabelledString(_StringSVG):
|
||||||
self.color_to_label(submob.get_fill_color())
|
self.color_to_label(submob.get_fill_color())
|
||||||
for submob in self.submobjects
|
for submob in self.submobjects
|
||||||
]
|
]
|
||||||
if self.use_plain_file or self.has_predefined_colors:
|
if any([
|
||||||
file_path = self.get_file_path(use_plain_file=True)
|
self.use_plain_file,
|
||||||
plain_svg = _StringSVG(file_path)
|
self.reserved_svg_default,
|
||||||
|
self.has_predefined_colors
|
||||||
|
]):
|
||||||
|
file_path = self.get_file_path_(use_plain_file=True)
|
||||||
|
plain_svg = _StringSVG(
|
||||||
|
file_path,
|
||||||
|
svg_default=self.reserved_svg_default,
|
||||||
|
path_string_config=self.path_string_config
|
||||||
|
)
|
||||||
self.set_submobjects(plain_svg.submobjects)
|
self.set_submobjects(plain_svg.submobjects)
|
||||||
else:
|
else:
|
||||||
self.set_fill(self.base_color)
|
self.set_fill(self.base_color)
|
||||||
|
@ -77,8 +94,8 @@ class LabelledString(_StringSVG):
|
||||||
submob.label = label
|
submob.label = label
|
||||||
|
|
||||||
def pre_parse(self) -> None:
|
def pre_parse(self) -> None:
|
||||||
self.full_span = self.get_full_span()
|
self.string_len = len(self.string)
|
||||||
self.space_spans = self.get_space_spans()
|
self.full_span = (0, self.string_len)
|
||||||
|
|
||||||
def parse(self) -> None:
|
def parse(self) -> None:
|
||||||
self.command_repl_items = self.get_command_repl_items()
|
self.command_repl_items = self.get_command_repl_items()
|
||||||
|
@ -89,31 +106,57 @@ class LabelledString(_StringSVG):
|
||||||
self.external_specified_spans = self.get_external_specified_spans()
|
self.external_specified_spans = self.get_external_specified_spans()
|
||||||
self.specified_spans = self.get_specified_spans()
|
self.specified_spans = self.get_specified_spans()
|
||||||
self.label_span_list = self.get_label_span_list()
|
self.label_span_list = self.get_label_span_list()
|
||||||
self.containing_labels_dict = self.get_containing_labels_dict()
|
self.check_overlapping()
|
||||||
self.has_predefined_colors = self.get_has_predefined_colors()
|
|
||||||
|
|
||||||
# Toolkits
|
# Toolkits
|
||||||
|
|
||||||
def find_spans(self, pattern: str) -> list[Span]:
|
def get_substr(self, span: Span) -> str:
|
||||||
return [
|
return self.string[slice(*span)]
|
||||||
match_obj.span()
|
|
||||||
for match_obj in re.finditer(pattern, self.string)
|
|
||||||
]
|
|
||||||
|
|
||||||
def find_substr(self, *substrs: str) -> list[Span]:
|
def finditer(self, pattern, **kwargs):
|
||||||
|
return re.compile(pattern).finditer(self.string, **kwargs)
|
||||||
|
|
||||||
|
def search(self, pattern, **kwargs):
|
||||||
|
return re.compile(pattern).search(self.string, **kwargs)
|
||||||
|
|
||||||
|
def match(self, pattern, **kwargs):
|
||||||
|
return re.compile(pattern).match(self.string, **kwargs)
|
||||||
|
|
||||||
|
def find_spans(self, pattern: str) -> list[Span]:
|
||||||
|
return [match_obj.span() for match_obj in self.finditer(pattern)]
|
||||||
|
|
||||||
|
def find_substr(self, substr: str) -> list[Span]:
|
||||||
|
if not substr:
|
||||||
|
return []
|
||||||
|
return self.find_spans(re.escape(substr))
|
||||||
|
|
||||||
|
def find_substrs(self, substrs: list[str]) -> list[Span]:
|
||||||
return list(it.chain(*[
|
return list(it.chain(*[
|
||||||
self.find_spans(re.escape(substr)) if substr else []
|
self.find_substr(substr)
|
||||||
for substr in remove_list_redundancies(substrs)
|
for substr in remove_list_redundancies(substrs)
|
||||||
]))
|
]))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_neighbouring_pairs(iterable: Iterable) -> list:
|
def get_neighbouring_pairs(iterable: list) -> list[tuple]:
|
||||||
return list(adjacent_pairs(iterable))[:-1]
|
return list(zip(iterable[:-1], iterable[1:]))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def span_contains(span_0: Span, span_1: Span) -> bool:
|
def span_contains(span_0: Span, span_1: Span) -> bool:
|
||||||
return span_0[0] <= span_1[0] and span_0[1] >= span_1[1]
|
return span_0[0] <= span_1[0] and span_0[1] >= span_1[1]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_complement_spans(
|
||||||
|
interval_spans: list[Span], universal_span: Span
|
||||||
|
) -> list[Span]:
|
||||||
|
if not interval_spans:
|
||||||
|
return [universal_span]
|
||||||
|
|
||||||
|
span_ends, span_begins = zip(*interval_spans)
|
||||||
|
return list(zip(
|
||||||
|
(universal_span[0], *span_begins),
|
||||||
|
(*span_ends, universal_span[1])
|
||||||
|
))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def compress_neighbours(vals: list[int]) -> list[tuple[int, Span]]:
|
def compress_neighbours(vals: list[int]) -> list[tuple[int, Span]]:
|
||||||
if not vals:
|
if not vals:
|
||||||
|
@ -148,31 +191,6 @@ class LabelledString(_StringSVG):
|
||||||
index = LabelledString.find_region_index(sorted_seq, val)
|
index = LabelledString.find_region_index(sorted_seq, val)
|
||||||
return sorted_seq[index + index_shift]
|
return sorted_seq[index + index_shift]
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def replace_str_by_spans(
|
|
||||||
substr: str, span_repl_dict: dict[Span, str]
|
|
||||||
) -> str:
|
|
||||||
if not span_repl_dict:
|
|
||||||
return substr
|
|
||||||
|
|
||||||
spans = sorted(span_repl_dict.keys())
|
|
||||||
if not all(
|
|
||||||
span_0[1] <= span_1[0]
|
|
||||||
for span_0, span_1 in LabelledString.get_neighbouring_pairs(spans)
|
|
||||||
):
|
|
||||||
raise ValueError("Overlapping replacement")
|
|
||||||
|
|
||||||
span_ends, span_begins = zip(*spans)
|
|
||||||
pieces = [
|
|
||||||
substr[slice(*span)]
|
|
||||||
for span in zip(
|
|
||||||
(0, *span_begins),
|
|
||||||
(*span_ends, len(substr))
|
|
||||||
)
|
|
||||||
]
|
|
||||||
repl_strs = [*[span_repl_dict[span] for span in spans], ""]
|
|
||||||
return "".join(it.chain(*zip(pieces, repl_strs)))
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def get_span_replacement_dict(
|
def get_span_replacement_dict(
|
||||||
inserted_string_pairs: list[tuple[Span, tuple[str, str]]],
|
inserted_string_pairs: list[tuple[Span, tuple[str, str]]],
|
||||||
|
@ -199,6 +217,27 @@ class LabelledString(_StringSVG):
|
||||||
})
|
})
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
def get_replaced_substr(
|
||||||
|
self, span: Span, span_repl_dict: dict[Span, str]
|
||||||
|
) -> str:
|
||||||
|
repl_spans = sorted(filter(
|
||||||
|
lambda repl_span: self.span_contains(span, repl_span),
|
||||||
|
span_repl_dict.keys()
|
||||||
|
))
|
||||||
|
if not all(
|
||||||
|
span_0[1] <= span_1[0]
|
||||||
|
for span_0, span_1 in self.get_neighbouring_pairs(repl_spans)
|
||||||
|
):
|
||||||
|
raise ValueError("Overlapping replacement")
|
||||||
|
|
||||||
|
pieces = [
|
||||||
|
self.get_substr(piece_span)
|
||||||
|
for piece_span in self.get_complement_spans(repl_spans, span)
|
||||||
|
]
|
||||||
|
repl_strs = [span_repl_dict[repl_span] for repl_span in repl_spans]
|
||||||
|
repl_strs.append("")
|
||||||
|
return "".join(it.chain(*zip(pieces, repl_strs)))
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def rslide(index: int, skipped: list[Span]) -> int:
|
def rslide(index: int, skipped: list[Span]) -> int:
|
||||||
transfer_dict = dict(sorted(skipped))
|
transfer_dict = dict(sorted(skipped))
|
||||||
|
@ -215,13 +254,6 @@ class LabelledString(_StringSVG):
|
||||||
index = transfer_dict[index]
|
index = transfer_dict[index]
|
||||||
return index
|
return index
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def shrink_span(span: Span, skipped: list[Span]) -> Span:
|
|
||||||
return (
|
|
||||||
LabelledString.rslide(span[0], skipped),
|
|
||||||
LabelledString.lslide(span[1], skipped)
|
|
||||||
)
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def rgb_to_int(rgb_tuple: tuple[int, int, int]) -> int:
|
def rgb_to_int(rgb_tuple: tuple[int, int, int]) -> int:
|
||||||
r, g, b = rgb_tuple
|
r, g, b = rgb_tuple
|
||||||
|
@ -250,14 +282,6 @@ class LabelledString(_StringSVG):
|
||||||
def get_end_color_command_str() -> str:
|
def get_end_color_command_str() -> str:
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
# Pre-parsing
|
|
||||||
|
|
||||||
def get_full_span(self) -> Span:
|
|
||||||
return (0, len(self.string))
|
|
||||||
|
|
||||||
def get_space_spans(self) -> list[Span]:
|
|
||||||
return self.find_spans(r"\s")
|
|
||||||
|
|
||||||
# Parsing
|
# Parsing
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
|
@ -272,11 +296,17 @@ class LabelledString(_StringSVG):
|
||||||
|
|
||||||
def get_skipped_spans(self) -> list[Span]:
|
def get_skipped_spans(self) -> list[Span]:
|
||||||
return list(it.chain(
|
return list(it.chain(
|
||||||
self.space_spans,
|
self.find_spans(r"\s"),
|
||||||
self.command_spans,
|
self.command_spans,
|
||||||
self.ignored_spans
|
self.ignored_spans
|
||||||
))
|
))
|
||||||
|
|
||||||
|
def shrink_span(self, span: Span) -> Span:
|
||||||
|
return (
|
||||||
|
self.rslide(span[0], self.skipped_spans),
|
||||||
|
self.lslide(span[1], self.skipped_spans)
|
||||||
|
)
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def get_internal_specified_spans(self) -> list[Span]:
|
def get_internal_specified_spans(self) -> list[Span]:
|
||||||
return []
|
return []
|
||||||
|
@ -290,14 +320,11 @@ class LabelledString(_StringSVG):
|
||||||
self.full_span,
|
self.full_span,
|
||||||
*self.internal_specified_spans,
|
*self.internal_specified_spans,
|
||||||
*self.external_specified_spans,
|
*self.external_specified_spans,
|
||||||
*self.find_substr(*self.isolate)
|
*self.find_substrs(self.isolate)
|
||||||
]
|
]
|
||||||
shrinked_spans = list(filter(
|
shrinked_spans = list(filter(
|
||||||
lambda span: span[0] < span[1],
|
lambda span: span[0] < span[1],
|
||||||
[
|
[self.shrink_span(span) for span in spans]
|
||||||
self.shrink_span(span, self.skipped_spans)
|
|
||||||
for span in spans
|
|
||||||
]
|
|
||||||
))
|
))
|
||||||
return remove_list_redundancies(shrinked_spans)
|
return remove_list_redundancies(shrinked_spans)
|
||||||
|
|
||||||
|
@ -305,28 +332,14 @@ class LabelledString(_StringSVG):
|
||||||
def get_label_span_list(self) -> list[Span]:
|
def get_label_span_list(self) -> list[Span]:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
def get_containing_labels_dict(self) -> dict[Span, list[int]]:
|
def check_overlapping(self) -> None:
|
||||||
label_span_list = self.label_span_list
|
for span_0, span_1 in it.product(self.label_span_list, repeat=2):
|
||||||
result = {
|
if not span_0[0] < span_1[0] < span_0[1] < span_1[1]:
|
||||||
span: []
|
continue
|
||||||
for span in label_span_list
|
|
||||||
}
|
|
||||||
for span_0 in label_span_list:
|
|
||||||
for span_index, span_1 in enumerate(label_span_list):
|
|
||||||
if self.span_contains(span_0, span_1):
|
|
||||||
result[span_0].append(span_index)
|
|
||||||
elif span_0[0] < span_1[0] < span_0[1] < span_1[1]:
|
|
||||||
string_0, string_1 = [
|
|
||||||
self.string[slice(*span)]
|
|
||||||
for span in [span_0, span_1]
|
|
||||||
]
|
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"Partially overlapping substrings detected: "
|
"Partially overlapping substrings detected: "
|
||||||
f"'{string_0}' and '{string_1}'"
|
f"'{self.get_substr(span_0)}' and '{self.get_substr(span_1)}'"
|
||||||
)
|
)
|
||||||
if self.full_span not in result:
|
|
||||||
result[self.full_span] = list(range(len(label_span_list)))
|
|
||||||
return result
|
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def get_inserted_string_pairs(
|
def get_inserted_string_pairs(
|
||||||
|
@ -345,7 +358,7 @@ class LabelledString(_StringSVG):
|
||||||
self.get_inserted_string_pairs(use_plain_file),
|
self.get_inserted_string_pairs(use_plain_file),
|
||||||
self.get_other_repl_items(use_plain_file)
|
self.get_other_repl_items(use_plain_file)
|
||||||
)
|
)
|
||||||
result = self.replace_str_by_spans(self.string, span_repl_dict)
|
result = self.get_replaced_substr(self.full_span, span_repl_dict)
|
||||||
|
|
||||||
if not use_plain_file:
|
if not use_plain_file:
|
||||||
return result
|
return result
|
||||||
|
@ -358,20 +371,14 @@ class LabelledString(_StringSVG):
|
||||||
])
|
])
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
def get_has_predefined_colors(self) -> bool:
|
def has_predefined_colors(self) -> bool:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# Post-parsing
|
# Post-parsing
|
||||||
|
|
||||||
def get_cleaned_substr(self, span: Span) -> str:
|
def get_cleaned_substr(self, span: Span) -> str:
|
||||||
span_repl_dict = {
|
span_repl_dict = dict.fromkeys(self.command_spans, "")
|
||||||
tuple([index - span[0] for index in cmd_span]): ""
|
return self.get_replaced_substr(span, span_repl_dict)
|
||||||
for cmd_span in self.command_spans
|
|
||||||
if self.span_contains(span, cmd_span)
|
|
||||||
}
|
|
||||||
return self.replace_str_by_spans(
|
|
||||||
self.string[slice(*span)], span_repl_dict
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_specified_substrs(self) -> list[str]:
|
def get_specified_substrs(self) -> list[str]:
|
||||||
return remove_list_redundancies([
|
return remove_list_redundancies([
|
||||||
|
@ -387,42 +394,36 @@ class LabelledString(_StringSVG):
|
||||||
|
|
||||||
def get_group_substrs(self) -> list[str]:
|
def get_group_substrs(self) -> list[str]:
|
||||||
group_labels, _ = self.get_group_span_items()
|
group_labels, _ = self.get_group_span_items()
|
||||||
|
if not group_labels:
|
||||||
|
return []
|
||||||
|
|
||||||
ordered_spans = [
|
ordered_spans = [
|
||||||
self.label_span_list[label] if label != -1 else self.full_span
|
self.label_span_list[label] if label != -1 else self.full_span
|
||||||
for label in group_labels
|
for label in group_labels
|
||||||
]
|
]
|
||||||
ordered_containing_labels = [
|
interval_spans = [
|
||||||
self.containing_labels_dict[span]
|
(
|
||||||
for span in ordered_spans
|
next_span[0]
|
||||||
]
|
if self.span_contains(prev_span, next_span)
|
||||||
ordered_span_begins, ordered_span_ends = zip(*ordered_spans)
|
else prev_span[1],
|
||||||
span_begins = [
|
prev_span[1]
|
||||||
prev_end if prev_label in containing_labels else curr_begin
|
if self.span_contains(next_span, prev_span)
|
||||||
for prev_end, prev_label, containing_labels, curr_begin in zip(
|
else next_span[0]
|
||||||
ordered_span_ends[:-1], group_labels[:-1],
|
)
|
||||||
ordered_containing_labels[1:], ordered_span_begins[1:]
|
for prev_span, next_span in self.get_neighbouring_pairs(
|
||||||
|
ordered_spans
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
span_ends = [
|
|
||||||
next_begin if next_label in containing_labels else curr_end
|
|
||||||
for next_begin, next_label, containing_labels, curr_end in zip(
|
|
||||||
ordered_span_begins[1:], group_labels[1:],
|
|
||||||
ordered_containing_labels[:-1], ordered_span_ends[:-1]
|
|
||||||
)
|
|
||||||
]
|
|
||||||
spans = list(zip(
|
|
||||||
(ordered_span_begins[0], *span_begins),
|
|
||||||
(*span_ends, ordered_span_ends[-1])
|
|
||||||
))
|
|
||||||
shrinked_spans = [
|
shrinked_spans = [
|
||||||
self.shrink_span(span, self.skipped_spans)
|
self.shrink_span(span)
|
||||||
for span in spans
|
for span in self.get_complement_spans(
|
||||||
|
interval_spans, (ordered_spans[0][0], ordered_spans[-1][1])
|
||||||
|
)
|
||||||
]
|
]
|
||||||
group_substrs = [
|
return [
|
||||||
self.get_cleaned_substr(span) if span[0] < span[1] else ""
|
self.get_cleaned_substr(span) if span[0] < span[1] else ""
|
||||||
for span in shrinked_spans
|
for span in shrinked_spans
|
||||||
]
|
]
|
||||||
return group_substrs
|
|
||||||
|
|
||||||
def get_submob_groups(self) -> VGroup:
|
def get_submob_groups(self) -> VGroup:
|
||||||
_, submob_spans = self.get_group_span_items()
|
_, submob_spans = self.get_group_span_items()
|
||||||
|
@ -433,18 +434,17 @@ class LabelledString(_StringSVG):
|
||||||
|
|
||||||
# Selector
|
# Selector
|
||||||
|
|
||||||
def find_span_components_of_custom_span(
|
def find_span_components(self, custom_span: Span) -> list[Span]:
|
||||||
self, custom_span: Span
|
shrinked_span = self.shrink_span(custom_span)
|
||||||
) -> list[Span]:
|
if shrinked_span[0] >= shrinked_span[1]:
|
||||||
if custom_span[0] >= custom_span[1]:
|
|
||||||
return []
|
return []
|
||||||
|
|
||||||
indices = remove_list_redundancies(list(it.chain(
|
indices = remove_list_redundancies(list(it.chain(
|
||||||
self.full_span,
|
self.full_span,
|
||||||
*self.label_span_list
|
*self.label_span_list
|
||||||
)))
|
)))
|
||||||
span_begin = self.take_nearest_value(indices, custom_span[0], 0)
|
span_begin = self.take_nearest_value(indices, shrinked_span[0], 0)
|
||||||
span_end = self.take_nearest_value(indices, custom_span[1] - 1, 1)
|
span_end = self.take_nearest_value(indices, shrinked_span[1] - 1, 1)
|
||||||
span_choices = sorted(filter(
|
span_choices = sorted(filter(
|
||||||
lambda span: self.span_contains((span_begin, span_end), span),
|
lambda span: self.span_contains((span_begin, span_end), span),
|
||||||
self.label_span_list
|
self.label_span_list
|
||||||
|
@ -463,19 +463,19 @@ class LabelledString(_StringSVG):
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def get_parts_by_custom_span(self, custom_span: Span) -> VGroup:
|
def get_parts_by_custom_span(self, custom_span: Span) -> VGroup:
|
||||||
spans = self.find_span_components_of_custom_span(custom_span)
|
labels = [
|
||||||
labels = set(it.chain(*[
|
label for label, span in enumerate(self.label_span_list)
|
||||||
self.containing_labels_dict[span]
|
if any([
|
||||||
for span in spans
|
self.span_contains(span_component, span)
|
||||||
]))
|
for span_component in self.find_span_components(custom_span)
|
||||||
|
])
|
||||||
|
]
|
||||||
return VGroup(*filter(
|
return VGroup(*filter(
|
||||||
lambda submob: submob.label in labels,
|
lambda submob: submob.label in labels,
|
||||||
self.submobjects
|
self.submobjects
|
||||||
))
|
))
|
||||||
|
|
||||||
def get_parts_by_string(self, substr: str) -> VGroup:
|
def get_parts_by_string(self, substr: str) -> VGroup:
|
||||||
if not substr:
|
|
||||||
return VGroup()
|
|
||||||
return VGroup(*[
|
return VGroup(*[
|
||||||
self.get_parts_by_custom_span(span)
|
self.get_parts_by_custom_span(span)
|
||||||
for span in self.find_substr(substr)
|
for span in self.find_substr(substr)
|
||||||
|
|
|
@ -1,6 +1,5 @@
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import re
|
|
||||||
import colour
|
import colour
|
||||||
from typing import Union, Sequence
|
from typing import Union, Sequence
|
||||||
|
|
||||||
|
@ -57,7 +56,7 @@ class MTex(LabelledString):
|
||||||
|
|
||||||
def get_file_path_by_content(self, content: str) -> str:
|
def get_file_path_by_content(self, content: str) -> str:
|
||||||
full_tex = self.get_tex_file_body(content)
|
full_tex = self.get_tex_file_body(content)
|
||||||
with display_during_execution(f"Writing \"{self.string}\""):
|
with display_during_execution(f"Writing \"{self.tex_string}\""):
|
||||||
file_path = self.tex_to_svg_file_path(full_tex)
|
file_path = self.tex_to_svg_file_path(full_tex)
|
||||||
return file_path
|
return file_path
|
||||||
|
|
||||||
|
@ -116,19 +115,19 @@ class MTex(LabelledString):
|
||||||
if (span[1] - span[0]) % 2 == 1
|
if (span[1] - span[0]) % 2 == 1
|
||||||
]
|
]
|
||||||
|
|
||||||
def get_unescaped_char_spans(self, *chars: str):
|
def get_unescaped_char_spans(self, chars: str):
|
||||||
return sorted(filter(
|
return sorted(filter(
|
||||||
lambda span: span[0] - 1 not in self.backslash_indices,
|
lambda span: span[0] - 1 not in self.backslash_indices,
|
||||||
self.find_substr(*chars)
|
self.find_substrs(list(chars))
|
||||||
))
|
))
|
||||||
|
|
||||||
def get_brace_index_pairs(self) -> list[Span]:
|
def get_brace_index_pairs(self) -> list[Span]:
|
||||||
string = self.string
|
|
||||||
left_brace_indices = []
|
left_brace_indices = []
|
||||||
right_brace_indices = []
|
right_brace_indices = []
|
||||||
left_brace_indices_stack = []
|
left_brace_indices_stack = []
|
||||||
for index, _ in self.get_unescaped_char_spans("{", "}"):
|
for span in self.get_unescaped_char_spans("{}"):
|
||||||
if string[index] == "{":
|
index = span[0]
|
||||||
|
if self.get_substr(span) == "{":
|
||||||
left_brace_indices_stack.append(index)
|
left_brace_indices_stack.append(index)
|
||||||
else:
|
else:
|
||||||
if not left_brace_indices_stack:
|
if not left_brace_indices_stack:
|
||||||
|
@ -141,18 +140,18 @@ class MTex(LabelledString):
|
||||||
return list(zip(left_brace_indices, right_brace_indices))
|
return list(zip(left_brace_indices, right_brace_indices))
|
||||||
|
|
||||||
def get_script_char_spans(self) -> list[int]:
|
def get_script_char_spans(self) -> list[int]:
|
||||||
return self.get_unescaped_char_spans("_", "^")
|
return self.get_unescaped_char_spans("_^")
|
||||||
|
|
||||||
def get_script_content_spans(self) -> list[Span]:
|
def get_script_content_spans(self) -> list[Span]:
|
||||||
result = []
|
result = []
|
||||||
brace_indices_dict = dict(self.brace_index_pairs)
|
brace_indices_dict = dict(self.brace_index_pairs)
|
||||||
|
script_pattern = r"[a-zA-Z0-9]|\\[a-zA-Z]+"
|
||||||
for script_char_span in self.script_char_spans:
|
for script_char_span in self.script_char_spans:
|
||||||
span_begin = self.rslide(script_char_span[1], self.space_spans)
|
span_begin = self.match(r"\s*", pos=script_char_span[1]).end()
|
||||||
if span_begin in brace_indices_dict.keys():
|
if span_begin in brace_indices_dict.keys():
|
||||||
span_end = brace_indices_dict[span_begin] + 1
|
span_end = brace_indices_dict[span_begin] + 1
|
||||||
else:
|
else:
|
||||||
pattern = re.compile(r"[a-zA-Z0-9]|\\[a-zA-Z]+")
|
match_obj = self.match(script_pattern, pos=span_begin)
|
||||||
match_obj = pattern.match(self.string, pos=span_begin)
|
|
||||||
if not match_obj:
|
if not match_obj:
|
||||||
script_name = {
|
script_name = {
|
||||||
"_": "subscript",
|
"_": "subscript",
|
||||||
|
@ -169,7 +168,7 @@ class MTex(LabelledString):
|
||||||
def get_script_spans(self) -> list[Span]:
|
def get_script_spans(self) -> list[Span]:
|
||||||
return [
|
return [
|
||||||
(
|
(
|
||||||
self.lslide(script_char_span[0], self.space_spans),
|
self.search(r"\s*$", endpos=script_char_span[0]).start(),
|
||||||
script_content_span[1]
|
script_content_span[1]
|
||||||
)
|
)
|
||||||
for script_char_span, script_content_span in zip(
|
for script_char_span, script_content_span in zip(
|
||||||
|
@ -200,7 +199,7 @@ class MTex(LabelledString):
|
||||||
")",
|
")",
|
||||||
r"(?![a-zA-Z])"
|
r"(?![a-zA-Z])"
|
||||||
])
|
])
|
||||||
for match_obj in re.finditer(pattern, self.string):
|
for match_obj in self.finditer(pattern):
|
||||||
span_begin, cmd_end = match_obj.span()
|
span_begin, cmd_end = match_obj.span()
|
||||||
if span_begin not in backslash_indices:
|
if span_begin not in backslash_indices:
|
||||||
continue
|
continue
|
||||||
|
@ -243,7 +242,7 @@ class MTex(LabelledString):
|
||||||
return result
|
return result
|
||||||
|
|
||||||
def get_external_specified_spans(self) -> list[Span]:
|
def get_external_specified_spans(self) -> list[Span]:
|
||||||
return self.find_substr(*self.tex_to_color_map.keys())
|
return self.find_substrs(list(self.tex_to_color_map.keys()))
|
||||||
|
|
||||||
def get_label_span_list(self) -> list[Span]:
|
def get_label_span_list(self) -> list[Span]:
|
||||||
result = self.script_content_spans.copy()
|
result = self.script_content_spans.copy()
|
||||||
|
@ -284,7 +283,8 @@ class MTex(LabelledString):
|
||||||
return []
|
return []
|
||||||
return self.command_repl_items.copy()
|
return self.command_repl_items.copy()
|
||||||
|
|
||||||
def get_has_predefined_colors(self) -> bool:
|
@property
|
||||||
|
def has_predefined_colors(self) -> bool:
|
||||||
return bool(self.command_repl_items)
|
return bool(self.command_repl_items)
|
||||||
|
|
||||||
# Post-parsing
|
# Post-parsing
|
||||||
|
|
|
@ -58,6 +58,7 @@ class SVGMobject(VMobject):
|
||||||
},
|
},
|
||||||
"path_string_config": {},
|
"path_string_config": {},
|
||||||
}
|
}
|
||||||
|
|
||||||
def __init__(self, file_name: str | None = None, **kwargs):
|
def __init__(self, file_name: str | None = None, **kwargs):
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
self.file_name = file_name or self.file_name
|
self.file_name = file_name or self.file_name
|
||||||
|
|
|
@ -17,7 +17,6 @@ from manimpango import MarkupUtils
|
||||||
from manimlib.logger import log
|
from manimlib.logger import log
|
||||||
from manimlib.constants import *
|
from manimlib.constants import *
|
||||||
from manimlib.mobject.svg.labelled_string import LabelledString
|
from manimlib.mobject.svg.labelled_string import LabelledString
|
||||||
from manimlib.mobject.types.vectorized_mobject import VGroup
|
|
||||||
from manimlib.utils.customization import get_customization
|
from manimlib.utils.customization import get_customization
|
||||||
from manimlib.utils.tex_file_writing import tex_hash
|
from manimlib.utils.tex_file_writing import tex_hash
|
||||||
from manimlib.utils.config_ops import digest_config
|
from manimlib.utils.config_ops import digest_config
|
||||||
|
@ -30,9 +29,11 @@ from typing import TYPE_CHECKING
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from manimlib.mobject.types.vectorized_mobject import VMobject
|
from manimlib.mobject.types.vectorized_mobject import VMobject
|
||||||
|
from manimlib.mobject.types.vectorized_mobject import VGroup
|
||||||
ManimColor = Union[str, colour.Color, Sequence[float]]
|
ManimColor = Union[str, colour.Color, Sequence[float]]
|
||||||
Span = tuple[int, int]
|
Span = tuple[int, int]
|
||||||
|
|
||||||
|
|
||||||
TEXT_MOB_SCALE_FACTOR = 0.0076
|
TEXT_MOB_SCALE_FACTOR = 0.0076
|
||||||
DEFAULT_LINE_SPACING_SCALE = 0.6
|
DEFAULT_LINE_SPACING_SCALE = 0.6
|
||||||
|
|
||||||
|
@ -313,19 +314,14 @@ class MarkupText(LabelledString):
|
||||||
if isinstance(substr_or_span, str):
|
if isinstance(substr_or_span, str):
|
||||||
return self.find_substr(substr_or_span)
|
return self.find_substr(substr_or_span)
|
||||||
|
|
||||||
string_len = len(self.string)
|
span = tuple([
|
||||||
span_begin, span_end = substr_or_span
|
(index if index >= 0 else index + self.string_len)
|
||||||
if span_begin is None:
|
if index is not None else substitute
|
||||||
span_begin = 0
|
for index, substitute in zip(substr_or_span, self.full_span)
|
||||||
elif span_begin < 0:
|
])
|
||||||
span_begin += string_len
|
if span[0] >= span[1]:
|
||||||
if span_end is None:
|
|
||||||
span_end = string_len
|
|
||||||
elif span_end < 0:
|
|
||||||
span_end += string_len
|
|
||||||
if span_begin >= span_end:
|
|
||||||
return []
|
return []
|
||||||
return [(span_begin, span_end)]
|
return [span]
|
||||||
|
|
||||||
# Pre-parsing
|
# Pre-parsing
|
||||||
|
|
||||||
|
@ -339,7 +335,7 @@ class MarkupText(LabelledString):
|
||||||
attr_pattern = r"""(\w+)\s*\=\s*(['"])(.*?)\2"""
|
attr_pattern = r"""(\w+)\s*\=\s*(['"])(.*?)\2"""
|
||||||
begin_match_obj_stack = []
|
begin_match_obj_stack = []
|
||||||
match_obj_pairs = []
|
match_obj_pairs = []
|
||||||
for match_obj in re.finditer(tag_pattern, self.string):
|
for match_obj in self.finditer(tag_pattern):
|
||||||
if not match_obj.group(1):
|
if not match_obj.group(1):
|
||||||
begin_match_obj_stack.append(match_obj)
|
begin_match_obj_stack.append(match_obj)
|
||||||
else:
|
else:
|
||||||
|
@ -475,7 +471,7 @@ class MarkupText(LabelledString):
|
||||||
breakup_indices
|
breakup_indices
|
||||||
))
|
))
|
||||||
return list(filter(
|
return list(filter(
|
||||||
lambda span: self.string[slice(*span)].strip(),
|
lambda span: self.get_substr(span).strip(),
|
||||||
self.get_neighbouring_pairs(breakup_indices)
|
self.get_neighbouring_pairs(breakup_indices)
|
||||||
))
|
))
|
||||||
|
|
||||||
|
@ -511,7 +507,8 @@ class MarkupText(LabelledString):
|
||||||
) -> list[tuple[Span, str]]:
|
) -> list[tuple[Span, str]]:
|
||||||
return self.command_repl_items.copy()
|
return self.command_repl_items.copy()
|
||||||
|
|
||||||
def get_has_predefined_colors(self) -> bool:
|
@property
|
||||||
|
def has_predefined_colors(self) -> bool:
|
||||||
return any([
|
return any([
|
||||||
key in COLOR_RELATED_KEYS
|
key in COLOR_RELATED_KEYS
|
||||||
for _, attr_dict in self.predefined_attr_dicts
|
for _, attr_dict in self.predefined_attr_dicts
|
||||||
|
|
Loading…
Add table
Reference in a new issue