import time import sys import curses import io 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): self.buffer += s if s.endswith('\n'): self.curses_client.print_str(self.buffer[:-1]) self.buffer = '' return len(s) 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 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 if '\033[1m' in s: _attrs |= curses.A_BOLD s = s.replace('\033[1m', '') s = s.replace('\033[0m', '') return s, _attrs def read_str(self, prompt='>', echo_to_main_window=True): prompt = prompt.replace('\n', '') if not prompt.endswith(' '): prompt += ' ' if not self._input_window: return raw_input(prompt) prompt, _attrs = self._get_attrs(prompt) if self.show_cursor: curses.curs_set(1) self._input_window.addstr(0, 1, prompt, _attrs) res = self._input_window.getstr(0, len(prompt) + 1) self._input_window.clear() if self.show_cursor: curses.curs_set(0) self._input_window.refresh() if echo_to_main_window: self.print_str('%s%s' % (prompt, res)) return res def print_str(self, string, attrs=None): string = str(string) strs = string.split('\n') if '\n' in string else [string] for s in strs: if any(p for p in self.ignore_patterns if p in s): continue s, _attrs = self._get_attrs(s, base_attrs=attrs) if self._main_window: while self._y_pos >= self._height: self._main_window.scroll() self._y_pos -= 1 self._main_window.addstr(self._y_pos, 0, s.encode('utf-8'), _attrs) self._y_pos += 1 else: print s.encode('utf-8') if self._main_window: self._main_window.refresh() def clear(self): if self._main_window: 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): if True: 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 else: main_method(**kwargs)