seroy avatar seroy committed 59c8aea

Tab to 4 spaces

Comments (0)

Files changed (1)

Radio-t Chat/Radio-t Chat.py

 
 
 class ChatViewsRegistry(object):
-  views = {}
+    views = {}
 
-  def __contains__(self, value):
-    if isinstance(value, sublime.View):
-      return value.id() in self.views
-    else:
-      return value in self.views
+    def __contains__(self, value):
+        if isinstance(value, sublime.View):
+            return value.id() in self.views
+        else:
+            return value in self.views
 
-  def add_view(self, view):
-    if view in self.views:
-      raise Exception("View already in registry")
-    thread = ChatUpdaterThread(view=view)
-    self.views[view.id()] = thread
-    thread.start()
+    def add_view(self, view):
+        if view in self.views:
+            raise Exception("View already in registry")
+        thread = ChatUpdaterThread(view=view)
+        self.views[view.id()] = thread
+        thread.start()
 
-  def remove_view(self, view):
-    thread = self.views[view.id()]
-    thread.stop()
-    #thread.join() # slow with big values of ChatUpdaterThread.timeout
+    def remove_view(self, view):
+        thread = self.views[view.id()]
+        thread.stop()
+        #thread.join() # slow with big values of ChatUpdaterThread.timeout
 
 
 chat_registry = ChatViewsRegistry()
 settings = sublime.load_settings(__name__ + '.sublime-settings')
 
 class ChatUpdaterThread(threading.Thread):
-  timeout = 3 # in seconds between updates
-  view = None # instance sublime.View
-  cookies = None
-  view_is_close = False
-  shown = None
+    timeout = 3 # in seconds between updates
+    view = None # instance sublime.View
+    cookies = None
+    view_is_close = False
+    shown = None
 
-  def __init__(self, view, *args, **kwargs):
-    self.view = view
-    self.shown = {}
-    self.cookies = cookielib.CookieJar()
-    threading.Thread.__init__(self, *args, **kwargs)
+    def __init__(self, view, *args, **kwargs):
+        self.view = view
+        self.shown = {}
+        self.cookies = cookielib.CookieJar()
+        threading.Thread.__init__(self, *args, **kwargs)
 
-  def update_chat(self, records):
-    self.view.set_read_only(False)
-    edit = self.view.begin_edit()
-    oldlocale = locale.getlocale(locale.LC_TIME)
-    for record in records:
-      if record['seq'] in self.shown:
-        continue
-      self.shown[record['seq']] = True
-      try:
-        time = datetime.datetime.strptime(record["time"],
-                                          "%a %b %d %H:%M:%S UTC %Y")
+    def update_chat(self, records):
+        self.view.set_read_only(False)
+        edit = self.view.begin_edit()
+        oldlocale = locale.getlocale(locale.LC_TIME)
+        for record in records:
+            if record['seq'] in self.shown:
+                continue
+            self.shown[record['seq']] = True
+            try:
+                time = datetime.datetime.strptime(record["time"],
+                                                  "%a %b %d %H:%M:%S UTC %Y")
+                try:
+                    time += datetime.timedelta(**settings.get('timedelta', 0))
+                except TypeError:
+                    pass
+                record['time'] = time.strftime(settings.get("dateformat", "%H:%M"))
+            except ValueError:
+                pass
+            self.view.insert(edit, self.view.size(),
+                             settings.get("string_format",
+                             "%(time)s <%(from)s>: %(msg)s\n") % record)
+            if settings.get('auto_scroll', True):
+                self.view.show(self.view.size())
+
+        self.view.end_edit(edit)
+        self.view.set_read_only(True)
+
+    def on_load_messages(self, records):
+        # This fix RuntimeError (must call on main thread, consider using
+        # sublime.set_timeout) on Mac and get stability on Linux
+        sublime.set_timeout(functools.partial(self.update_chat, records), 0)
+
+
+    def load_messages(self, *args, **kwargs):
+        params = {'mode': 'next', 'recs': 10}
+        params.update(kwargs)
+        qs = urllib.urlencode(params)
+        request = urllib2.Request('http://jc.radio-t.com:18000/data/json?' + qs)
+        cookie_handler= urllib2.HTTPCookieProcessor(self.cookies)
+        opener = urllib2.build_opener(cookie_handler)
         try:
