@@ -777,3 +777,53 @@ def text(
777777 )
778778
779779 return self .__draw_text_cairo (location , text , colour , font , max_w , bg , align , real_bg = real_bg , key = key )
780+
781+ def get_wrapped_lines (self , text : str , font : int , max_x : int ) -> list [str ]:
782+ """
783+ Flynn disclaimer: slop function, seems to work though. Wraps the input text and returns the text of the displayed lines.
784+ """
785+ if not text :
786+ return []
787+
788+ if font not in self .f_dict :
789+ logging .info (f"Font not loaded: { font !s} " )
790+ return [text ]
791+
792+ max_x += 12
793+ max_x = round (max_x )
794+
795+ layout = self .layout
796+ layout .set_auto_dir (False )
797+ layout .set_font_description (self ._font_description (font ))
798+ layout .set_wrap (Pango .WrapMode .WORD_CHAR )
799+ layout .set_ellipsize (Pango .EllipsizeMode .NONE )
800+ layout .set_width (max_x * 1000 )
801+ layout .set_height (- 1 )
802+
803+ all_lines : list [str ] = []
804+
805+ # Split on real newlines ourselves so Pango only ever wraps a single
806+ # paragraph at a time — that way every line it returns is a soft wrap,
807+ # and every boundary between paragraphs is unambiguously a real \n.
808+ for paragraph in text .split ("\n " ):
809+ if paragraph == "" :
810+ all_lines .append ("\n " )
811+ continue
812+
813+ try :
814+ layout .set_text (paragraph , - 1 )
815+ except Exception :
816+ logging .exception (f"Text error on text: { paragraph } " )
817+ paragraph = paragraph .encode ("utf-8" , "replace" ).decode ("utf-8" )
818+ layout .set_text (paragraph , - 1 )
819+
820+ encoded = paragraph .encode ("utf-8" )
821+ for i , line in enumerate (layout .get_lines_readonly ()):
822+ start = line .start_index
823+ end = start + line .length
824+ if i == 0 :
825+ all_lines .append ('\n ' + encoded [start :end ].decode ("utf-8" ))
826+ else :
827+ all_lines .append (encoded [start :end ].decode ("utf-8" ))
828+
829+ return all_lines
0 commit comments