Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 1 | import logging |
| 2 | import oe.classutils |
| 3 | import shlex |
| 4 | from bb.process import Popen, ExecutionError |
| 5 | from distutils.version import LooseVersion |
| 6 | |
| 7 | logger = logging.getLogger('BitBake.OE.Terminal') |
| 8 | |
| 9 | |
| 10 | class UnsupportedTerminal(Exception): |
| 11 | pass |
| 12 | |
| 13 | class NoSupportedTerminals(Exception): |
| 14 | pass |
| 15 | |
| 16 | |
| 17 | class 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 28 | class Terminal(Popen, metaclass=Registry): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 29 | 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 42 | if isinstance(self.command, str): |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 43 | return shlex.split(self.command.format(**fmt)) |
| 44 | else: |
| 45 | return [element.format(**fmt) for element in self.command] |
| 46 | |
| 47 | class 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 | |
| 53 | class Gnome(XTerminal): |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 54 | command = 'gnome-terminal -t "{title}" -x {command}' |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 55 | 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 Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 64 | # 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 Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 86 | |
| 87 | class Mate(XTerminal): |
| 88 | command = 'mate-terminal -t "{title}" -x {command}' |
| 89 | priority = 2 |
| 90 | |
| 91 | class Xfce(XTerminal): |
| 92 | command = 'xfce4-terminal -T "{title}" -e "{command}"' |
| 93 | priority = 2 |
| 94 | |
| 95 | class Terminology(XTerminal): |
| 96 | command = 'terminology -T="{title}" -e {command}' |
| 97 | priority = 2 |
| 98 | |
| 99 | class Konsole(XTerminal): |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 100 | command = 'konsole --nofork --workdir . -p tabtitle="{title}" -e {command}' |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 101 | 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 | |
| 111 | class XTerm(XTerminal): |
| 112 | command = 'xterm -T "{title}" -e {command}' |
| 113 | priority = 1 |
| 114 | |
| 115 | class Rxvt(XTerminal): |
| 116 | command = 'rxvt -T "{title}" -e {command}' |
| 117 | priority = 1 |
| 118 | |
| 119 | class 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 | |
| 134 | class 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 Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 148 | raise UnsupportedTerminal('tmux pane too small or tmux < 1.9 version is being used') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 149 | |
| 150 | Terminal.__init__(self, sh_cmd, title, env, d) |
| 151 | |
| 152 | class 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 | |
| 167 | class 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 | |
| 190 | class 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 | |
| 206 | def prioritized(): |
| 207 | return Registry.prioritized() |
| 208 | |
| 209 | def 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 | |
| 220 | def 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] |
| 230 | if pipe.returncode != 0: |
| 231 | raise ExecutionError(sh_cmd, pipe.returncode, output) |
| 232 | |
| 233 | def check_tmux_pane_size(tmux): |
| 234 | import subprocess as sub |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 235 | # On older tmux versions (<1.9), return false. The reason |
| 236 | # is that there is no easy way to get the height of the active panel |
| 237 | # on current window without nested formats (available from version 1.9) |
| 238 | vernum = check_terminal_version("tmux") |
| 239 | if vernum and LooseVersion(vernum) < '1.9': |
| 240 | return False |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 241 | try: |
| 242 | p = sub.Popen('%s list-panes -F "#{?pane_active,#{pane_height},}"' % tmux, |
| 243 | shell=True,stdout=sub.PIPE,stderr=sub.PIPE) |
| 244 | out, err = p.communicate() |
| 245 | size = int(out.strip()) |
| 246 | except OSError as exc: |
| 247 | import errno |
| 248 | if exc.errno == errno.ENOENT: |
| 249 | return None |
| 250 | else: |
| 251 | raise |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 252 | |
| 253 | return size/2 >= 19 |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 254 | |
| 255 | def check_terminal_version(terminalName): |
| 256 | import subprocess as sub |
| 257 | try: |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 258 | cmdversion = '%s --version' % terminalName |
| 259 | if terminalName.startswith('tmux'): |
| 260 | cmdversion = '%s -V' % terminalName |
| 261 | newenv = os.environ.copy() |
| 262 | newenv["LANG"] = "C" |
| 263 | p = sub.Popen(['sh', '-c', cmdversion], stdout=sub.PIPE, stderr=sub.PIPE, env=newenv) |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 264 | out, err = p.communicate() |
Patrick Williams | c0f7c04 | 2017-02-23 20:41:17 -0600 | [diff] [blame] | 265 | ver_info = out.decode().rstrip().split('\n') |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 266 | except OSError as exc: |
| 267 | import errno |
| 268 | if exc.errno == errno.ENOENT: |
| 269 | return None |
| 270 | else: |
| 271 | raise |
| 272 | vernum = None |
| 273 | for ver in ver_info: |
| 274 | if ver.startswith('Konsole'): |
| 275 | vernum = ver.split(' ')[-1] |
| 276 | if ver.startswith('GNOME Terminal'): |
| 277 | vernum = ver.split(' ')[-1] |
Patrick Williams | d8c66bc | 2016-06-20 12:57:21 -0500 | [diff] [blame] | 278 | if ver.startswith('tmux'): |
| 279 | vernum = ver.split()[-1] |
Patrick Williams | c124f4f | 2015-09-15 14:41:29 -0500 | [diff] [blame] | 280 | return vernum |
| 281 | |
| 282 | def distro_name(): |
| 283 | try: |
| 284 | p = Popen(['lsb_release', '-i']) |
| 285 | out, err = p.communicate() |
| 286 | distro = out.split(':')[1].strip().lower() |
| 287 | except: |
| 288 | distro = "unknown" |
| 289 | return distro |