curses_util.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. import time
  2. import sys
  3. import curses
  4. import io
  5. import traceback
  6. import subprocess
  7. import os
  8. import fcntl
  9. import threading
  10. class StreamWriter(io.TextIOBase):
  11. buffer = ''
  12. def __init__(self, curses_client):
  13. self.curses_client = curses_client
  14. def write(self, s):
  15. self.buffer += s
  16. if s.endswith('\n'):
  17. self.curses_client.print_str(self.buffer[:-1])
  18. self.buffer = ''
  19. return len(s)
  20. class CursesClient(object):
  21. highlight_patterns = []
  22. ignore_patterns = []
  23. show_cursor = True
  24. title = None
  25. _main_window = None
  26. _input_window = None
  27. _y_pos = 0
  28. _height = None
  29. _width = None
  30. _launched_processes = []
  31. def _consume_process_output(self, process, read_fd, write_fd):
  32. while process.poll() is None:
  33. try:
  34. line = read_fd.readline()
  35. if line.endswith('\n'):
  36. line = line[:-1]
  37. self.print_str(line)
  38. except IOError, e:
  39. if '[Errno 11]' in str(e):
  40. time.sleep(0.1)
  41. else:
  42. raise e
  43. try:
  44. while True:
  45. line = read_fd.readline()
  46. if line.endswith('\n'):
  47. line = line[:-1]
  48. self.print_str(line)
  49. except IOError, e:
  50. if '[Errno 11]' in str(e):
  51. pass
  52. else:
  53. raise e
  54. self.print_str('')
  55. write_fd.close()
  56. read_fd.close()
  57. def call(self, args, block_until_terminated=True):
  58. r, w = os.pipe()
  59. rf = os.fdopen(r, 'r', 0)
  60. wf = os.fdopen(w, 'w', 0)
  61. fcntl.fcntl(rf, fcntl.F_SETFL, os.O_NONBLOCK)
  62. p = subprocess.Popen(args, stdout=wf, stderr=wf, universal_newlines=True)
  63. if block_until_terminated:
  64. self._consume_process_output(p, rf, wf)
  65. else:
  66. self._launched_processes.append(p)
  67. t = threading.Thread(target=self._consume_process_output, args=(p, rf, wf))
  68. t.start()
  69. return p
  70. def _get_attrs(self, s, base_attrs=None):
  71. _attrs = 0
  72. if base_attrs:
  73. for attr in base_attrs:
  74. _attrs |= attr
  75. for pattern in self.highlight_patterns:
  76. if pattern in s:
  77. _attrs |= curses.A_BOLD
  78. if '\033[1m' in s:
  79. _attrs |= curses.A_BOLD
  80. s = s.replace('\033[1m', '')
  81. s = s.replace('\033[0m', '')
  82. return s, _attrs
  83. def read_str(self, prompt='>', echo_to_main_window=True):
  84. prompt = prompt.replace('\n', '')
  85. if not prompt.endswith(' '):
  86. prompt += ' '
  87. if not self._input_window:
  88. return raw_input(prompt)
  89. prompt, _attrs = self._get_attrs(prompt)
  90. if self.show_cursor:
  91. curses.curs_set(1)
  92. self._input_window.addstr(0, 1, prompt, _attrs)
  93. res = self._input_window.getstr(0, len(prompt) + 1)
  94. self._input_window.clear()
  95. if self.show_cursor:
  96. curses.curs_set(0)
  97. self._input_window.refresh()
  98. if echo_to_main_window:
  99. self.print_str('%s%s' % (prompt, res))
  100. return res
  101. def print_str(self, string, attrs=None):
  102. string = str(string)
  103. strs = string.split('\n') if '\n' in string else [string]
  104. for s in strs:
  105. if any(p for p in self.ignore_patterns if p in s):
  106. continue
  107. s, _attrs = self._get_attrs(s, base_attrs=attrs)
  108. if self._main_window:
  109. while self._y_pos >= self._height:
  110. self._main_window.scroll()
  111. self._y_pos -= 1
  112. self._main_window.addstr(self._y_pos, 0, s.encode('utf-8'), _attrs)
  113. self._y_pos += 1
  114. else:
  115. print s.encode('utf-8')
  116. if self._main_window:
  117. self._main_window.refresh()
  118. def clear(self):
  119. if self._main_window:
  120. self._main_window.clear()
  121. self._main_window.refresh()
  122. self._y_pos = 0
  123. def _run(self, stdscr, main_method, **kwargs):
  124. curses.echo()
  125. curses.curs_set(0)
  126. height, width = stdscr.getmaxyx()
  127. top_box = stdscr.subwin(height - 3, width, 0, 0)
  128. top_win = top_box.subwin(height - 5, width - 2, 1, 1)
  129. bottom_box = stdscr.subwin(height - 3, 0)
  130. bottom_win = bottom_box.subwin(1, width - 2, height - 2, 1)
  131. top_box.box()
  132. bottom_box.box()
  133. if self.title:
  134. title = ' %s ' % self.title
  135. title_start = (width - len(title)) / 2
  136. title_start = max(2, title_start)
  137. length = min(width - 4, len(title))
  138. top_box.addstr(0, title_start, title[:length])
  139. top_box.refresh()
  140. top_win.idlok(True)
  141. top_win.scrollok(True)
  142. stdscr.refresh()
  143. self._main_window = top_win
  144. self._input_window = bottom_win
  145. self._height, self._width = self._main_window.getmaxyx()
  146. try:
  147. main_method(**kwargs)
  148. for p in self._launched_processes:
  149. p.wait()
  150. except Exception, e:
  151. self.print_str(str(e))
  152. traceback.print_exc()
  153. self.read_str('Press enter to quit.')
  154. def run(self, main_method, intercept_output_streams=False, **kwargs):
  155. if True:
  156. old_stdout, old_stderr = sys.stdout, sys.stderr
  157. if intercept_output_streams:
  158. sys.stdout = StreamWriter(self)
  159. sys.stderr = StreamWriter(self)
  160. curses.wrapper(self._run, main_method=main_method, **kwargs)
  161. sys.stdout, sys.stderr = old_stdout, old_stderr
  162. else:
  163. main_method(**kwargs)