blob: 3c8ef59a45a63d616d8206dfb60748ba0b7b41d3 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001import logging
2import oe.classutils
3import shlex
4from bb.process import Popen, ExecutionError
5from distutils.version import LooseVersion
6
7logger = logging.getLogger('BitBake.OE.Terminal')
8
9
10class UnsupportedTerminal(Exception):
11 pass
12
13class NoSupportedTerminals(Exception):
14 pass
15
16
17class Registry(oe.classutils.ClassRegistry):
18 command = None
19
20 def __init__(cls, name, bases, attrs):
21 super(Registry, cls).__init__(name.lower(), bases, attrs)
22
23 @property
24 def implemented(cls):
25 return bool(cls.command)
26
27
Patrick Williamsc0f7c042017-02-23 20:41:17 -060028class Terminal(Popen, metaclass=Registry):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050029 def __init__(self, sh_cmd, title=None, env=None, d=None):
30 fmt_sh_cmd = self.format_command(sh_cmd, title)
31 try:
32 Popen.__init__(self, fmt_sh_cmd, env=env)
33 except OSError as exc:
34 import errno
35 if exc.errno == errno.ENOENT:
36 raise UnsupportedTerminal(self.name)
37 else:
38 raise
39
40 def format_command(self, sh_cmd, title):
41 fmt = {'title': title or 'Terminal', 'command': sh_cmd}
Patrick Williamsc0f7c042017-02-23 20:41:17 -060042 if isinstance(self.command, str):
Patrick Williamsc124f4f2015-09-15 14:41:29 -050043 return shlex.split(self.command.format(**fmt))
44 else:
45 return [element.format(**fmt) for element in self.command]
46
47class XTerminal(Terminal):
48 def __init__(self, sh_cmd, title=None, env=None, d=None):
49 Terminal.__init__(self, sh_cmd, title, env, d)
50 if not os.environ.get('DISPLAY'):
51 raise UnsupportedTerminal(self.name)
52
53class Gnome(XTerminal):
Patrick Williamsc0f7c042017-02-23 20:41:17 -060054 command = 'gnome-terminal -t "{title}" -x {command}'
Patrick Williamsc124f4f2015-09-15 14:41:29 -050055 priority = 2
56
57 def __init__(self, sh_cmd, title=None, env=None, d=None):
58 # Recent versions of gnome-terminal does not support non-UTF8 charset:
59 # https://bugzilla.gnome.org/show_bug.cgi?id=732127; as a workaround,
60 # clearing the LC_ALL environment variable so it uses the locale.
61 # Once fixed on the gnome-terminal project, this should be removed.
62 if os.getenv('LC_ALL'): os.putenv('LC_ALL','')
63
Patrick Williamsc0f7c042017-02-23 20:41:17 -060064 # We need to know when the command completes but gnome-terminal gives us no way
65 # to do this. We therefore write the pid to a file using a "phonehome" wrapper
66 # script, then monitor the pid until it exits. Thanks gnome!
67 import tempfile
68 pidfile = tempfile.NamedTemporaryFile(delete = False).name
69 try:
70 sh_cmd = "oe-gnome-terminal-phonehome " + pidfile + " " + sh_cmd
71 XTerminal.__init__(self, sh_cmd, title, env, d)
72 while os.stat(pidfile).st_size <= 0:
73 continue
74 with open(pidfile, "r") as f:
75 pid = int(f.readline())
76 finally:
77 os.unlink(pidfile)
78
79 import time
80 while True:
81 try:
82 os.kill(pid, 0)
83 time.sleep(0.1)
84 except OSError:
85 return
Patrick Williamsc124f4f2015-09-15 14:41:29 -050086
87class Mate(XTerminal):
88 command = 'mate-terminal -t "{title}" -x {command}'
89 priority = 2
90
91class Xfce(XTerminal):
92 command = 'xfce4-terminal -T "{title}" -e "{command}"'
93 priority = 2
94
95class Terminology(XTerminal):
96 command = 'terminology -T="{title}" -e {command}'
97 priority = 2
98
99class Konsole(XTerminal):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500100 command = 'konsole --nofork --workdir . -p tabtitle="{title}" -e {command}'
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500101 priority = 2
102
103 def __init__(self, sh_cmd, title=None, env=None, d=None):
104 # Check version
105 vernum = check_terminal_version("konsole")
106 if vernum and LooseVersion(vernum) < '2.0.0':
107 # Konsole from KDE 3.x
108 self.command = 'konsole -T "{title}" -e {command}'
109 XTerminal.__init__(self, sh_cmd, title, env, d)
110
111class XTerm(XTerminal):
112 command = 'xterm -T "{title}" -e {command}'
113 priority = 1
114
115class Rxvt(XTerminal):
116 command = 'rxvt -T "{title}" -e {command}'
117 priority = 1
118
119class Screen(Terminal):
120 command = 'screen -D -m -t "{title}" -S devshell {command}'
121
122 def __init__(self, sh_cmd, title=None, env=None, d=None):
123 s_id = "devshell_%i" % os.getpid()
124 self.command = "screen -D -m -t \"{title}\" -S %s {command}" % s_id
125 Terminal.__init__(self, sh_cmd, title, env, d)
126 msg = 'Screen started. Please connect in another terminal with ' \
127 '"screen -r %s"' % s_id
128 if (d):
129 bb.event.fire(bb.event.LogExecTTY(msg, "screen -r %s" % s_id,
130 0.5, 10), d)
131 else:
132 logger.warn(msg)
133
134class TmuxRunning(Terminal):
135 """Open a new pane in the current running tmux window"""
136 name = 'tmux-running'
137 command = 'tmux split-window "{command}"'
138 priority = 2.75
139
140 def __init__(self, sh_cmd, title=None, env=None, d=None):
141 if not bb.utils.which(os.getenv('PATH'), 'tmux'):
142 raise UnsupportedTerminal('tmux is not installed')
143
144 if not os.getenv('TMUX'):
145 raise UnsupportedTerminal('tmux is not running')
146
147 if not check_tmux_pane_size('tmux'):
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500148 raise UnsupportedTerminal('tmux pane too small or tmux < 1.9 version is being used')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500149
150 Terminal.__init__(self, sh_cmd, title, env, d)
151
152class TmuxNewWindow(Terminal):
153 """Open a new window in the current running tmux session"""
154 name = 'tmux-new-window'
155 command = 'tmux new-window -n "{title}" "{command}"'
156 priority = 2.70
157
158 def __init__(self, sh_cmd, title=None, env=None, d=None):
159 if not bb.utils.which(os.getenv('PATH'), 'tmux'):
160 raise UnsupportedTerminal('tmux is not installed')
161
162 if not os.getenv('TMUX'):
163 raise UnsupportedTerminal('tmux is not running')
164
165 Terminal.__init__(self, sh_cmd, title, env, d)
166
167class Tmux(Terminal):
168 """Start a new tmux session and window"""
169 command = 'tmux new -d -s devshell -n devshell "{command}"'
170 priority = 0.75
171
172 def __init__(self, sh_cmd, title=None, env=None, d=None):
173 if not bb.utils.which(os.getenv('PATH'), 'tmux'):
174 raise UnsupportedTerminal('tmux is not installed')
175
176 # TODO: consider using a 'devshell' session shared amongst all
177 # devshells, if it's already there, add a new window to it.
178 window_name = 'devshell-%i' % os.getpid()
179
180 self.command = 'tmux new -d -s {0} -n {0} "{{command}}"'.format(window_name)
181 Terminal.__init__(self, sh_cmd, title, env, d)
182
183 attach_cmd = 'tmux att -t {0}'.format(window_name)
184 msg = 'Tmux started. Please connect in another terminal with `tmux att -t {0}`'.format(window_name)
185 if d:
186 bb.event.fire(bb.event.LogExecTTY(msg, attach_cmd, 0.5, 10), d)
187 else:
188 logger.warn(msg)
189
190class Custom(Terminal):
191 command = 'false' # This is a placeholder
192 priority = 3
193
194 def __init__(self, sh_cmd, title=None, env=None, d=None):
195 self.command = d and d.getVar('OE_TERMINAL_CUSTOMCMD', True)
196 if self.command:
197 if not '{command}' in self.command:
198 self.command += ' {command}'
199 Terminal.__init__(self, sh_cmd, title, env, d)
200 logger.warn('Custom terminal was started.')
201 else:
202 logger.debug(1, 'No custom terminal (OE_TERMINAL_CUSTOMCMD) set')
203 raise UnsupportedTerminal('OE_TERMINAL_CUSTOMCMD not set')
204
205
206def prioritized():
207 return Registry.prioritized()
208
209def spawn_preferred(sh_cmd, title=None, env=None, d=None):
210 """Spawn the first supported terminal, by priority"""
211 for terminal in prioritized():
212 try:
213 spawn(terminal.name, sh_cmd, title, env, d)
214 break
215 except UnsupportedTerminal:
216 continue
217 else:
218 raise NoSupportedTerminals()
219
220def spawn(name, sh_cmd, title=None, env=None, d=None):
221 """Spawn the specified terminal, by name"""
222 logger.debug(1, 'Attempting to spawn terminal "%s"', name)
223 try:
224 terminal = Registry.registry[name]
225 except KeyError:
226 raise UnsupportedTerminal(name)
227
228 pipe = terminal(sh_cmd, title, env, d)
229 output = pipe.communicate()[0]
Brad Bishop37a0e4d2017-12-04 01:01:44 -0500230 if output:
231 output = output.decode("utf-8")
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500232 if pipe.returncode != 0:
233 raise ExecutionError(sh_cmd, pipe.returncode, output)
234
235def check_tmux_pane_size(tmux):
236 import subprocess as sub
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500237 # On older tmux versions (<1.9), return false. The reason
238 # is that there is no easy way to get the height of the active panel
239 # on current window without nested formats (available from version 1.9)
240 vernum = check_terminal_version("tmux")
241 if vernum and LooseVersion(vernum) < '1.9':
242 return False
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500243 try:
244 p = sub.Popen('%s list-panes -F "#{?pane_active,#{pane_height},}"' % tmux,
245 shell=True,stdout=sub.PIPE,stderr=sub.PIPE)
246 out, err = p.communicate()
247 size = int(out.strip())
248 except OSError as exc:
249 import errno
250 if exc.errno == errno.ENOENT:
251 return None
252 else:
253 raise
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500254
255 return size/2 >= 19
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500256
257def check_terminal_version(terminalName):
258 import subprocess as sub
259 try:
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500260 cmdversion = '%s --version' % terminalName
261 if terminalName.startswith('tmux'):
262 cmdversion = '%s -V' % terminalName
263 newenv = os.environ.copy()
264 newenv["LANG"] = "C"
265 p = sub.Popen(['sh', '-c', cmdversion], stdout=sub.PIPE, stderr=sub.PIPE, env=newenv)
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500266 out, err = p.communicate()
Patrick Williamsc0f7c042017-02-23 20:41:17 -0600267 ver_info = out.decode().rstrip().split('\n')
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500268 except OSError as exc:
269 import errno
270 if exc.errno == errno.ENOENT:
271 return None
272 else:
273 raise
274 vernum = None
275 for ver in ver_info:
276 if ver.startswith('Konsole'):
277 vernum = ver.split(' ')[-1]
278 if ver.startswith('GNOME Terminal'):
279 vernum = ver.split(' ')[-1]
Patrick Williamsd8c66bc2016-06-20 12:57:21 -0500280 if ver.startswith('tmux'):
281 vernum = ver.split()[-1]
Patrick Williamsc124f4f2015-09-15 14:41:29 -0500282 return vernum
283
284def distro_name():
285 try:
286 p = Popen(['lsb_release', '-i'])
287 out, err = p.communicate()
288 distro = out.split(':')[1].strip().lower()
289 except:
290 distro = "unknown"
291 return distro