terminal.py 11 KB

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