소스 검색

curses client update

Martin 9 년 전
부모
커밋
2863137407

+ 2 - 3
voice_control/input_sources/__init__.py

@@ -5,7 +5,6 @@ import conf
 
 LANGUAGE = 'en-GB'
 PREFERRED_PHRASES = None
-
 _TOKEN_STREAM = None
 
 class TokenStream(object):
@@ -25,12 +24,12 @@ class TokenStream(object):
     def get_line(self, timeout):
         return self.get_token(timeout)
 
-def launch_input_sources():
+def launch_input_sources(curses_client):
     global _TOKEN_STREAM
     _TOKEN_STREAM = TokenStream()
 
     services = [
-        console.ConsoleInput(_TOKEN_STREAM),
+        console.ConsoleInput(curses_client, _TOKEN_STREAM),
     ]
 
     if conf.ENABLE_SPEECH_INPUT:

+ 3 - 3
voice_control/input_sources/console.py

@@ -1,14 +1,14 @@
 import base
-import util.curses_util
 
 class ConsoleInput(base.InputSource):
-    def __init__(self, token_stream):
+    def __init__(self, curses_client, token_stream):
         self.stream = token_stream
+        self.curses_client = curses_client
     
     def run(self):
         while True:
             try:
-                cmd = util.curses_util.read_str()
+                cmd = self.curses_client.read_str()
                 for token in cmd.split(' '):
                     token = token.strip()
                     if token:

+ 14 - 4
voice_control/main.py

@@ -2,6 +2,7 @@ import logging
 import sys
 import signal
 import input_sources
+import output
 import services
 import util.curses_util
 
@@ -34,11 +35,20 @@ def test():
     
     print 'c'
 
-def _run():
+def _run(cclient):
     _init_logging()
-    input_sources.launch_input_sources()
-    services.launch_services(_interrupt_callback)
+    input_sources.launch_input_sources(cclient)
+    output.init_services(cclient)
+    services.launch_services(cclient, _interrupt_callback)
 
 if __name__ == "__main__":
-    util.curses_util.run(_run)
+    cclient = util.curses_util.CursesClient()
+    cclient.title = 'voice_control'
+    cclient.show_cursor = False
+
+    input_sources.CURSES_CLIENT = cclient
+    output.CURSES_CLIENT = cclient
+
+    cclient.run(_run, intercept_output_streams=True, cclient=cclient)
+
     #test()

+ 14 - 10
voice_control/output/__init__.py

@@ -2,16 +2,20 @@ import logging
 import console
 import conf
 
-SERVICES = [
-    console.Console(),
-]
-
-if conf.ENABLE_SOUND_OUTPUT:
-    import audio_output
-    SERVICES.append(audio_output.AudioOutput())
-if conf.SLACK_BOT_API_KEY:
-    import slack_bot
-    SERVICES.append(slack_bot.SlackBot())
+SERVICES = []
+
+def init_services(cclient):
+    global SERVICES
+    SERVICES = [
+        console.Console(cclient),
+    ]
+
+    if conf.ENABLE_SOUND_OUTPUT:
+        import audio_output
+        SERVICES.append(audio_output.AudioOutput())
+    if conf.SLACK_BOT_API_KEY:
+        import slack_bot
+        SERVICES.append(slack_bot.SlackBot())
 
 def success():
     for service in SERVICES:

+ 10 - 7
voice_control/output/console.py

@@ -3,23 +3,26 @@ import base
 import util.curses_util
 
 class Console(base.Base):
+    def __init__(self, cclient):
+        self.cclient = cclient
+
     def failure(self, s=None):
         if s is None:
-            util.curses_util.print_str('Failed.')
+            self.cclient.print_str('Failed.')
         else:
-            util.curses_util.print_str(s)
+            self.cclient.print_str(s)
         
     def tts(self, s):
-        util.curses_util.print_str(s)
+        self.cclient.print_str(s)
     
     def text(self, s):
-        util.curses_util.print_str(s)
+        self.cclient.print_str(s)
     
     def debug(self, s):
-        util.curses_util.print_str(s)
+        self.cclient.print_str(s)
     
     def cancelled(self):
-        util.curses_util.print_str('Cancelled.')
+        self.cclient.print_str('Cancelled.')
     
     def success(self):
-        util.curses_util.print_str('OK.')
+        self.cclient.print_str('OK.')

+ 4 - 4
voice_control/services/__init__.py

@@ -9,7 +9,7 @@ import echo
 import duckduckgo_answers
 import music
 
