ncurses.py 15 KB

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