-          time += datetime.timedelta(**settings.get('timedelta', 0))
-        except TypeError:
-          pass
-        record['time'] = time.strftime(settings.get("dateformat", "%H:%M"))
-      except ValueError:
-        pass
-      self.view.insert(edit, self.view.size(),
-                      settings.get("string_format",
-                                   "%(time)s <%(from)s>: %(msg)s\n") % record)
-      if settings.get('auto_scroll', True):
-        self.view.show(self.view.size())
+            opener = urllib2.build_opener(cookie_handler)
+            response = opener.open(request)
+            if response.getcode() != 200:
+                raise Exception("Data receive error")
+            records = json.load(response)['records']
+            self.on_load_messages(records)
+        except (KeyError, IndexError, TypeError, ValueError, urllib2.URLError):
+            print "Error on loading messages for radio-t chat view"
 
-    self.view.end_edit(edit)
-    self.view.set_read_only(True)
+    def run(self):
+        threading.Thread(target=self.load_messages,
+                         kwargs={'mode': 'last', 'recs': 50}).start()
+        while not self.view_is_close:
+            sleep(self.timeout)
+            threading.Thread(target=self.load_messages).start()
 
-  def on_load_messages(self, records):
-    # This fix RuntimeError (must call on main thread, consider using
-    # sublime.set_timeout) on Mac and get stability on Linux
-    sublime.set_timeout(functools.partial(self.update_chat, records), 0)
-
-
-  def load_messages(self, *args, **kwargs):
-    params = {'mode': 'next', 'recs': 10}
-    params.update(kwargs)
-    qs = urllib.urlencode(params)
-    request = urllib2.Request('http://jc.radio-t.com:18000/data/json?' + qs)
-    cookie_handler= urllib2.HTTPCookieProcessor(self.cookies)
-    opener = urllib2.build_opener(cookie_handler)
-    try:
-      opener = urllib2.build_opener(cookie_handler)
-      response = opener.open(request)
-      if response.getcode() != 200:
-        raise Exception("Data receive error")
-      records = json.load(response)['records']
-      self.on_load_messages(records)
-    except (KeyError, IndexError, TypeError, ValueError, urllib2.URLError):
-      print "Error on loading messages for radio-t chat view"
-
-  def run(self):
-    threading.Thread(target=self.load_messages,
-                     kwargs={'mode': 'last', 'recs': 50}).start()
-    while not self.view_is_close:
-      sleep(self.timeout)
-      threading.Thread(target=self.load_messages).start()
-
-  def stop(self):
-    self.view_is_close = True
+    def stop(self):
+        self.view_is_close = True
 
 
 class ChatClose(sublime_plugin.EventListener):
-  def on_close(self, view):
-    if view in chat_registry:
-      chat_registry.remove_view(view)
+    def on_close(self, view):
+        if view in chat_registry:
+            chat_registry.remove_view(view)
 
 
 class OpenRadiotChatCommand(sublime_plugin.WindowCommand):
-  def run(self):
-    view = self.window.new_file()
-    view.set_name(settings.get('view_title', ''))
-    view.settings().set('line_numbers', settings.get('line_numbers', False))
-    view.settings().set('draw_white_space',
-                        settings.get('draw_white_space', 'none'))
-    self.window.focus_view(view)
-    view.set_read_only(True)
-    view.set_scratch(True)
-    self.window.focus_view(view)
-    chat_registry.add_view(view)
+    def run(self):
+        view = self.window.new_file()
+        view.set_name(settings.get('view_title', ''))
+        view.settings().set('line_numbers', settings.get('line_numbers', False))
+        view.settings().set('draw_white_space',
+                            settings.get('draw_white_space', 'none'))
+        self.window.focus_view(view)
+        view.set_read_only(True)
+        view.set_scratch(True)
+        self.window.focus_view(view)
+        chat_registry.add_view(view)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.