curses_util.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import curses
  2. import io
  3. _MAIN_WINDOW = None
  4. _INPUT_WINDOW = None
  5. _Y_POS = 0
  6. _HEIGHT = None
  7. _WIDTH = None
  8. class StreamWriter(io.TextIOBase):
  9. def write(self, s):
  10. print_str(s)
  11. return len(s)
  12. def read_str(prompt='>', echo_to_main_window=True):
  13. _INPUT_WINDOW.addstr(0, 1, prompt)
  14. res = _INPUT_WINDOW.getstr(0, len(prompt) + 2)
  15. _INPUT_WINDOW.clear()
  16. _INPUT_WINDOW.refresh()
  17. if echo_to_main_window:
  18. print_str('%s %s' % (prompt, res))
  19. return res
  20. def print_str(s, *args):
  21. global _Y_POS
  22. while _Y_POS >= _HEIGHT:
  23. _MAIN_WINDOW.scroll()
  24. _Y_POS -= 1
  25. _MAIN_WINDOW.addstr(_Y_POS, 0, s)
  26. _MAIN_WINDOW.refresh()
  27. _Y_POS += 1
  28. def _run(stdscr, main_method):
  29. curses.echo()
  30. curses.curs_set(0)
  31. height, width = stdscr.getmaxyx()
  32. top_box = stdscr.subwin(height - 3, width, 0, 0)
  33. top_win = top_box.subwin(height - 5, width - 2, 1, 1)
  34. bottom_box = stdscr.subwin(height - 3, 0)
  35. bottom_win = bottom_box.subwin(1, width - 2, height - 2, 1)
  36. top_box.box()
  37. bottom_box.box()
  38. top_win.idlok(True)
  39. top_win.scrollok(True)
  40. stdscr.refresh()
  41. global _MAIN_WINDOW
  42. _MAIN_WINDOW = top_win
  43. global _INPUT_WINDOW
  44. _INPUT_WINDOW = bottom_win
  45. global _HEIGHT
  46. global _WIDTH
  47. _HEIGHT, _WIDTH = _MAIN_WINDOW.getmaxyx()
  48. main_method()
  49. def run(main_method):
  50. curses.wrapper(_run, main_method=main_method)