diff src/cagou/plugins/plugin_wid_chat.py @ 100:d7447c585603

chat: added url detection on text messages
author Goffi <goffi@goffi.org>
date Sat, 31 Dec 2016 12:12:17 +0100
parents 4d8c122b86a6
children 20251d926cc2
line wrap: on
line diff
--- a/src/cagou/plugins/plugin_wid_chat.py	Thu Dec 29 23:47:13 2016 +0100
+++ b/src/cagou/plugins/plugin_wid_chat.py	Sat Dec 31 12:12:17 2016 +0100
@@ -33,11 +33,12 @@
 from kivy import properties
 from sat_frontends.quick_frontend import quick_widgets
 from sat_frontends.quick_frontend import quick_chat
-from sat_frontends.tools import jid, css_color
+from sat_frontends.tools import jid, css_color, strings as sat_strings
 from cagou.core import cagou_widget
 from cagou.core.image import Image
 from cagou import G
 from xml.etree import ElementTree as ET
+import webbrowser
 
 
 PLUGIN_INFO = {
@@ -61,7 +62,44 @@
 
 
 class SimpleXHTMLWidgetEscapedText(Label):
-    pass
+
+    def _addUrlMarkup(self, text):
+        text_elts = []
+        idx = 0
+        links = 0
+        while True:
+            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)
+                url = m.group()
+                text_elts.append(u'[color=5500ff][ref={link}]{url}[/ref][/color]'.format(
+                    link = link_key,
+                    url = url
+                    ))
+                if not links:
+                    self.ref_urls = {link_key: url}
+                else:
+                    self.ref_urls[link_key] = url
+                links += 1
+                idx += m.end()
+            else:
+                if links:
+                    text_elts.append(escape_markup(text[idx:]))
+                    self.markup = True
+                    self.text = u''.join(text_elts)
+                break
+
+    def on_text(self, instance, text):
+        # do NOT call the method if self.markup is set
+        # this would result in infinite loop (because self.text
+        # is changed if an URL is found, and in this case markup too)
+        if text and not self.markup:
+            self._addUrlMarkup(text)
+
+    def on_ref_press(self, ref):
+        url = self.ref_urls[ref]
+        webbrowser.open(url)
 
 
 class SimpleXHTMLWidgetText(Label):