-def _get_services():
+def _get_services(cclient):
     res = {
         'email': email_mailgun.Email(),
         'food': todo_wunderlist.Wunderlist(True, 'food'),
@@ -17,15 +17,15 @@ def _get_services():
         'time': current_time.CurrentTime('Europe/Dublin'),
         'echo': echo.Echo(),
         'duck': duckduckgo_answers.DuckDuckGo(),
-        'play': music.Music(),
+        'play': music.Music(cclient),
     }
 
     res['help'] = services.help.Help(res)
 
     return res
 
-def launch_services(interrupted):
-    _services = _get_services()
+def launch_services(cclient, interrupted):
+    _services = _get_services(cclient)
 
     for s in _services.values():
         if not s.initialized:

+ 3 - 3
voice_control/services/music.py

@@ -1,4 +1,3 @@
-import subprocess
 import os
 import base
 import output
@@ -9,8 +8,9 @@ class Music(base.BaseService):
     folders = None
     current_process = None
 
-    def __init__(self):
+    def __init__(self, cclient):
         self.initialized = False
+        self.cclient = cclient
 
     def init(self):
         if not conf.MUSIC_FOLDER:
@@ -57,7 +57,7 @@ class Music(base.BaseService):
             f = self._search(tokens)
             if f:
                 output.debug('playing %s' % f)
