Display a scrollable text box in the bottom half of the screen.
| 1021 | |
| 1022 | |
| 1023 | class TextBox: |
| 1024 | """Display a scrollable text box in the bottom half of the screen. |
| 1025 | |
| 1026 | """ |
| 1027 | def __init__(self, scr, data='', title=""): |
| 1028 | self._running = False |
| 1029 | self.scr = scr |
| 1030 | self.data = data |
| 1031 | self.title = title |
| 1032 | self.tdata = [] # transformed data |
| 1033 | self.hid_rows = 0 # number of hidden rows from the beginning |
| 1034 | self.setup_handlers() |
| 1035 | |
| 1036 | def __call__(self): |
| 1037 | self.run() |
| 1038 | |
| 1039 | def setup_handlers(self): |
| 1040 | self.handlers = {'\n': self.close, |
| 1041 | curses.KEY_ENTER: self.close, |
| 1042 | 'q': self.close, |
| 1043 | curses.KEY_RESIZE: self.close, |
| 1044 | curses.KEY_DOWN: self.scroll_down, |
| 1045 | 'j': self.scroll_down, |
| 1046 | curses.KEY_UP: self.scroll_up, |
| 1047 | 'k': self.scroll_up, |
| 1048 | } |
| 1049 | |
| 1050 | def _calculate_layout(self): |
| 1051 | """Setup popup window and format data. """ |
| 1052 | self.scr.touchwin() |
| 1053 | self.term_rows, self.term_cols = self.scr.getmaxyx() |
| 1054 | self.box_height = self.term_rows - int(self.term_rows / 2) |
| 1055 | self.win = curses.newwin(int(self.term_rows / 2), |
| 1056 | self.term_cols, self.box_height, 0) |
| 1057 | try: |
| 1058 | curses.curs_set(False) |
| 1059 | except _curses.error: |
| 1060 | pass |
| 1061 | # transform raw data into list of lines ready to be printed |
| 1062 | s = self.data.splitlines() |
| 1063 | s = [wrap(i, self.term_cols - 3, subsequent_indent=" ") or [""] for i in s] |
| 1064 | self.tdata = [i for j in s for i in j] |
| 1065 | # -3 -- 2 for the box lines and 1 for the title row |
| 1066 | self.nlines = min(len(self.tdata), self.box_height - 3) |
| 1067 | self.scr.refresh() |
| 1068 | |
| 1069 | def run(self): |
| 1070 | self._running = True |
| 1071 | self._calculate_layout() |
| 1072 | while self._running: |
| 1073 | self.display() |
| 1074 | c = self.scr.getch() |
| 1075 | self.handle_key(c) |
| 1076 | |
| 1077 | def handle_key(self, key): |
| 1078 | if 0 < key < 256: |
| 1079 | key = chr(key) |
| 1080 | try: |