ncurses.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. #
  2. # BitBake Curses UI Implementation
  3. #
  4. # Implements an ncurses frontend for the BitBake utility.
  5. #
  6. # Copyright (C) 2006 Michael 'Mickey' Lauer
  7. # Copyright (C) 2006-2007 Richard Purdie
  8. #
  9. # SPDX-License-Identifier: GPL-2.0-only
  10. #
  11. # This program is free software; you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License version 2 as
  13. # published by the Free Software Foundation.
  14. #
  15. # This program is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU General Public License along
  21. # with this program; if not, write to the Free Software Foundation, Inc.,
  22. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  23. """
  24. We have the following windows:
  25. 1.) Main Window: Shows what we are ultimately building and how far we are. Includes status bar
  26. 2.) Thread Activity Window: Shows one status line for every concurrent bitbake thread.
  27. 3.) Command Line Window: Contains an interactive command line where you can interact w/ Bitbake.
  28. Basic window layout is like that:
  29. |---------------------------------------------------------|
  30. | <Main Window> | <Thread Activity Window> |
  31. | | 0: foo do_compile complete|
  32. | Building Gtk+-2.6.10 | 1: bar do_patch complete |
  33. | Status: 60% | ... |
  34. | | ... |
  35. | | ... |
  36. |---------------------------------------------------------|
  37. |<Command Line Window> |
  38. |>>> which virtual/kernel |
  39. |openzaurus-kernel |
  40. |>>> _ |
  41. |---------------------------------------------------------|
  42. """
  43. import logging
  44. import os, sys, itertools, time, subprocess
  45. try:
  46. import curses
  47. except ImportError:
  48. sys.exit("FATAL: The ncurses ui could not load the required curses python module.")
  49. import bb
  50. import xmlrpc.client
  51. from bb import ui
  52. from bb.ui import uihelper
  53. parsespin = itertools.cycle( r'|/-\\' )
  54. X = 0
  55. Y = 1
  56. WIDTH = 2
  57. HEIGHT = 3
  58. MAXSTATUSLENGTH = 32
  59. class NCursesUI:
  60. """
  61. NCurses UI Class
  62. """
  63. class Window:
  64. """Base Window Class"""
  65. def __init__( self, x, y, width, height, fg=curses.COLOR_BLACK, bg=curses.COLOR_WHITE ):
  66. self.win = curses.newwin( height, width, y, x )
  67. self.dimensions = ( x, y, width, height )
  68. """
  69. if curses.has_colors():
  70. color = 1
  71. curses.init_pair( color, fg, bg )
  72. self.win.bkgdset( ord(' '), curses.color_pair(color) )
  73. else:
  74. self.win.bkgdset( ord(' '), curses.A_BOLD )
  75. """
  76. self.erase()
  77. self.setScrolling()
  78. self.win.noutrefresh()
  79. def erase( self ):
  80. self.win.erase()
  81. def setScrolling( self, b = True ):
  82. self.win.scrollok( b )
  83. self.win.idlok( b )
  84. def setBoxed( self ):
  85. self.boxed = True
  86. self.win.box()
  87. self.win.noutrefresh()
  88. def setText( self, x, y, text, *args ):
  89. self.win.addstr( y, x, text, *args )
  90. self.win.noutrefresh()
  91. def appendText( self, text, *args ):
  92. self.win.addstr( text, *args )
  93. self.win.noutrefresh()
  94. def drawHline( self, y ):
  95. self.win.hline( y, 0, curses.ACS_HLINE, self.dimensions[WIDTH] )
  96. self.win.noutrefresh()
  97. class DecoratedWindow( Window ):
  98. """Base class for windows with a box and a title bar"""
  99. def __init__( self, title, x, y, width, height, fg=curses.COLOR_BLACK, bg=curses.COLOR_WHITE ):
  100. NCursesUI.Window.__init__( self, x+1, y+3, width-2, height-4, fg, bg )
  101. self.decoration = NCursesUI.Window( x, y, width, height, fg, bg )
  102. self.decoration.setBoxed()
  103. self.decoration.win.hline( 2, 1, curses.ACS_HLINE, width-2 )
  104. self.setTitle( title )
  105. def setTitle( self, title ):
  106. self.decoration.setText( 1, 1, title.center( self.dimensions[WIDTH]-2 ), curses.A_BOLD )
  107. #-------------------------------------------------------------------------#
  108. # class TitleWindow( Window ):
  109. #-------------------------------------------------------------------------#
  110. # """Title Window"""
  111. # def __init__( self, x, y, width, height ):
  112. # NCursesUI.Window.__init__( self, x, y, width, height )
  113. # version = bb.__version__
  114. # title = "BitBake %s" % version
  115. # credit = "(C) 2003-2007 Team BitBake"
  116. # #self.win.hline( 2, 1, curses.ACS_HLINE, width-2 )
  117. # self.win.border()
  118. # self.setText( 1, 1, title.center( self.dimensions[WIDTH]-2 ), curses.A_BOLD )
  119. # self.setText( 1, 2, credit.center( self.dimensions[WIDTH]-2 ), curses.A_BOLD )
  120. #-------------------------------------------------------------------------#
  121. class ThreadActivityWindow( DecoratedWindow ):
  122. #-------------------------------------------------------------------------#
  123. """Thread Activity Window"""
  124. def __init__( self, x, y, width, height ):
  125. NCursesUI.DecoratedWindow.__init__( self, "Thread Activity", x, y, width, height )
  126. def setStatus( self, thread, text ):
  127. line = "%02d: %s" % ( thread, text )
  128. width = self.dimensions[WIDTH]
  129. if ( len(line) > width ):
  130. line = line[:width-3] + "..."
  131. else:
  132. line = line.ljust( width )
  133. self.setText( 0, thread, line )
  134. #-------------------------------------------------------------------------#
  135. class MainWindow( DecoratedWindow ):
  136. #-------------------------------------------------------------------------#
  137. """Main Window"""
  138. def __init__( self, x, y, width, height ):
  139. self.StatusPosition = width - MAXSTATUSLENGTH
  140. NCursesUI.DecoratedWindow.__init__( self, None, x, y, width, height )
  141. curses.nl()
  142. def setTitle( self, title ):
  143. title = "BitBake %s" % bb.__version__
  144. self.decoration.setText( 2, 1, title, curses.A_BOLD )
  145. self.decoration.setText( self.StatusPosition - 8, 1, "Status:", curses.A_BOLD )
  146. def setStatus(self, status):
  147. while len(status) < MAXSTATUSLENGTH:
  148. status = status + " "
  149. self.decoration.setText( self.StatusPosition, 1, status, curses.A_BOLD )
  150. #-------------------------------------------------------------------------#
  151. class ShellOutputWindow( DecoratedWindow ):
  152. #-------------------------------------------------------------------------#
  153. """Interactive Command Line Output"""
  154. def __init__( self, x, y, width, height ):
  155. NCursesUI.DecoratedWindow.__init__( self, "Command Line Window", x, y, width, height )
  156. #-------------------------------------------------------------------------#
  157. class ShellInputWindow( Window ):
  158. #-------------------------------------------------------------------------#
  159. """Interactive Command Line Input"""
  160. def __init__( self, x, y, width, height ):
  161. NCursesUI.Window.__init__( self, x, y, width, height )
  162. # put that to the top again from curses.textpad import Textbox
  163. # self.textbox = Textbox( self.win )
  164. # t = threading.Thread()
  165. # t.run = self.textbox.edit
  166. # t.start()
  167. #-------------------------------------------------------------------------#
  168. def main(self, stdscr, server, eventHandler, params):
  169. #-------------------------------------------------------------------------#
  170. height, width = stdscr.getmaxyx()
  171. # for now split it like that:
  172. # MAIN_y + THREAD_y = 2/3 screen at the top
  173. # MAIN_x = 2/3 left, THREAD_y = 1/3 right
  174. # CLI_y = 1/3 of screen at the bottom
  175. # CLI_x = full
  176. main_left = 0
  177. main_top = 0
  178. main_height = ( height // 3 * 2 )
  179. main_width = ( width // 3 ) * 2
  180. clo_left = main_left
  181. clo_top = main_top + main_height
  182. clo_height = height - main_height - main_top - 1
  183. clo_width = width
  184. cli_left = main_left
  185. cli_top = clo_top + clo_height
  186. cli_height = 1
  187. cli_width = width
  188. thread_left = main_left + main_width
  189. thread_top = main_top
  190. thread_height = main_height
  191. thread_width = width - main_width
  192. #tw = self.TitleWindow( 0, 0, width, main_top )
  193. mw = self.MainWindow( main_left, main_top, main_width, main_height )
  194. taw = self.ThreadActivityWindow( thread_left, thread_top, thread_width, thread_height )
  195. clo = self.ShellOutputWindow( clo_left, clo_top, clo_width, clo_height )
  196. cli = self.ShellInputWindow( cli_left, cli_top, cli_width, cli_height )
  197. cli.setText( 0, 0, "BB>" )
  198. mw.setStatus("Idle")
  199. helper = uihelper.BBUIHelper()
  200. shutdown = 0
  201. try:
  202. params.updateFromServer(server)
  203. cmdline = params.parseActions()
  204. if not cmdline:
  205. print("Nothing to do. Use 'bitbake world' to build everything, or run 'bitbake --help' for usage information.")
  206. return 1
  207. if 'msg' in cmdline and cmdline['msg']:
  208. logger.error(cmdline['msg'])
  209. return 1
  210. cmdline = cmdline['action']
  211. ret, error = server.runCommand(cmdline)
  212. if error:
  213. print("Error running command '%s': %s" % (cmdline, error))
  214. return
  215. elif ret != True:
  216. print("Couldn't get default commandlind! %s" % ret)
  217. return
  218. except xmlrpc.client.Fault as x:
  219. print("XMLRPC Fault getting commandline:\n %s" % x)
  220. return
  221. exitflag = False
  222. while not exitflag:
  223. try:
  224. event = eventHandler.waitEvent(0.25)
  225. if not event:
  226. continue
  227. helper.eventHandler(event)
  228. if isinstance(event, bb.build.TaskBase):
  229. mw.appendText("NOTE: %s\n" % event._message)
  230. if isinstance(event, logging.LogRecord):
  231. mw.appendText(logging.getLevelName(event.levelno) + ': ' + event.getMessage() + '\n')
  232. if isinstance(event, bb.event.CacheLoadStarted):
  233. self.parse_total = event.total
  234. if isinstance(event, bb.event.CacheLoadProgress):
  235. x = event.current
  236. y = self.parse_total
  237. mw.setStatus("Loading Cache: %s [%2d %%]" % ( next(parsespin), x*100/y ) )
  238. if isinstance(event, bb.event.CacheLoadCompleted):
  239. mw.setStatus("Idle")
  240. mw.appendText("Loaded %d entries from dependency cache.\n"
  241. % ( event.num_entries))
  242. if isinstance(event, bb.event.ParseStarted):
  243. self.parse_total = event.total
  244. if isinstance(event, bb.event.ParseProgress):
  245. x = event.current
  246. y = self.parse_total
  247. mw.setStatus("Parsing Recipes: %s [%2d %%]" % ( next(parsespin), x*100/y ) )
  248. if isinstance(event, bb.event.ParseCompleted):
  249. mw.setStatus("Idle")
  250. mw.appendText("Parsing finished. %d cached, %d parsed, %d skipped, %d masked.\n"
  251. % ( event.cached, event.parsed, event.skipped, event.masked ))
  252. # if isinstance(event, bb.build.TaskFailed):
  253. # if event.logfile:
  254. # if data.getVar("BBINCLUDELOGS", d):
  255. # bb.error("log data follows (%s)" % logfile)
  256. # number_of_lines = data.getVar("BBINCLUDELOGS_LINES", d)
  257. # if number_of_lines:
  258. # subprocess.check_call('tail -n%s %s' % (number_of_lines, logfile), shell=True)
  259. # else:
  260. # f = open(logfile, "r")
  261. # while True:
  262. # l = f.readline()
  263. # if l == '':
  264. # break
  265. # l = l.rstrip()
  266. # print '| %s' % l
  267. # f.close()
  268. # else:
  269. # bb.error("see log in %s" % logfile)
  270. if isinstance(event, bb.command.CommandCompleted):
  271. # stop so the user can see the result of the build, but
  272. # also allow them to now exit with a single ^C
  273. shutdown = 2
  274. if isinstance(event, bb.command.CommandFailed):
  275. mw.appendText(str(event))
  276. time.sleep(2)
  277. exitflag = True
  278. if isinstance(event, bb.command.CommandExit):
  279. exitflag = True
  280. if isinstance(event, bb.cooker.CookerExit):
  281. exitflag = True
  282. if isinstance(event, bb.event.LogExecTTY):
  283. mw.appendText('WARN: ' + event.msg + '\n')
  284. if helper.needUpdate:
  285. activetasks, failedtasks = helper.getTasks()
  286. taw.erase()
  287. taw.setText(0, 0, "")
  288. if activetasks:
  289. taw.appendText("Active Tasks:\n")
  290. for task in activetasks.values():
  291. taw.appendText(task["title"] + '\n')
  292. if failedtasks:
  293. taw.appendText("Failed Tasks:\n")
  294. for task in failedtasks:
  295. taw.appendText(task["title"] + '\n')
  296. curses.doupdate()
  297. except EnvironmentError as ioerror:
  298. # ignore interrupted io
  299. if ioerror.args[0] == 4:
  300. pass
  301. except KeyboardInterrupt:
  302. if shutdown == 2:
  303. mw.appendText("Third Keyboard Interrupt, exit.\n")
  304. exitflag = True
  305. if shutdown == 1:
  306. mw.appendText("Second Keyboard Interrupt, stopping...\n")
  307. _, error = server.runCommand(["stateForceShutdown"])
  308. if error:
  309. print("Unable to cleanly stop: %s" % error)
  310. if shutdown == 0:
  311. mw.appendText("Keyboard Interrupt, closing down...\n")
  312. _, error = server.runCommand(["stateShutdown"])
  313. if error:
  314. print("Unable to cleanly shutdown: %s" % error)
  315. shutdown = shutdown + 1
  316. pass
  317. def main(server, eventHandler, params):
  318. if not os.isatty(sys.stdout.fileno()):
  319. print("FATAL: Unable to run 'ncurses' UI without a TTY.")
  320. return
  321. ui = NCursesUI()
  322. try:
  323. curses.wrapper(ui.main, server, eventHandler, params)
  324. except:
  325. import traceback
  326. traceback.print_exc()