terminal.py 10 KB

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