ncurses.py 15 KB

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