diff cagou/core/simple_xhtml.py @ 312:772c170b47a9

Python3 port: /!\ Cagou now runs with Python 3.6+ Port has been done in the same way as for backend (check backend commit b2d067339de3 message for details).
author Goffi <goffi@goffi.org>
date Tue, 13 Aug 2019 19:14:22 +0200
parents 86b1cd8121dd
children 5868a5575e01
line wrap: on
line diff
--- a/cagou/core/simple_xhtml.py	Mon Aug 05 11:21:54 2019 +0200
+++ b/cagou/core/simple_xhtml.py	Tue Aug 13 19:14:22 2019 +0200
@@ -31,12 +31,9 @@
 import webbrowser
 
 
-class Escape(unicode):
+class Escape(str):
     """Class used to mark that a message need to be escaped"""
 
-    def __init__(self, text):
-        super(Escape, self).__init__(text)
-
 
 class SimpleXHTMLWidgetEscapedText(Label):
 
@@ -52,9 +49,9 @@
             m = sat_strings.RE_URL.search(text[idx:])
             if m is not None:
                 text_elts.append(escape_markup(m.string[0:m.start()]))
-                link_key = u'link_' + unicode(links)
+                link_key = 'link_' + str(links)
                 url = m.group()
-                text_elts.append(u'[color=5500ff][ref={link}]{url}[/ref][/color]'.format(
+                text_elts.append('[color=5500ff][ref={link}]{url}[/ref][/color]'.format(
                     link = link_key,
                     url = url
                     ))
@@ -68,7 +65,7 @@
                 if links:
                     text_elts.append(escape_markup(text[idx:]))
                     self.markup = True
-                    self.text = u''.join(text_elts)
+                    self.text = ''.join(text_elts)
                 break
 
     def on_text(self, instance, text):
@@ -107,7 +104,7 @@
         while parent and not isinstance(parent, SimpleXHTMLWidget):
             parent = parent.parent
         if parent is None:
-            log.error(u"no SimpleXHTMLWidget parent found")
+            log.error("no SimpleXHTMLWidget parent found")
         return parent
 
     def _on_source_load(self, value):
@@ -208,12 +205,12 @@
             self.splitted
         except AttributeError:
             # XXX: to make things easier, we split labels in words
-            log.debug(u"split start")
+            log.debug("split start")
             children = self.children[::-1]
             self.clear_widgets()
             for child in children:
                 if isinstance(child, Label):
-                    log.debug(u"label before split: {}".format(child.text))
+                    log.debug("label before split: {}".format(child.text))
                     styles = []
                     tag = False
                     new_text = []
@@ -228,9 +225,9 @@
                     for c in child.text:
                         if tag:
                             # we are parsing a markup tag
-                            if c == u']':
-                                current_tag_s = u''.join(current_tag)
-                                current_style = (current_tag_s, u''.join(current_value))
+                            if c == ']':
+                                current_tag_s = ''.join(current_tag)
+                                current_style = (current_tag_s, ''.join(current_value))
                                 if close:
                                     for idx, s in enumerate(reversed(styles)):
                                         if s[0] == current_tag_s:
@@ -243,9 +240,9 @@
                                 tag = False
                                 value = False
                                 close = False
-                            elif c == u'/':
+                            elif c == '/':
                                 close = True
-                            elif c == u'=':
+                            elif c == '=':
                                 value = True
                             elif value:
                                 current_value.append(c)
@@ -254,38 +251,38 @@
                             new_text.append(c)
                         else:
                             # we are parsing regular text
-                            if c == u'[':
+                            if c == '[':
                                 new_text.append(c)
                                 tag = True
-                            elif c == u' ':
+                            elif c == ' ':
                                 # new word, we do a new widget
-                                new_text.append(u' ')
+                                new_text.append(' ')
                                 for t, v in reversed(styles):
-                                    new_text.append(u'[/{}]'.format(t))
-                                current_wid.text = u''.join(new_text)
+                                    new_text.append('[/{}]'.format(t))
+                                current_wid.text = ''.join(new_text)
                                 new_text = []
                                 self.add_widget(current_wid)
-                                log.debug(u"new widget: {}".format(current_wid.text))
+                                log.debug("new widget: {}".format(current_wid.text))
                                 current_wid = self._createText()
                                 for t, v in styles:
-                                    new_text.append(u'[{tag}{value}]'.format(
+                                    new_text.append('[{tag}{value}]'.format(
                                         tag = t,
-                                        value = u'={}'.format(v) if v else u''))
+                                        value = '={}'.format(v) if v else ''))
                             else:
                                 new_text.append(c)
                     if current_wid.text:
                         # we may have a remaining widget after the parsing
                         close_styles = []
                         for t, v in reversed(styles):
-                            close_styles.append(u'[/{}]'.format(t))
-                        current_wid.text = u''.join(close_styles)
+                            close_styles.append('[/{}]'.format(t))
+                        current_wid.text = ''.join(close_styles)
                         self.add_widget(current_wid)
-                        log.debug(u"new widget: {}".format(current_wid.text))
+                        log.debug("new widget: {}".format(current_wid.text))
                 else:
                     # non Label widgets, we just add them
                     self.add_widget(child)
             self.splitted = True
-            log.debug(u"split OK")
+            log.debug("split OK")
 
         # we now set the content width
         # FIXME: for now we just use the full width
@@ -303,7 +300,7 @@
         try:
             method = getattr(self, "xhtml_{}".format(e.tag))
         except AttributeError:
-            log.warning(u"Unhandled XHTML tag: {}".format(e.tag))
+            log.warning("Unhandled XHTML tag: {}".format(e.tag))
             method = self.xhtml_generic
         method(e)
 
@@ -317,9 +314,9 @@
             should most probably be set to True
         """
         label = self._getLabel()
-        label.text += u'[{tag}{value}]'.format(
+        label.text += '[{tag}{value}]'.format(
             tag = tag,
-            value = u'={}'.format(value) if value else ''
+            value = '={}'.format(value) if value else ''
             )
         if append_to_list:
             self.styles.append((tag, value))
@@ -332,7 +329,7 @@
             should most probably be set to True
         """
         label = self._getLabel()
-        label.text += u'[/{tag}]'.format(
+        label.text += '[/{tag}]'.format(
             tag = tag
             )
         if remove_from_list:
@@ -382,19 +379,19 @@
         @param e(ET.Element): element which may have a "style" attribute
         """
         styles_limit = len(self.styles)
-        styles = e.attrib['style'].split(u';')
+        styles = e.attrib['style'].split(';')
         for style in styles:
             try:
-                prop, value = style.split(u':')
+                prop, value = style.split(':')
             except ValueError:
-                log.warning(u"can't parse style: {}".format(style))
+                log.warning("can't parse style: {}".format(style))
                 continue
-            prop = prop.strip().replace(u'-', '_')
+            prop = prop.strip().replace('-', '_')
             value = value.strip()
             try:
                 method = getattr(self, "css_{}".format(prop))
             except AttributeError:
-                log.warning(u"Unhandled CSS: {}".format(prop))
+                log.warning("Unhandled CSS: {}".format(prop))
             else:
                 method(e, value)
         self._css_styles = self.styles[styles_limit:]
@@ -419,7 +416,7 @@
         """
         # we first add markup and CSS style
         if markup is not None:
-            if isinstance(markup, basestring):
+            if isinstance(markup, str):
                 tag, value = markup, None
             else:
                 tag, value = markup
@@ -460,17 +457,17 @@
         try:
             src = elem.attrib['src']
         except KeyError:
-            log.warning(u"<img> element without src: {}".format(ET.tostring(elem)))
+            log.warning("<img> element without src: {}".format(ET.tostring(elem)))
             return
         try:
-            target_height = int(elem.get(u'height', 0))
+            target_height = int(elem.get('height', 0))
         except ValueError:
-            log.warning(u"Can't parse image height: {}".format(elem.get(u'height')))
+            log.warning("Can't parse image height: {}".format(elem.get('height')))
             target_height = 0
         try:
-            target_width = int(elem.get(u'width', 0))
+            target_width = int(elem.get('width', 0))
         except ValueError:
-            log.warning(u"Can't parse image width: {}".format(elem.get(u'width')))
+            log.warning("Can't parse image width: {}".format(elem.get('width')))
             target_width = 0
 
         img = SimpleXHTMLWidgetImage(source=src, target_height=target_height, target_width=target_width)
@@ -491,12 +488,12 @@
     # methods handling CSS properties
 
     def css_color(self, elem, value):
-        self._addStyle(u"color", css_color.parse(value))
+        self._addStyle("color", css_color.parse(value))
 
     def css_text_decoration(self, elem, value):
-        if value == u'underline':
+        if value == 'underline':
             self._addStyle('u')
-        elif value == u'line-through':
+        elif value == 'line-through':
             self._addStyle('s')
         else:
-            log.warning(u"unhandled text decoration: {}".format(value))
+            log.warning("unhandled text decoration: {}".format(value))