-                self.current_process = subprocess.Popen(['cvlc', '-Z', f, ], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
+                self.current_process = self.cclient.call(['cvlc', '-Z', f, ], block_until_terminated=False)
 
             else:
                 output.failure()

+ 177 - 48
voice_control/util/curses_util.py

@@ -1,68 +1,197 @@
+import time
+import sys
 import curses
 import io
-
-_MAIN_WINDOW = None
-_INPUT_WINDOW = None
-_Y_POS = 0
-_HEIGHT = None
-_WIDTH = None
+import traceback
+import subprocess
+import os
+import fcntl
+import threading
 
 class StreamWriter(io.TextIOBase):
+    buffer = ''
+
+    def __init__(self, curses_client):
+        self.curses_client = curses_client
+
     def write(self, s):
-        print_str(s)
+        self.buffer += s
+        
+        if s.endswith('\n'):
+            self.curses_client.print_str(self.buffer[:-1])
+            self.buffer = ''
+        
         return len(s)
 
-def read_str(prompt='>', echo_to_main_window=True):
-    _INPUT_WINDOW.addstr(0, 1, prompt)
-    res = _INPUT_WINDOW.getstr(0, len(prompt) + 2)
-    _INPUT_WINDOW.clear()
-    _INPUT_WINDOW.refresh()
-
-    if echo_to_main_window:
-        print_str('%s %s' % (prompt, res))
+class CursesClient(object):
+    highlight_patterns = []
+    ignore_patterns = []
+    show_cursor = True
+    title = None
+
+    _main_window = None
+    _input_window = None
+    _y_pos = 0
+    _height = None
+    _width = None
+    _launched_processes = []
+
+    def _consume_process_output(self, process, read_fd, write_fd):
+        while process.poll() is None:
+            try:
+                line = read_fd.readline()
+                if line.endswith('\n'):
+                    line = line[:-1]
+                self.print_str(line)
+            except IOError, e:
+                if '[Errno 11]' in str(e):
+                    time.sleep(0.1)
+                else:
+                    raise e
+
+        try:
+            while True:
+                line = read_fd.readline()
+                if line.endswith('\n'):
+                    line = line[:-1]
+                self.print_str(line)
+        except IOError, e:
+            if '[Errno 11]' in str(e):
+                pass
+            else:
+                raise e
+
+        self.print_str('')
+
+        write_fd.close()
+        read_fd.close()
+
+    def call(self, args, block_until_terminated=True):
+        r, w = os.pipe()
+        rf = os.fdopen(r, 'r', 0)
+        wf = os.fdopen(w, 'w', 0)
+        fcntl.fcntl(rf, fcntl.F_SETFL, os.O_NONBLOCK)
+
+        p = subprocess.Popen(args, stdout=wf, stderr=wf, universal_newlines=True)
+
+        if block_until_terminated:
+            self._consume_process_output(p, rf, wf)
+        else:
+            self._launched_processes.append(p)
+            t = threading.Thread(target=self._consume_process_output, args=(p, rf, wf))
+            t.start()
         
-    return res
+        return p
+
+    def _get_attrs(self, s, base_attrs=None):
+        _attrs = 0
+        if base_attrs:
+            for attr in base_attrs:
+                _attrs |= attr
+        for pattern in self.highlight_patterns:
+            if pattern in s:
+                _attrs |= curses.A_BOLD
 
-def print_str(s, *args):
-    global _Y_POS
+        if '\033[1m' in s:
+            _attrs |= curses.A_BOLD
 
-    while _Y_POS >= _HEIGHT:
-        _MAIN_WINDOW.scroll()
-        _Y_POS -= 1
+        s = s.replace('\033[1m', '')
+        s = s.replace('\033[0m', '')
 
-    _MAIN_WINDOW.addstr(_Y_POS, 0, s)
-    _MAIN_WINDOW.refresh()
-    _Y_POS += 1
+        return s, _attrs
 
-def _run(stdscr, main_method):
-    curses.echo()
-    curses.curs_set(0)
-    
-    height, width = stdscr.getmaxyx()
-    top_box = stdscr.subwin(height - 3, width, 0, 0)
-    top_win = top_box.subwin(height - 5, width - 2, 1, 1)
-    bottom_box = stdscr.subwin(height - 3, 0)
-    bottom_win = bottom_box.subwin(1, width - 2, height - 2, 1)
-    top_box.box()
-    bottom_box.box()
+    def read_str(self, prompt='>', echo_to_main_window=True):
+        prompt = prompt.replace('\n', '')
+        if not prompt.endswith(' '):
+            prompt += ' '
 
-    top_win.idlok(True)
-    top_win.scrollok(True)
+        prompt, _attrs = self._get_attrs(prompt)
 
+        if self.show_cursor:
+            curses.curs_set(1)
 
-    stdscr.refresh()
+        self._input_window.addstr(0, 1, prompt, _attrs)
+        res = self._input_window.getstr(0, len(prompt) + 1)
+        self._input_window.clear()
 
-    global _MAIN_WINDOW
-    _MAIN_WINDOW = top_win
+        if self.show_cursor:
+            curses.curs_set(0)
 
-    global _INPUT_WINDOW
-    _INPUT_WINDOW = bottom_win
+        self._input_window.refresh()
 
-    global _HEIGHT
-    global _WIDTH
-    _HEIGHT, _WIDTH = _MAIN_WINDOW.getmaxyx()
+        if echo_to_main_window:
+            self.print_str('%s%s' % (prompt, res))
+            
+        return res
 
-    main_method()
+    def print_str(self, string, attrs=None):
+        string = str(string)
+        strs = string.split('\n') if '\n' in string else [string]
 
-def run(main_method):
-    curses.wrapper(_run, main_method=main_method)
+        for s in strs:
+            if any(p for p in self.ignore_patterns if p in s):
+                continue
+
+            while self._y_pos >= self._height:
+                self._main_window.scroll()
+                self._y_pos -= 1
+
+            s, _attrs = self._get_attrs(s, base_attrs=attrs)
+
+            self._main_window.addstr(self._y_pos, 0, s.encode('utf-8'), _attrs)
+            self._y_pos += 1
+
+        self._main_window.refresh()
+
+    def clear(self):
+        self._main_window.clear()
+        self._main_window.refresh()
+        self._y_pos = 0
+
+    def _run(self, stdscr, main_method, **kwargs):
+        curses.echo()
+        curses.curs_set(0)
+        
+        height, width = stdscr.getmaxyx()
+        top_box = stdscr.subwin(height - 3, width, 0, 0)
+        top_win = top_box.subwin(height - 5, width - 2, 1, 1)
+        bottom_box = stdscr.subwin(height - 3, 0)
+        bottom_win = bottom_box.subwin(1, width - 2, height - 2, 1)
+        top_box.box()
+        bottom_box.box()
+
+        if self.title:
+            title = ' %s ' % self.title
+            title_start = (width - len(title)) / 2
+            title_start = max(2, title_start)
+            length = min(width - 4, len(title))
+            top_box.addstr(0, title_start, title[:length])
+            top_box.refresh()
+
+        top_win.idlok(True)
+        top_win.scrollok(True)
+
+        stdscr.refresh()
+
+        self._main_window = top_win
+        self._input_window = bottom_win
+        self._height, self._width = self._main_window.getmaxyx()
+
+        try:
+            main_method(**kwargs)
+            for p in self._launched_processes:
+                p.wait()
+        except Exception, e:
+            self.print_str(str(e))
+            traceback.print_exc()
+            self.read_str('Press enter to quit.')
+
+    def run(self, main_method, intercept_output_streams=False, **kwargs):
+        old_stdout, old_stderr = sys.stdout, sys.stderr
+        if intercept_output_streams:
+            sys.stdout = StreamWriter(self)
+            sys.stderr = StreamWriter(self)
+
+        curses.wrapper(self._run, main_method=main_method, **kwargs)
+
+        sys.stdout, sys.stderr = old_stdout, old_stderr