A community-maintained Python framework for creating mathematical animations.
Fixed Some bugs of code_mobject.py and Text_mobject.py (#198)
Navpreet Devpuri1f02ae066564
diff --git a/manim/mobject/svg/code_mobject.py b/manim/mobject/svg/code_mobject.pyindex 86ba413de..16a73b086 100644--- a/manim/mobject/svg/code_mobject.py+++ b/manim/mobject/svg/code_mobject.py@@ -1,67 +1,142 @@-"""-1) Code is VGroup() with three things- 1.1) Code[0] is Code.background_mobject- which can be a- 1.1.1) Rectangle() if background == "rectangle"- 1.1.2) VGroup() of Rectangle() and Dot() for three buttons if background == "window"- 1.2) Code[1] is Code.line_numbers Which is a Paragraph() object, this mean you can use- Code.line_numbers[0] or Code[1][0] to access first line number- 1.3) Code[2] is Code.code- 1.3.1) Which is a Paragraph() with color highlighted, this mean you can use- Code.code[1] or Code[2][1]- line number 1- Code.code[1][0] or Code.code[1][0]- first character of line number 1- Code.code[1][0:5] or Code.code[1][0:5]- first five characters of line number 1-"""--__all__ = ["Code","hilite_me",- "get_default_style",- "insert_line_numbers",+ "insert_line_numbers_in_html",]-import htmlimport osfrom ...constants import *-from ...container import Container-from ...mobject.geometry import RoundedRectangle+from ...mobject.geometry import RoundedRectangle, Dotfrom ...mobject.shape_matchers import SurroundingRectanglefrom ...mobject.svg.text_mobject import Paragraphfrom ...mobject.types.vectorized_mobject import VGroup+from pygments.lexers import guess_lexer_for_filenameimport refrom pygments import highlightfrom pygments.lexers import get_lexer_by_namefrom pygments.formatters.html import HtmlFormatter-+from pygments.styles import get_all_stylesclass Code(VGroup):+ """Class Code is used to display code with color highlighted.++ Code.styles_list static variable is containing list of names of all styles+ Code is VGroup() with three things+ Code[0] is Code.background_mobject is a VGroup()+ VGroup() of SurroundingRectangle() if background == "rectangle"+ VGroup() of RoundedRectangle() and Dot() for three buttons if background == "window"+ Code[1] is Code.line_numbers Which is a Paragraph() object, this mean you can use+ Code.line_numbers[0] or Code.line_numbers.chars[0] or Code[1].chars[0] to access first line number+ Code[2] is Code.code+ Which is a Paragraph() with color highlighted, this mean you can use+ Code.code[1] or Code.code.chars[1] or Code[2].chars[1]+ line number 1+ Code.code[1][0] or Code.code.chars[1][0] or Code[2].chars[1][0]+ first character of line number 1+ Code.code[1][0:5] Code.code.chars[1][0:5] or Code[2].chars[1][0:5]+ first five characters of line number 1+ Code.code[][] Code.code.chars[][] or Code[2].chars[][] will create problems when using Transform() because of invisible characters+ so, before using Transform() remove invisible characters by using remove_invisible_chars()++ Parameters+ ----------+ file_name : :class:`str`+ Name of the code file to display.+ tab_width : :class:`int`, optional+ Number of space characters corresponding to a tab character. Defaults to 3.+ line_spacing : :class:`float`, optional+ Amount of space between lines in relation to font size. Defaults to 0.3, which means 30% of font size.+ scale_factor : class:`float`, optional+ A number which scales displayed code. Defaults to 0.5.+ font : :class:`str`, optional+ The name of the text font to be used. Defaults to `"Monospac821 BT"`.+ stroke_width : class:`float`, optional+ Stroke width for text. 0 is recommended, and the default.+ margin: class :`float`, optional+ Inner margin of text from the background. Defaults to 0.3.+ indentation_chars : :class:`str`, optional+ "Indentation chars" refers to the spaces/tabs at the beginning of a given code line. Defaults to `" "`.+ background : :class:`str`, optional+ Defines the background's type. Currently supports only `"rectangle"` (default) and `"window"`.+ background_stroke_width : class:`float`, optional+ Defines the stroke width of the background. Defaults to 1.+ background_stroke_color : class:`str`, optional+ Defines the stroke color for the background. Defaults to `WHITE`.+ corner_radius : :class:`float`, optional+ Defines the corner radius for the background. Defaults to 0.2.+ insert_line_no : :class:`bool`, optional+ Defines whether line numbers should be inserted in displayed code. Defaults to `True`.+ line_no_from : :class:`int`, optional+ Defines the first line's number in the line count. Defaults to 1.+ line_no_buff : :class:`float`, optional+ Defines the spacing between line numbers and displayed code. Defaults to 0.4.+ style : :class:`str`, optional+ Defines the style type of displayed code. You can see possible names of styles in with :attr:`styles_list`. Defaults to `"vim"`.+ language : Optional[:class:`str`], optional+ Specifies the programming language the given code was written in. If `None` (the default), the language will be automatically detected. For the list of possible options, visit https://pygments.org/docs/lexers/ and look for 'aliases or short names'.+ generate_html_file : :class:`bool`, optional+ Defines whether to generate highlighted html code to the folder `assets/codes/generated_html_files`. Defaults to `False`.++ Attributes+ ----------+ background_mobject : :class:`~.VGroup`+ To display background according to background type specified by background in Parameters.+ VGroup with SurroundingRectangle() if background == "rectangle"+ VGroup with RoundedRectangle() and Dot() for three buttons if background == "window"+ line_numbers : :class:`~.Paragraph`+ To display line numbers of displayed code if insert_line_no == True.+ code : :class:`~.Paragraph`+ To display highlighted code.++ Examples+ --------+ Normal usage::+ helloworldcpp = Code(+ "helloworldcpp.cpp",+ tab_width=4,+ background_stroke_width=1,+ background_stroke_color=WHITE,+ insert_line_no=True,+ style=Code.styles_list[15],+ background="window",+ language="cpp",+ )+ Remove unwanted invisible characters::+ self.play(Transform(remove_invisible_chars(Code.code.chars[0:2]), remove_invisible_chars(Code.code.chars[3][0:3])))+ remove_invisible_chars(Code.code) or remove_invisible_chars(Code)+ """++ # tuples in the form (name, aliases, filetypes, mimetypes)+ # 'language' of CONFIG is aliases or short names+ # For more information about pygments.lexers visit https://pygments.org/docs/lexers/+ # from pygments.lexers import get_all_lexers+ # all_lexers = get_all_lexers()+ styles_list = list(get_all_styles())+ # For more information about pygments.styles visit https://pygments.org/docs/styles/CONFIG = {"tab_width": 3,- "line_spacing": 0.1,+ "line_spacing": 0.3,"scale_factor": 0.5,- "run_time": 1,"font": "Monospac821 BT","stroke_width": 0,"margin": 0.3,- "indentation_char": " ",+ "indentation_chars": " ","background": "rectangle", # or window+ "background_stroke_width": 1,+ "background_stroke_color": WHITE,"corner_radius": 0.2,"insert_line_no": True,"line_no_from": 1,"line_no_buff": 0.4,"style": "vim",- "language": "cpp",+ "language": None,"generate_html_file": False,}def __init__(self, file_name=None, **kwargs):- Container.__init__(self, **kwargs)+ VGroup.__init__(self, **kwargs)self.file_name = file_name or self.file_nameself.ensure_valid_file()self.style = self.style.lower()@@ -74,35 +149,36 @@ class Code(VGroup):if self.insert_line_no:self.line_numbers = self.gen_line_numbers()self.line_numbers.next_to(self.code, direction=LEFT, buff=self.line_no_buff)-if self.background == "rectangle":if self.insert_line_no:forground = VGroup(self.code, self.line_numbers)else:forground = self.code- self.background_mobject = SurroundingRectangle(+ rect = SurroundingRectangle(forground,buff=self.margin,color=self.background_color,fill_color=self.background_color,- stroke_width=0,+ stroke_width=self.background_stroke_width,+ stroke_color=self.background_stroke_color,fill_opacity=1,)- self.background_mobject.round_corners(self.corner_radius)+ rect.round_corners(self.corner_radius)+ self.background_mobject = VGroup(rect)else:if self.insert_line_no:forground = VGroup(self.code, self.line_numbers)else:forground = self.code-height = forground.get_height() + 0.1 * 3 + 2 * self.marginwidth = forground.get_width() + 0.1 * 3 + 2 * self.margin- rrect = RoundedRectangle(+ rect = RoundedRectangle(corner_radius=self.corner_radius,height=height,width=width,- stroke_width=0,+ stroke_width=self.background_stroke_width,+ stroke_color=self.background_stroke_color,color=self.background_color,fill_opacity=1,)@@ -117,40 +193,26 @@ class Code(VGroup):+ LEFT * (width / 2 - 0.1 * 5 - self.corner_radius / 2 - 0.05))- self.background_mobject = VGroup(rrect, buttons)+ self.background_mobject = VGroup(rect, buttons)x = (height - forground.get_height()) / 2 - 0.1 * 3self.background_mobject.shift(forground.get_center())self.background_mobject.shift(UP * x)-if self.insert_line_no:VGroup.__init__(- self, self.background_mobject, self.line_numbers, *self.code, **kwargs+ self, self.background_mobject, self.line_numbers, self.code, **kwargs)else:VGroup.__init__(self,self.background_mobject,Dot(fill_opacity=0, stroke_opacity=0),- *self.code,- **kwargs,+ self.code,+ **kwargs)-self.move_to(np.array([0, 0, 0]))- def apply_points_function_about_point(- self, func, about_point=None, about_edge=None- ):- if about_point is None:- if about_edge is None:- about_edge = self.get_corner(UP + LEFT)- about_point = self.get_critical_point(about_edge)- for mob in self.family_members_with_points():- mob.points -= about_point- mob.points = func(mob.points)- mob.points += about_point- return self-def ensure_valid_file(self):+ """Function to validate file."""if self.file_name is None:raise Exception("Must specify file for Code")possible_paths = [@@ -161,9 +223,18 @@ class Code(VGroup):if os.path.exists(path):self.file_path = pathreturn- raise IOError("No file matching %s in codes directory" % self.file_name)+ raise IOError(+ "File %s not found. Please specify a correct file path" % self.file_name+ )def gen_line_numbers(self):+ """Function to generate line_numbers.++ Returns+ -------+ :class:`~.Paragraph`+ The generated line_numbers according to parameters.+ """line_numbers_array = []for line_no in range(0, self.code_json.__len__()):number = str(self.line_no_from + line_no)@@ -173,11 +244,20 @@ class Code(VGroup):line_spacing=self.line_spacing,alignment="right",font=self.font,- stroke_width=self.stroke_width,+ stroke_width=self.stroke_width).scale(self.scale_factor)+ for i in line_numbers:+ i.set_color(self.default_color)return line_numbersdef gen_colored_lines(self):+ """Function to generate code.++ Returns+ -------+ :class:`~.Paragraph`+ The generated code according to parameters.+ """lines_text = []for line_no in range(0, self.code_json.__len__()):line_str = ""@@ -188,12 +268,11 @@ class Code(VGroup):*[i for i in lines_text],line_spacing=self.line_spacing,tab_width=self.tab_width,- alignment="left",font=self.font,- stroke_width=self.stroke_width,+ stroke_width=self.stroke_width).scale(self.scale_factor)for line_no in range(code.__len__()):- line = code[line_no]+ line = code.chars[line_no]line_char_index = self.tab_spaces[line_no]for word_index in range(self.code_json[line_no].__len__()):line[@@ -204,17 +283,20 @@ class Code(VGroup):return codedef gen_html_string(self):+ """Function to generate html string with code highlighted and stores in variable html_string."""file = open(self.file_path, "r")code_str = file.read()file.close()self.html_string = hilite_me(code_str,self.language,- {},self.style,self.insert_line_no,"border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;",+ self.file_path,+ self.line_no_from)+if self.generate_html_file:os.makedirs(os.path.join("assets", "codes", "generated_html_files"), exist_ok=True@@ -229,6 +311,13 @@ class Code(VGroup):file.close()def gen_code_json(self):+ """Function to background_color, generate code_json and tab_spaces from html_string.+ background_color is just background color of displayed code.+ code_json is 2d array with rows as line numbers+ and columns as a array with length 2 having text and text's color value.+ tab_spaces is 2d array with rows as line numbers+ and columns as corresponding number of indentation_chars in front of that line in code.+ """if (self.background_color == "#111111"or self.background_color == "#272822"@@ -238,6 +327,7 @@ class Code(VGroup):self.default_color = "#ffffff"else:self.default_color = "#000000"+ # print(self.default_color,self.background_color)for i in range(3, -1, -1):self.html_string = self.html_string.replace("</" + " " * i, "</")for i in range(10, -1, -1):@@ -267,33 +357,32 @@ class Code(VGroup):# print(lines[line_index])self.code_json.append([])code_json_line_index = code_json_line_index + 1- if lines[line_index].startswith(self.indentation_char):+ if lines[line_index].startswith(self.indentation_chars):start_point = lines[line_index].find("<")starting_string = lines[line_index][:start_point]- indentation_char_count = lines[line_index][:start_point].count(- self.indentation_char+ indentation_chars_count = lines[line_index][:start_point].count(+ self.indentation_chars)if (starting_string.__len__()- != indentation_char_count * self.indentation_char.__len__()+ != indentation_chars_count * self.indentation_chars.__len__()):lines[line_index] = (- "\t" * indentation_char_count+ "\t" * indentation_chars_count+ starting_string[- starting_string.rfind(self.indentation_char)- + self.indentation_char.__len__() :+ starting_string.rfind(self.indentation_chars)+ + self.indentation_chars.__len__() :]+ lines[line_index][start_point:])else:lines[line_index] = (- "\t" * indentation_char_count + lines[line_index][start_point:]+ "\t" * indentation_chars_count + lines[line_index][start_point:])-- indentation_char_count = 0- while lines[line_index][indentation_char_count] == "\t":- indentation_char_count = indentation_char_count + 1- self.tab_spaces.append(indentation_char_count)+ indentation_chars_count = 0+ while lines[line_index][indentation_chars_count] == "\t":+ indentation_chars_count = indentation_chars_count + 1+ self.tab_spaces.append(indentation_chars_count)# print(lines[line_index])lines[line_index] = self.correct_non_span(lines[line_index])# print(lines[line_index])@@ -307,7 +396,6 @@ class Code(VGroup):color = words[word_index][color_index + starti : color_index + starti + 7]-start_point = words[word_index].find(">")end_point = words[word_index].find("</span>")text = words[word_index][start_point + 1 : end_point]@@ -318,6 +406,18 @@ class Code(VGroup):# print(self.code_json)def correct_non_span(self, line_str):+ """Function put text color to those strings that don't have one according to background_color of displayed code.++ Parameters+ ---------+ line_str : :class:`str`+ Takes a html element's string to put color to it according to background_color of displayed code.++ Returns+ -------+ :class:`str`+ The generated html element's string with having color attributes.+ """words = line_str.split("</span>")line_str = ""for i in range(0, words.__len__()):@@ -357,8 +457,26 @@ class Code(VGroup):return line_str-def hilite_me(code, lexer, options, style, linenos, divstyles):- lexer = lexer or "python"+def hilite_me(code, language, style, insert_line_no, divstyles, file_path, line_no_from):+ """Function to highlight code from string to html.++ Parameters+ ---------+ code : :class:`str`+ Code string.+ language : :class:`str`+ The name of the programming language the given code was written in.+ style : :class:`str`+ Code style name.+ insert_line_no : :class:`bool`+ Defines whether line numbers should be inserted in the html file.+ divstyles : :class:`str`+ Some html css styles.+ file_path : :class:`str`+ Path of code file.+ line_no_from : :class:`int`+ Defines the first line's number in the line count.+ """style = style or "colorful"defstyles = "overflow:auto;width:auto;"@@ -370,28 +488,41 @@ def hilite_me(code, lexer, options, style, linenos, divstyles):cssstyles=defstyles + divstyles,prestyles="margin: 0",)- html = highlight(code, get_lexer_by_name(lexer, **options), formatter)- if linenos:- html = insert_line_numbers(html)- html = "<!-- HTML generated using hilite.me -->" + html+ if language is None:+ lexer = guess_lexer_for_filename(file_path, code)+ html = highlight(code, lexer, formatter)+ else:+ html = highlight(code, get_lexer_by_name(language, **{}), formatter)+ if insert_line_no:+ html = insert_line_numbers_in_html(html, line_no_from)+ html = "<!-- HTML generated by Code() -->" + htmlreturn html-def get_default_style():- return "border:solid gray;border-width:.1em .1em .1em .8em;padding:.2em .6em;"+def insert_line_numbers_in_html(html, line_no_from):+ """Function that inserts line numbers in the highlighted HTML code.+ Parameters+ ---------+ html : :class:`str`+ html string of highlighted code.+ line_no_from : :class:`int`+ Defines the first line's number in the line count.-def insert_line_numbers(html):+ Returns+ -------+ :class:`str`+ The generated html string with having line numbers.+ """match = re.search("(<pre[^>]*>)(.*)(</pre>)", html, re.DOTALL)if not match:return html-pre_open = match.group(1)pre = match.group(2)pre_close = match.group(3)html = html.replace(pre_close, "</pre></td></tr></table>")- numbers = range(1, pre.count("\n") + 1)+ numbers = range(line_no_from, line_no_from + pre.count("\n") + 1)format = "%" + str(len(str(numbers[-1]))) + "i"lines = "\n".join(format % i for i in numbers)html = html.replace(diff --git a/manim/mobject/svg/text_mobject.py b/manim/mobject/svg/text_mobject.pyindex c161d5d1b..c36a3464b 100644--- a/manim/mobject/svg/text_mobject.py+++ b/manim/mobject/svg/text_mobject.py@@ -1,5 +1,4 @@-__all__ = ["TextSetting", "Text", "TextWithFixHeight", "Paragraph"]-+__all__ = ["TextSetting", "Text", "Paragraph"]import reimport os@@ -19,6 +18,40 @@ from ...utils.config_ops import digest_configTEXT_MOB_SCALE_FACTOR = 0.05+def remove_invisible_chars(mobject):+ """Fuction to remove unwanted invisble characters from some mobject++ Parameters+ ---------+ mobject : :class:`~.SVGMobject`+ Any SVGMobject from which we want to remove unwanted invisble characters.++ Returns+ -------+ :class:`~.SVGMobject`+ The SVGMobject without unwanted invisble characters.+ """++ iscode = False+ if mobject.__class__.__name__ == "Text":+ mobject = mobject[:]+ elif mobject.__class__.__name__ == "Code":+ iscode = True+ code = mobject+ mobject = mobject.code+ mobject_without_dots = VGroup()+ if mobject[0].__class__ == VGroup:+ for i in range(mobject.__len__()):+ mobject_without_dots.add(VGroup())+ mobject_without_dots[i].add(*[k for k in mobject[i] if k.__class__ != Dot])+ else:+ mobject_without_dots.add(*[k for k in mobject if k.__class__ != Dot])+ if iscode:+ code.code = mobject_without_dots+ return code+ return mobject_without_dots++class TextSetting(object):def __init__(self, start, end, font, slant, weight, line_num=-1):self.start = start@@ -30,6 +63,14 @@ class TextSetting(object):class Text(SVGMobject):+ """ Text is used for displaying Text.+ Text is VGroup() of each characters+ that mean you can use it like+ Text[0:5] or Text.chars[0:5] to access first five characters+ Text[0:5] or Text or Text.chars[0:5] will create problems when using Transform() because of invisible characters+ so, before using Transform() remove invisible characters by using remove_invisible_chars()+ for example self.play(Transform(remove_invisible_chars(text.chars[0:4]), remove_invisible_chars(text2.chars[0:2])))+ """CONFIG = {# Mobject"color": WHITE,@@ -42,7 +83,7 @@ class Text(SVGMobject):# Text"font": "","gradient": None,- "lsh": -1,+ "line_spacing": -1,"size": 1,"slant": NORMAL,"weight": NORMAL,@@ -57,19 +98,22 @@ class Text(SVGMobject):def __init__(self, text, **config):self.full2short(config)digest_config(self, config)+ self.original_text = texttext_without_tabs = textif text.find("\t") != -1:text_without_tabs = text.replace("\t", " " * self.tab_width)self.text = text_without_tabs- self.lsh = self.size if self.lsh == -1 else self.lsh-+ if self.line_spacing == -1:+ self.line_spacing = self.size + self.size * 0.3+ else:+ self.line_spacing = self.size + self.size * self.line_spacingfile_name = self.text2svg()self.remove_last_M(file_name)SVGMobject.__init__(self, file_name, **config)- self.apply_front_and_end_spaces()self.text = text- self.apply_space_chars()-+ self.submobjects = [*self.gen_chars()]+ self.chars = VGroup(*self.submobjects)+ self.text = text_without_tabs.replace(" ", "").replace("\n", "")nppc = self.n_points_per_cubic_curvefor each in self:if len(each.points) == 0:@@ -87,105 +131,37 @@ class Text(SVGMobject):each.add_line_to(last)last = points[index + 1]each.add_line_to(last)-if self.t2c:self.set_color_by_t2c()if self.gradient:self.set_color_by_gradient(*self.gradient)if self.t2g:self.set_color_by_t2g()-# anti-aliasingif self.height is None and self.width is None:self.scale(TEXT_MOB_SCALE_FACTOR)- def get_space_width(self):- size = self.size * 10-- dir_name = file_writer_config["text_dir"]- file_name = os.path.join(dir_name, "space") + ".svg"-- surface = cairo.SVGSurface(file_name, 600, 400)- context = cairo.Context(surface)- context.set_font_size(size)- context.move_to(START_X, START_Y)- context.select_font_face(- self.font, self.str2slant(self.slant), self.str2weight(self.weight)- )- context.move_to(START_X, START_Y)- context.show_text("_")- surface.finish()- svg_with_space = SVGMobject(- file_name,- height=self.height,- width=self.width,- stroke_width=self.stroke_width,- should_center=self.should_center,- unpack_groups=self.unpack_groups,- )- space_width = svg_with_space.get_width()- return space_width-- def apply_front_and_end_spaces(self):- space_width = self.get_space_width()- max_height = self.get_height()- front_spaces_count = 0- i = -1- for i in range(self.text.__len__()):- if self.text[i] == " ":- front_spaces_count += 1- continue- else:- break- first_visible_char_index = i- if first_visible_char_index != 0:- space = Rectangle(- width=space_width * front_spaces_count,- height=max_height,- fill_opacity=0,- stroke_opacity=0,- stroke_width=0,- )- text_width = self.get_width()- space.move_to(np.array([-text_width / 2, max_height / 2, 0]))- self.next_to(space, direction=RIGHT, buff=0)- self.submobjects.insert(0, space)-- i = -1- last_spaces_count = 0- for i in range(self.text.__len__() - 1, -1, -1):- if self.text[i] == " ":- last_spaces_count += 1- continue- else:- break- last_visible_char_index = i- if last_visible_char_index != self.text.__len__() - 1:- space = Rectangle(- width=space_width * last_spaces_count,- height=max_height,- fill_opacity=0,- stroke_opacity=0,- stroke_width=0,- )- text_width = self.get_width()- space.move_to(np.array([-text_width / 2, max_height / 2, 0]))- self.next_to(space, direction=LEFT, buff=0)- self.submobjects.append(space)- self.move_to(np.array([0, 0, 0]))-- def apply_space_chars(self):- char_index = 0- while char_index < self.text.__len__() - 1:- char_index += 1+ def gen_chars(self):+ chars = VGroup()+ submobjects_char_index = 0+ for char_index in range(self.text.__len__()):if (self.text[char_index] == " "or self.text[char_index] == "\t"or self.text[char_index] == "\n"):- space = Dot(fill_opacity=0, stroke_opacity=0)- space.move_to(self.submobjects[char_index - 1].get_center())- self.submobjects.insert(char_index, space)+ space = Dot(redius=0, fill_opacity=0, stroke_opacity=0)+ if char_index == 0:+ space.move_to(self.submobjects[submobjects_char_index].get_center())+ else:+ space.move_to(+ self.submobjects[submobjects_char_index - 1].get_center()+ )+ chars.add(space)+ else:+ chars.add(self.submobjects[submobjects_char_index])+ submobjects_char_index += 1+ return charsdef remove_last_M(self, file_name):with open(file_name, "r") as fpr:@@ -194,26 +170,23 @@ class Text(SVGMobject):with open(file_name, "w") as fpw:fpw.write(content)- def find_indexes(self, word):+ def find_indexes(self, word, text):m = re.match(r"\[([0-9\-]{0,}):([0-9\-]{0,})\]", word)if m:start = int(m.group(1)) if m.group(1) != "" else 0- end = int(m.group(2)) if m.group(2) != "" else len(self.text)- start = len(self.text) + start if start < 0 else start- end = len(self.text) + end if end < 0 else end+ end = int(m.group(2)) if m.group(2) != "" else len(text)+ start = len(text) + start if start < 0 else start+ end = len(text) + end if end < 0 else endreturn [(start, end)]-indexes = []- index = self.text.find(word)+ index = text.find(word)while index != -1:indexes.append((index, index + len(word)))- index = self.text.find(word, index + len(word))+ index = text.find(word, index + len(word))return indexesdef full2short(self, config):for kwargs in [config, self.CONFIG]:- if kwargs.__contains__("line_spacing_height"):- kwargs["lsh"] = kwargs.pop("line_spacing_height")if kwargs.__contains__("text2color"):kwargs["t2c"] = kwargs.pop("text2color")if kwargs.__contains__("text2font"):@@ -228,14 +201,14 @@ class Text(SVGMobject):def set_color_by_t2c(self, t2c=None):t2c = t2c if t2c else self.t2cfor word, color in list(t2c.items()):- for start, end in self.find_indexes(word):- self[start:end].set_color(color)+ for start, end in self.find_indexes(word, self.original_text):+ self.chars[start:end].set_color(color)def set_color_by_t2g(self, t2g=None):t2g = t2g if t2g else self.t2gfor word, gradient in list(t2g.items()):- for start, end in self.find_indexes(word):- self[start:end].set_color_by_gradient(*gradient)+ for start, end in self.find_indexes(word, self.original_text):+ self.chars[start:end].set_color_by_gradient(*gradient)def str2slant(self, string):if string == NORMAL:@@ -254,7 +227,7 @@ class Text(SVGMobject):def text2hash(self):settings = self.font + self.slant + self.weightsettings += str(self.t2f) + str(self.t2s) + str(self.t2w)- settings += str(self.lsh) + str(self.size)+ settings += str(self.line_spacing) + str(self.size)id_str = self.text + settingshasher = hashlib.sha256()hasher.update(id_str.encode())@@ -267,10 +240,9 @@ class Text(SVGMobject):fsw = [self.font, self.slant, self.weight]if t2x[i]:for word, x in list(t2x[i].items()):- for start, end in self.find_indexes(word):+ for start, end in self.find_indexes(word, self.text):fsw[i] = xsettings.append(TextSetting(start, end, *fsw))-# Set All text settings(default font slant weight)fsw = [self.font, self.slant, self.weight]settings.sort(key=lambda setting: setting.start)@@ -286,7 +258,7 @@ class Text(SVGMobject):if re.search(r"\n", self.text):line_num = 0- for start, end in self.find_indexes("\n"):+ for start, end in self.find_indexes("\n", self.text):for setting in settings:if setting.line_num == -1:setting.line_num = line_num@@ -299,28 +271,24 @@ class Text(SVGMobject):settings.append(new_setting)settings.sort(key=lambda setting: setting.start)break-for setting in settings:if setting.line_num == -1:setting.line_num = 0-return settingsdef text2svg(self):# anti-aliasingsize = self.size * 10- lsh = self.lsh * 10+ line_spacing = self.line_spacing * 10if self.font == "":if NOT_SETTING_FONT_MSG != "":- logger.warning(NOT_SETTING_FONT_MSG)-+ print(NOT_SETTING_FONT_MSG)dir_name = file_writer_config["text_dir"]hash_name = self.text2hash()file_name = os.path.join(dir_name, hash_name) + ".svg"if os.path.exists(file_name):return file_name-surface = cairo.SVGSurface(file_name, 600, 400)context = cairo.Context(surface)context.set_font_size(size)@@ -339,122 +307,258 @@ class Text(SVGMobject):if setting.line_num != last_line_num:offset_x = 0last_line_num = setting.line_num- context.move_to(START_X + offset_x, START_Y + lsh * setting.line_num)+ context.move_to(+ START_X + offset_x, START_Y + line_spacing * setting.line_num+ )context.show_text(text)offset_x += context.text_extents(text)[4]-+ surface.finish()return file_name-class TextWithFixHeight(Text):- def __init__(self, text, **kwargs):- Text.__init__(self, text, **kwargs)- max_height = Text("(gyt{[/QW", **kwargs).get_height()- rectangle = Rectangle(- width=0, height=max_height, fill_opacity=0, stroke_opacity=0, stroke_width=0- )- self.submobjects.append(rectangle)+# Following class is just a Little implementation of upcomming feautures. Ignore it for now.+class TextWithBackground(Text):+ CONFIG = {+ "background_color": BLACK,+ }++ def __init__(self, text, **config):+ Text.__init__(self, text, **config)+ # self.text_backgrounds = self.gen_text_backgrounds(text)++ def gen_text_backgrounds(self, text):+ text_with_visible_chars = text.replace(" ", "").replace("\t", "")+ text_list = text_with_visible_chars.split("\n")+ text_backgrounds = VGroup()+ start_i = 0+ for line_no in range(text_list.__len__()):+ rect_counts = len(text_list[line_no])+ text_backgrounds.add(*self[start_i:rect_counts])+ start_i += 2 * rect_counts+ text_backgrounds.set_color(self.background_color)++ return text_backgrounds++ def text2svg1(self):+ # anti-aliasing+ size = self.size * 10+ line_spacing = self.line_spacing * 10++ if self.font == "":+ if NOT_SETTING_FONT_MSG != "":+ logger.warning(NOT_SETTING_FONT_MSG)+ dir_name = consts.TEXT_DIR+ hash_name = self.text2hash()+ file_name = os.path.join(dir_name, hash_name) + ".svg"+ # if os.path.exists(file_name):+ # return file_name++ surface = cairo.SVGSurface(file_name, 600, 400)+ context = cairo.Context(surface)+ context.set_font_size(size)+ context.move_to(START_X, START_Y)++ settings = self.text2settings()+ offset_x = 0+ last_line_num = 0+ for setting in settings:+ font = setting.font+ slant = self.str2slant(setting.slant)+ weight = self.str2weight(setting.weight)+ text = self.text[setting.start : setting.end].replace("\n", " ")+ context.select_font_face(font, slant, weight)+ if setting.line_num != last_line_num:+ offset_x = 0+ last_line_num = setting.line_num+ tempx = START_X + offset_x+ tempy = START_Y + line_spacing * setting.line_num+ char_offset_x = 0+ char_height = tempy - size / 2 - (line_spacing - size)+ context.move_to(tempx, tempy)+ context.show_text(text)+ offset_x += context.text_extents(text)[4]+ surface.finish()+ return file_nameclass Paragraph(VGroup):+ """Paragraph is used to display paragraphs with more efficiency or having some extra features.++ paragraph paragraph.chars is VGroup() of each lines and each line is VGroup() of that line's characters+ that mean you can use it like+ paragraph[0:5] or paragraph.chars[0:5] to access first five lines+ paragraph[0][0:5] or paragraph.chars[0][0:5] to access first line's first five characters+ paragraph or paragraph[] or paragraph.chars[][] will create problems when using Transform() because of invisible characters+ so, before using Transform() remove invisible characters by using remove_invisible_chars()++ paragraph(" a b", " bcd\nefg") is same as paragraph(" a b", " bcd", "efg")+ that means paragraph[2] is "efg"++ Parameters+ ---------+ line_spacing : :class:`int`, optional+ Represents the spaning betweeb lines. Default to -1, which means auto.+ alignment : :class:`str`, optional+ Defines the alignment of paragraph. Default to "left". Possible values are "left", "right", "center"++ Examples+ --------+ Normal usage::+ paragraph = Paragraph('this is a awesome', 'paragraph', 'With \nNewlines', '\tWith Tabs', ' With Spaces',+ 'With Alignments',+ 'center', "left", "right")+ Remove unwanted invisible characters::+ self.play(Transform(remove_invisible_chars(paragraph.chars[0:2]), remove_invisible_chars(paragraph.chars[3][0:3]))+ """+CONFIG = {- "line_spacing": 0.1,- "alignment": "center",+ "line_spacing": -1,+ "alignment": None,}def __init__(self, *text, **config):- Container.__init__(self, **config)- self.lines_list = list(text)+ VGroup.__init__(self, **config)++ lines_str = "\n".join(list(text))+ self.lines_text = Text(lines_str, **config)+ lines_str_list = lines_str.split("\n")+ self.chars = self.gen_chars(lines_str_list)++ chars_lines_text_list = VGroup()+ char_index_counter = 0+ for line_index in range(lines_str_list.__len__()):+ chars_lines_text_list.add(+ self.lines_text[+ char_index_counter : char_index_counter+ + lines_str_list[line_index].__len__()+ + 1+ ]+ )+ char_index_counter += lines_str_list[line_index].__len__() + 1self.lines = []self.lines.append([])- for line_no in range(self.lines_list.__len__()):- if "\n" in self.lines_list[line_no]:- self.lines_list[line_no : line_no + 1] = self.lines_list[line_no].split(- "\n"- )- for line_no in range(self.lines_list.__len__()):- self.lines[0].append(TextWithFixHeight(self.lines_list[line_no], **config))- self.char_height = TextWithFixHeight("(", **config).get_height()+ for line_no in range(chars_lines_text_list.__len__()):+ self.lines[0].append(chars_lines_text_list[line_no])+ self.lines_initial_positions = []+ for line_no in range(self.lines[0].__len__()):+ self.lines_initial_positions.append(self.lines[0][line_no].get_center())self.lines.append([])- self.lines[1].extend([self.alignment for _ in range(self.lines_list.__len__())])- self.lines[0][0].move_to(np.array([0, 0, 0]))- self.align_lines()+ self.lines[1].extend(+ [self.alignment for _ in range(chars_lines_text_list.__len__())]+ )VGroup.__init__(self, *[self.lines[0][i] for i in range(self.lines[0].__len__())], **config)self.move_to(np.array([0, 0, 0]))+ if self.alignment:+ self.set_all_lines_alignments(self.alignment)++ def gen_chars(self, lines_str_list):+ """Function to convert plain string to 2d-VGroup of chars. 2d-VGroup mean "VGroup of VGroup".++ Parameters+ ---------+ lines_str_list : :class:`str`+ Plain text string.++ Returns+ -------+ :class:`~.VGroup`+ The generated 2d-VGroup of chars.+ """+ char_index_counter = 0+ chars = VGroup()+ for line_no in range(lines_str_list.__len__()):+ chars.add(VGroup())+ chars[line_no].add(+ *self.lines_text.chars[+ char_index_counter : char_index_counter+ + lines_str_list[line_no].__len__()+ + 1+ ]+ )+ char_index_counter += lines_str_list[line_no].__len__() + 1+ return chars- def set_all_lines_alignment(self, alignment):- self.lines[1] = [alignment for _ in range(self.lines_list.__len__())]+ def set_all_lines_alignments(self, alignment):+ """Function to set all line's aligment to a specific value.++ Parameters+ ---------+ alignment : :class:`str`+ Defines the alignment of paragraph. Possible values are "left", "right", "center".+ """for line_no in range(0, self.lines[0].__len__()):self.change_alignment_for_a_line(alignment, line_no)return self- def set_alignment(self, alignment, line_no):+ def set_line_alignment(self, alignment, line_no):+ """Function to set one line's aligment to a specific value.++ Parameters+ ---------+ alignment : :class:`str`+ Defines the alignment of paragraph. Possible values are "left", "right", "center".+ line_no : :class:`int`+ Defines the line number for which we want to set given alignment.+ """self.change_alignment_for_a_line(alignment, line_no)return self+ def set_all_lines_to_initial_positions(self):+ """Function to set one all lines to initial positions.+ """+ self.lines[1] = [None for _ in range(self.lines[0].__len__())]+ for line_no in range(0, self.lines[0].__len__()):+ self[line_no].move_to(+ self.get_center() + self.lines_initial_positions[line_no]+ )+ return self++ def set_line_to_initial_position(self, line_no):+ """Function to set one line to initial positions.++ Parameters+ ---------+ line_no : :class:`int`+ Defines the line number for which we want to set given alignment.+ """+ self.lines[1][line_no] = None+ self[line_no].move_to(self.get_center() + self.lines_initial_positions[line_no])+ return self+def change_alignment_for_a_line(self, alignment, line_no):+ """Function to change one line's aligment to a specific value.++ Parameters+ ---------+ alignment : :class:`str`+ Defines the alignment of paragraph. Possible values are "left", "right", "center".+ line_no : :class:`int`+ Defines the line number for which we want to set given alignment.+ """self.lines[1][line_no] = alignmentif self.lines[1][line_no] == "center":self[line_no].move_to(- self.get_top()- + np.array([0, -self.char_height / 2, 0])- + np.array([0, -line_no * (self.char_height + self.line_spacing), 0])+ np.array([self.get_center()[0], self[line_no].get_center()[1], 0]))elif self.lines[1][line_no] == "right":self[line_no].move_to(- self.get_top()- + np.array([0, -self.char_height / 2, 0])- + np.array(+ np.array([- self.get_width() / 2 - self.lines[0][line_no].get_width() / 2,- -line_no * (self.char_height + self.line_spacing),+ self.get_right()[0] - self[line_no].get_width() / 2,+ self[line_no].get_center()[1],0,]))elif self.lines[1][line_no] == "left":self[line_no].move_to(- self.get_top()- + np.array([0, -self.char_height / 2, 0])- + np.array(+ np.array([- -self.get_width() / 2 + self.lines[0][line_no].get_width() / 2,- -line_no * (self.char_height + self.line_spacing),+ self.get_left()[0] + self[line_no].get_width() / 2,+ self[line_no].get_center()[1],0,]))-- def align_lines(self):- for line_no in range(0, self.lines[0].__len__()):- if self.lines[1][line_no] == "center":- self.lines[0][line_no].move_to(- np.array([0, 0, 0])- + np.array(- [0, -line_no * (self.char_height + self.line_spacing), 0]- )- )- elif self.lines[1][line_no] == "left":- self.lines[0][line_no].move_to(- np.array([0, 0, 0])- + np.array(- [- self.lines[0][line_no].get_width() / 2,- -line_no * (self.char_height + self.line_spacing),- 0,- ]- )- )- elif self.lines[1][line_no] == "right":- self.lines[0][line_no].move_to(- np.array([0, 0, 0])- + np.array(- [- -self.lines[0][line_no].get_width() / 2,- -line_no * (self.char_height + self.line_spacing),- 0,- ]- )- )