-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfrontend.py
278 lines (230 loc) · 7.94 KB
/
frontend.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env python3
import curses
import sys
import os
from signal import signal, SIGTSTP, SIGINT
from time import sleep, time
from backend import Session
from procinfo import ProcessInfo
proc_info = ProcessInfo()
# TODO: write a module for procinfo+get_title
def get_title(pid, focus=False):
try:
proc_info.update()
child_pids = [pid,] + proc_info.all_children(pid)
top_pid = child_pids[-1]
cmd = self.get_cmdline(top_pid).split(' ')[0]
for child_pid in reversed(child_pids):
cwd = proc_info.cwd(child_pid)
if cwd:
break
except ProcessLookupError:
return 'Terminal'
if not (cwd and cmd and top_pid):
return 'Terminal'
if focus:
return "{}: {} {}".format(os.path.basename(cwd), cmd, top_pid)
else:
return cmd
class Terminal(object):
keymap = {
'SIGTSTP' : b'\x1a',
curses.KEY_BACKSPACE : b'\x08',
curses.KEY_CANCEL : b'\x03',
curses.KEY_CLEAR : b'\x0c',
curses.KEY_DC : b'~4',
curses.KEY_DOWN : b'~B',
curses.KEY_END : b'~F',
curses.KEY_F1 : b'~a',
curses.KEY_F2 : b'~b',
curses.KEY_F3 : b'~c',
curses.KEY_F4 : b'~d',
curses.KEY_F5 : b'~e',
curses.KEY_F6 : b'~f',
curses.KEY_F7 : b'~g',
curses.KEY_F8 : b'~h',
curses.KEY_F9 : b'~i',
curses.KEY_F10 : b'~j',
curses.KEY_F11 : b'~k',
curses.KEY_F12 : b'~l',
curses.KEY_HOME : b'~H',
curses.KEY_IC : b'~3',
curses.KEY_LEFT : b'~D',
curses.KEY_NPAGE : b'~2',
curses.KEY_PPAGE : b'~1',
curses.KEY_RIGHT : b'~C',
curses.KEY_UP : b'~A',
}
def __init__(self, parent_window, width=None, height=None, top=0, left=0):
h, w = parent_window.getmaxyx()
if not width:
width = w
if not height:
height = h-1
win = curses.newwin(height, width, top, left)
win.nodelay(1)
# set w, h
self.height, self.width = win.getmaxyx()
self.width -= 1; self.height -= 1; #max is max-1
self.session = Session(width=self.width, height = self.height)
self.pid = self.session.pid
self._window = win
self.scrollback = 0
self.last_scrollback = 0
self.last_scroll_screen = None
def get_input(self):
inp = self._window.getch()
return inp
def send_key(self, key):
if key == -1:
return
elif key in self.keymap:
c_char = self.keymap[key]
elif key == curses.KEY_SPREVIOUS:
self.scrollback += 5
return
elif key == curses.KEY_SNEXT:
self.scrollback -= 5
if self.scrollback < 0:
self.scrollback = 0
return
else:
c_char = chr(key).encode('utf-8')
self.session.write(c_char)
def get_cursorscreen(self):
if self.scrollback == 0:
self.last_scrollback = 0
return self.session.dump()
else:
if self.scrollback != self.last_scrollback:
self.last_scroll_screen = self.session.dump_history(self.scrollback)
self.last_scrollback = self.scrollback
return self.last_scroll_screen
def refresh(self):
(cx, cy), screen = self.get_cursorscreen()
# write the current screen to the window
self._window.erase()
for line_nr, line in enumerate(screen):
text = ''
for element in line:
if type(element) == str:
text += element
self._window.addstr(line_nr, 0, text)
# move to currents sessions cursor pos:
if cy != None:
self._window.move(cy, cx)
self._window.refresh()
def is_alive(self):
return self.session.is_alive()
def _write(self, d):
self.session.write(d)
def cancel(self):
self._write(self.keymap[curses.KEY_CANCEL])
def run(self):
self.session.keepalive()
class StatusBar(object):
def __init__(self, width, top, left):
height = 2
self.width = width
self._window = curses.newwin(height, width, top, left)
self.text = ''
self.focused_pid = 0
def set_focus(self, terminal):
self.fucused_pid = terminal.pid
def clear(self):
sell._window.clear()
def add_terminal(self, pid):
self.text += '[{}]'.format(get_title(pid, pid==self.fucused_pid))
def refresh(self):
text = (self.text+self.width*' ')[:self.width]
self._window.addstr(0, 0, text, curses.color_pair(1))
self._window.refresh()
class TerminalContainer(object):
def __init__(self, window):
self._window = window
self.height, self.width = window.getmaxyx()
self.terminals = []
self.focused = None
self.add_terminal()
self.statusbar = StatusBar(self.width, self.height-1, 0)
self.refreshs = 0
print('Container created!')
def add_terminal(self):
new_term = Terminal(self._window)
self.terminals.append(new_term)
self.focused = new_term
self.focused.run()
def get_input(self):
return self.focused.get_input()
def signal_handler(self, signal, stackframe):
if signal == SIGINT:
self.focused.cancel()
def is_alive(self):
if self.focused.is_alive():
return True
else:
self.terminals.remove(self.focused)
if self.terminals:
self.focused = self.terminals[0]
return self.is_alive()
else:
return False
def focus_terminal(self, index, relative=0):
"""focus terminal from self.terminals list
Arguments:
index -- defines which terminal should be focused
relative -- if this is != 0, index is replaced with
the focused terminals's index + the relative value
"""
if relative != 0:
current_index = self.terminals.index(self.focused)
index = current_index + relative
index = index % len(self.terminals)
self.focused = self.terminals[index]
def has_focus(self, terminal):
return terminal is self.focused
def input(self, y, x, prompt, attr=0):
self._window.nodelay(False)
curses.echo()
self._window.addstr(y, x, prompt, attr)
result = self._window.getstr()
self._window.nodelay(True)
curses.noecho()
return result
def run(self):
print('run Container... ')
while self.is_alive():
t1 = time()
self.refreshs += 1
if not self.refreshs % 60:
self.statusbar.refresh()
inp = self.focused.get_input()
self.focused.send_key(inp)
self.focused.refresh()
# reduce cpu-percentage:
sleeptime = (1/30) - (time()-t1)
if sleeptime > 0:
sleep(sleeptime)
if __name__ == '__main__':
def main(stdscr):
try:
# init colors:
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_RED)
# create terminal:
win = curses.newwin(100, 100, 0, 0)
master = TerminalContainer(stdscr)
# bin signals:
signal(SIGINT, master.signal_handler)
#signal(SIGTSTP, term.signal_handler)
# run terminal:
master.run()
except Exception as e:
# close all terminals if there is an bug/error in this program
try:
Session.close_all()
except:
pass
raise e
# close all sessions:
Session.close_all()
curses.wrapper(main)