blob: 52a891388af61f7375667ec23565cc57cd66b6f6 [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
28class Terminal(Popen):
29 __metaclass__ = Registry
30
31 def __init__(self, sh_cmd, title=None, env=None, d=None):
32 fmt_sh_cmd = self.format_command(sh_cmd, title)
33 try:
34 Popen.__init__(self, fmt_sh_cmd, env=env)
35 except OSError as exc:
36 import errno
37 if exc.errno == errno.ENOENT:
38 raise UnsupportedTerminal(self.name)
39 else:
40 raise
41
42 def format_command(self, sh_cmd, title):
43 fmt = {'title': title or 'Terminal', 'command': sh_cmd}
44 if isinstance(self.command, basestring):
45 return shlex.split(self.command.format(**fmt))
46 else:
47 return [element.format(**fmt) for element in self.command]
48
49class XTerminal(Terminal):
50 def __init__(self, sh_cmd, title=None, env=None, d=None):
51 Terminal.__init__(self, sh_cmd, title, env, d)
52 if not os.environ.get('DISPLAY'):
53 raise UnsupportedTerminal(self.name)
54
55class Gnome(XTerminal):
56 command = 'gnome-terminal -t "{title}" --disable-factory -x {command}'
57 priority = 2
58
59 def __init__(self, sh_cmd, title=None, env=None, d=None):
60 # Recent versions of gnome-terminal does not support non-UTF8 charset:
61 # https://bugzilla.gnome.org/show_bug.cgi?id=732127; as a workaround,
62 # clearing the LC_ALL environment variable so it uses the locale.
63 # Once fixed on the gnome-terminal project, this should be removed.
64 if os.getenv('LC_ALL'): os.putenv('LC_ALL','')
65
66 # Check version
67 vernum = check_terminal_version("gnome-terminal")
68 if vernum and LooseVersion(vernum) >= '3.10':
69 logger.debug(1, 'Gnome-Terminal 3.10 or later does not support --disable-factory')
70 self.command = 'gnome-terminal -t "{title}" -x {command}'
71 XTerminal.__init__(self, sh_cmd, title, env, d)
72
73class Mate(XTerminal):
74 command = 'mate-terminal -t "{title}" -x {command}'
75 priority = 2
76
77class Xfce(XTerminal):
78 command = 'xfce4-terminal -T "{title}" -e "{command}"'
79 priority = 2
80
81class Terminology(XTerminal):
82 command = 'terminology -T="{title}" -e {command}'
83 priority = 2
84
85class Konsole(XTerminal):
86 command = 'konsole --nofork -p tabtitle="{title}" -e {command}'
87 priority = 2
88
89 def __init__(self, sh_cmd, title=None, env=None, d=None):
90 # Check version
91 vernum = check_terminal_version("konsole")
92 if vernum and LooseVersion(vernum) < '2.0.0':
93 # Konsole from KDE 3.x
94 self.command = 'konsole -T "{title}" -e {command}'
95 XTerminal.__init__(self, sh_cmd, title, env, d)
96
97class XTerm(XTerminal):
98 command = 'xterm -T "{title}" -e {command}'
99 priority = 1
100
101class Rxvt(XTerminal):
102 command = 'rxvt -T "{title}" -e {command}'
103 priority = 1
104
105class Screen(Terminal):
106 command = 'screen -D -m -t "{title}" -S devshell {command}'
107
108 def __init__(self, sh_cmd, title=None, env=None, d=None):
109 s_id = "devshell_%i" % os.getpid()
110 self.command = "screen -D -m -t \"{title}\" -S %s {command}" % s_id
111 Terminal.__init__(self, sh_cmd, title, env, d)
112 msg = 'Screen started. Please connect in another terminal with ' \
113 '"screen -r %s"' % s_id
114 if (d):
115 bb.event.fire(bb.event.LogExecTTY(msg, "screen -r %s" % s_id,
116 0.5, 10), d)
117 else:
118 logger.warn(msg)
119
120class TmuxRunning(Terminal):
121 """Open a new pane in the current running tmux window"""
122 name = 'tmux-running'
123 command = 'tmux split-window "{command}"'
124 priority = 2.75
125
126 def __init__(self, sh_cmd, title=None, env=None, d=None):
127 if not bb.utils.which(os.getenv('PATH'), 'tmux'):
128 raise UnsupportedTerminal('tmux is not installed')
129
130 if not os.getenv('TMUX'):
131 raise UnsupportedTerminal('tmux is not running')
132
133 if not check_tmux_pane_size('tmux'):
134 raise UnsupportedTerminal('tmux pane too small')
135
136 Terminal.__init__(self, sh_cmd, title, env, d)
137
138class TmuxNewWindow(Terminal):
139 """Open a new window in the current running tmux session"""
140 name = 'tmux-new-window'
141 command = 'tmux new-window -n "{title}" "{command}"'
142 priority = 2.70
143
144 def __init__(self, sh_cmd, title=None, env=None, d=None):
145 if not bb.utils.which(os.getenv('PATH'), 'tmux'):
146 raise UnsupportedTerminal('tmux is not installed')
147
148 if not os.getenv('TMUX'):
149 raise UnsupportedTerminal('tmux is not running')
150
151 Terminal.__init__(self, sh_cmd, title, env, d)
152
153class Tmux(Terminal):
154 """Start a new tmux session and window"""
155 command = 'tmux new -d -s devshell -n devshell "{command}"'
156 priority = 0.75
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 # TODO: consider using a 'devshell' session shared amongst all
163 # devshells, if it's already there, add a new window to it.
164 window_name = 'devshell-%i' % os.getpid()
165
166 self.command = 'tmux new -d -s {0} -n {0} "{{command}}"'.format(window_name)
167 Terminal.__init__(self, sh_cmd, title, env, d)
168
169 attach_cmd = 'tmux att -t {0}'.format(window_name)
170 msg = 'Tmux started. Please connect in another terminal with `tmux att -t {0}`'.format(window_name)
171 if d:
172 bb.event.fire(bb.event.LogExecTTY(msg, attach_cmd, 0.5, 10), d)
173 else:
174 logger.warn(msg)
175
176class Custom(Terminal):
177 command = 'false' # This is a placeholder
178 priority = 3
179
180 def __init__(self, sh_cmd, title=None, env=None, d=None):
181 self.command = d and d.getVar('OE_TERMINAL_CUSTOMCMD', True)
182 if self.command:
183 if not '{command}' in self.command:
184 self.command += ' {command}'
185 Terminal.__init__(self, sh_cmd, title, env, d)
186 logger.warn('Custom terminal was started.')
187 else:
188 logger.debug(1, 'No custom terminal (OE_TERMINAL_CUSTOMCMD) set')
189 raise UnsupportedTerminal('OE_TERMINAL_CUSTOMCMD not set')
190
191
192def prioritized():
193 return Registry.prioritized()
194
195def spawn_preferred(sh_cmd, title=None, env=None, d=None):
196 """Spawn the first supported terminal, by priority"""
197 for terminal in prioritized():
198 try:
199 spawn(terminal.name, sh_cmd, title, env, d)
200 break
201 except UnsupportedTerminal:
202 continue
203 else:
204 raise NoSupportedTerminals()
205
206def spawn(name, sh_cmd, title=None, env=None, d=None):
207 """Spawn the specified terminal, by name"""
208 logger.debug(1, 'Attempting to spawn terminal "%s"', name)
209 try:
210 terminal = Registry.registry[name]
211 except KeyError:
212 raise UnsupportedTerminal(name)
213
214 pipe = terminal(sh_cmd, title, env, d)
215 output = pipe.communicate()[0]
216 if pipe.returncode != 0:
217 raise ExecutionError(sh_cmd, pipe.returncode, output)
218
219def check_tmux_pane_size(tmux):
220 import subprocess as sub
221 try:
222 p = sub.Popen('%s list-panes -F "#{?pane_active,#{pane_height},}"' % tmux,
223 shell=True,stdout=sub.PIPE,stderr=sub.PIPE)
224 out, err = p.communicate()
225 size = int(out.strip())
226 except OSError as exc:
227 import errno
228 if exc.errno == errno.ENOENT:
229 return None
230 else:
231 raise
232 if size/2 >= 19:
233 return True
234 return False
235
236def check_terminal_version(terminalName):
237 import subprocess as sub
238 try:
239 p = sub.Popen(['sh', '-c', '%s --version' % terminalName],stdout=sub.PIPE,stderr=sub.PIPE)
240 out, err = p.communicate()
241 ver_info = out.rstrip().split('\n')
242 except OSError as exc:
243 import errno
244 if exc.errno == errno.ENOENT:
245 return None
246 else:
247 raise
248 vernum = None
249 for ver in ver_info:
250 if ver.startswith('Konsole'):
251 vernum = ver.split(' ')[-1]
252 if ver.startswith('GNOME Terminal'):
253 vernum = ver.split(' ')[-1]
254 return vernum
255
256def distro_name():
257 try:
258 p = Popen(['lsb_release', '-i'])
259 out, err = p.communicate()
260 distro = out.split(':')[1].strip().lower()
261 except:
262 distro = "unknown"
263 return distro