menuconfig.py 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2018-2019, Nordic Semiconductor ASA and Ulf Magnusson
  3. # SPDX-License-Identifier: ISC
  4. """
  5. Overview
  6. ========
  7. A curses-based Python 2/3 menuconfig implementation. The interface should feel
  8. familiar to people used to mconf ('make menuconfig').
  9. Supports the same keys as mconf, and also supports a set of keybindings
  10. inspired by Vi:
  11. J/K : Down/Up
  12. L : Enter menu/Toggle item
  13. H : Leave menu
  14. Ctrl-D/U: Page Down/Page Up
  15. G/End : Jump to end of list
  16. g/Home : Jump to beginning of list
  17. [Space] toggles values if possible, and enters menus otherwise. [Enter] works
  18. the other way around.
  19. The mconf feature where pressing a key jumps to a menu entry with that
  20. character in it in the current menu isn't supported. A jump-to feature for
  21. jumping directly to any symbol (including invisible symbols), choice, menu or
  22. comment (as in a Kconfig 'comment "Foo"') is available instead.
  23. A few different modes are available:
  24. F: Toggle show-help mode, which shows the help text of the currently selected
  25. item in the window at the bottom of the menu display. This is handy when
  26. browsing through options.
  27. C: Toggle show-name mode, which shows the symbol name before each symbol menu
  28. entry
  29. A: Toggle show-all mode, which shows all items, including currently invisible
  30. items and items that lack a prompt. Invisible items are drawn in a different
  31. style to make them stand out.
  32. Running
  33. =======
  34. menuconfig.py can be run either as a standalone executable or by calling the
  35. menuconfig() function with an existing Kconfig instance. The second option is a
  36. bit inflexible in that it will still load and save .config, etc.
  37. When run in standalone mode, the top-level Kconfig file to load can be passed
  38. as a command-line argument. With no argument, it defaults to "Kconfig".
  39. The KCONFIG_CONFIG environment variable specifies the .config file to load (if
  40. it exists) and save. If KCONFIG_CONFIG is unset, ".config" is used.
  41. When overwriting a configuration file, the old version is saved to
  42. <filename>.old (e.g. .config.old).
  43. $srctree is supported through Kconfiglib.
  44. Color schemes
  45. =============
  46. It is possible to customize the color scheme by setting the MENUCONFIG_STYLE
  47. environment variable. For example, setting it to 'aquatic' will enable an
  48. alternative, less yellow, more 'make menuconfig'-like color scheme, contributed
  49. by Mitja Horvat (pinkfluid).
  50. This is the current list of built-in styles:
  51. - default classic Kconfiglib theme with a yellow accent
  52. - monochrome colorless theme (uses only bold and standout) attributes,
  53. this style is used if the terminal doesn't support colors
  54. - aquatic blue-tinted style loosely resembling the lxdialog theme
  55. It is possible to customize the current style by changing colors of UI
  56. elements on the screen. This is the list of elements that can be stylized:
  57. - path Top row in the main display, with the menu path
  58. - separator Separator lines between windows. Also used for the top line
  59. in the symbol information display.
  60. - list List of items, e.g. the main display
  61. - selection Style for the selected item
  62. - inv-list Like list, but for invisible items. Used in show-all mode.
  63. - inv-selection Like selection, but for invisible items. Used in show-all
  64. mode.
  65. - help Help text windows at the bottom of various fullscreen
  66. dialogs
  67. - show-help Window showing the help text in show-help mode
  68. - frame Frame around dialog boxes
  69. - body Body of dialog boxes
  70. - edit Edit box in pop-up dialogs
  71. - jump-edit Edit box in jump-to dialog
  72. - text Symbol information text
  73. The color definition is a comma separated list of attributes:
  74. - fg:COLOR Set the foreground/background colors. COLOR can be one of
  75. * or * the basic 16 colors (black, red, green, yellow, blue,
  76. - bg:COLOR magenta, cyan, white and brighter versions, for example,
  77. brightred). On terminals that support more than 8 colors,
  78. you can also directly put in a color number, e.g. fg:123
  79. (hexadecimal and octal constants are accepted as well).
  80. Colors outside the range -1..curses.COLORS-1 (which is
  81. terminal-dependent) are ignored (with a warning). The COLOR
  82. can be also specified using a RGB value in the HTML
  83. notation, for example #RRGGBB. If the terminal supports
  84. color changing, the color is rendered accurately.
  85. Otherwise, the visually nearest color is used.
  86. If the background or foreground color of an element is not
  87. specified, it defaults to -1, representing the default
  88. terminal foreground or background color.
  89. Note: On some terminals a bright version of the color
  90. implies bold.
  91. - bold Use bold text
  92. - underline Use underline text
  93. - standout Standout text attribute (reverse color)
  94. More often than not, some UI elements share the same color definition. In such
  95. cases the right value may specify an UI element from which the color definition
  96. will be copied. For example, "separator=help" will apply the current color
  97. definition for "help" to "separator".
  98. A keyword without the '=' is assumed to be a style template. The template name
  99. is looked up in the built-in styles list and the style definition is expanded
  100. in-place. With this, built-in styles can be used as basis for new styles.
  101. For example, take the aquatic theme and give it a red selection bar:
  102. MENUCONFIG_STYLE="aquatic selection=fg:white,bg:red"
  103. If there's an error in the style definition or if a missing style is assigned
  104. to, the assignment will be ignored, along with a warning being printed on
  105. stderr.
  106. The 'default' theme is always implicitly parsed first, so the following two
  107. settings have the same effect:
  108. MENUCONFIG_STYLE="selection=fg:white,bg:red"
  109. MENUCONFIG_STYLE="default selection=fg:white,bg:red"
  110. If the terminal doesn't support colors, the 'monochrome' theme is used, and
  111. MENUCONFIG_STYLE is ignored. The assumption is that the environment is broken
  112. somehow, and that the important thing is to get something usable.
  113. Other features
  114. ==============
  115. - Seamless terminal resizing
  116. - No dependencies on *nix, as the 'curses' module is in the Python standard
  117. library
  118. - Unicode text entry
  119. - Improved information screen compared to mconf:
  120. * Expressions are split up by their top-level &&/|| operands to improve
  121. readability
  122. * Undefined symbols in expressions are pointed out
  123. * Menus and comments have information displays
  124. * Kconfig definitions are printed
  125. * The include path is shown, listing the locations of the 'source'
  126. statements that included the Kconfig file of the symbol (or other
  127. item)
  128. Limitations
  129. ===========
  130. Doesn't work out of the box on Windows, but can be made to work with
  131. pip install windows-curses
  132. See the https://github.com/zephyrproject-rtos/windows-curses repository.
  133. """
  134. from __future__ import print_function
  135. import os
  136. import sys
  137. _IS_WINDOWS = os.name == "nt" # Are we running on Windows?
  138. try:
  139. import curses
  140. except ImportError as e:
  141. if not _IS_WINDOWS:
  142. raise
  143. sys.exit("""\
  144. menuconfig failed to import the standard Python 'curses' library. Try
  145. installing a package like windows-curses
  146. (https://github.com/zephyrproject-rtos/windows-curses) by running this command
  147. in cmd.exe:
  148. pip install windows-curses
  149. Starting with Kconfiglib 13.0.0, windows-curses is no longer automatically
  150. installed when installing Kconfiglib via pip on Windows (because it breaks
  151. installation on MSYS2).
  152. Exception:
  153. {}: {}""".format(type(e).__name__, e))
  154. import errno
  155. import locale
  156. import re
  157. import textwrap
  158. from kconfiglib import Symbol, Choice, MENU, COMMENT, MenuNode, \
  159. BOOL, TRISTATE, STRING, INT, HEX, \
  160. AND, OR, \
  161. expr_str, expr_value, split_expr, \
  162. standard_sc_expr_str, \
  163. TRI_TO_STR, TYPE_TO_STR, \
  164. standard_kconfig, standard_config_filename
  165. #
  166. # Configuration variables
  167. #
  168. # If True, try to change LC_CTYPE to a UTF-8 locale if it is set to the C
  169. # locale (which implies ASCII). This fixes curses Unicode I/O issues on systems
  170. # with bad defaults. ncurses configures itself from the locale settings.
  171. #
  172. # Related PEP: https://www.python.org/dev/peps/pep-0538/
  173. _CHANGE_C_LC_CTYPE_TO_UTF8 = True
  174. # How many steps an implicit submenu will be indented. Implicit submenus are
  175. # created when an item depends on the symbol before it. Note that symbols
  176. # defined with 'menuconfig' create a separate menu instead of indenting.
  177. _SUBMENU_INDENT = 4
  178. # Number of steps for Page Up/Down to jump
  179. _PG_JUMP = 6
  180. # Height of the help window in show-help mode
  181. _SHOW_HELP_HEIGHT = 8
  182. # How far the cursor needs to be from the edge of the window before it starts
  183. # to scroll. Used for the main menu display, the information display, the
  184. # search display, and for text boxes.
  185. _SCROLL_OFFSET = 5
  186. # Minimum width of dialogs that ask for text input
  187. _INPUT_DIALOG_MIN_WIDTH = 30
  188. # Number of arrows pointing up/down to draw when a window is scrolled
  189. _N_SCROLL_ARROWS = 14
  190. # Lines of help text shown at the bottom of the "main" display
  191. _MAIN_HELP_LINES = """
  192. [Space/Enter] Toggle/enter [ESC] Leave menu [S] Save
  193. [O] Load [?] Symbol info [/] Jump to symbol
  194. [F] Toggle show-help mode [C] Toggle show-name mode [A] Toggle show-all mode
  195. [Q] Quit (prompts for save) [D] Save minimal config (advanced)
  196. """[1:-1].split("\n")
  197. # Lines of help text shown at the bottom of the information dialog
  198. _INFO_HELP_LINES = """
  199. [ESC/q] Return to menu [/] Jump to symbol
  200. """[1:-1].split("\n")
  201. # Lines of help text shown at the bottom of the search dialog
  202. _JUMP_TO_HELP_LINES = """
  203. Type text to narrow the search. Regexes are supported (via Python's 're'
  204. module). The up/down cursor keys step in the list. [Enter] jumps to the
  205. selected symbol. [ESC] aborts the search. Type multiple space-separated
  206. strings/regexes to find entries that match all of them. Type Ctrl-F to
  207. view the help of the selected item without leaving the dialog.
  208. """[1:-1].split("\n")
  209. #
  210. # Styling
  211. #
  212. _STYLES = {
  213. "default": """
  214. path=fg:black,bg:white,bold
  215. separator=fg:black,bg:yellow,bold
  216. list=fg:black,bg:white
  217. selection=fg:white,bg:blue,bold
  218. inv-list=fg:red,bg:white
  219. inv-selection=fg:red,bg:blue
  220. help=path
  221. show-help=list
  222. frame=fg:black,bg:yellow,bold
  223. body=fg:white,bg:black
  224. edit=fg:white,bg:blue
  225. jump-edit=edit
  226. text=list
  227. """,
  228. # This style is forced on terminals that do no support colors
  229. "monochrome": """
  230. path=bold
  231. separator=bold,standout
  232. list=
  233. selection=bold,standout
  234. inv-list=bold
  235. inv-selection=bold,standout
  236. help=bold
  237. show-help=
  238. frame=bold,standout
  239. body=
  240. edit=standout
  241. jump-edit=
  242. text=
  243. """,
  244. # Blue-tinted style loosely resembling lxdialog
  245. "aquatic": """
  246. path=fg:white,bg:blue
  247. separator=fg:white,bg:cyan
  248. help=path
  249. frame=fg:white,bg:cyan
  250. body=fg:white,bg:blue
  251. edit=fg:black,bg:white
  252. """
  253. }
  254. _NAMED_COLORS = {
  255. # Basic colors
  256. "black": curses.COLOR_BLACK,
  257. "red": curses.COLOR_RED,
  258. "green": curses.COLOR_GREEN,
  259. "yellow": curses.COLOR_YELLOW,
  260. "blue": curses.COLOR_BLUE,
  261. "magenta": curses.COLOR_MAGENTA,
  262. "cyan": curses.COLOR_CYAN,
  263. "white": curses.COLOR_WHITE,
  264. # Bright versions
  265. "brightblack": curses.COLOR_BLACK + 8,
  266. "brightred": curses.COLOR_RED + 8,
  267. "brightgreen": curses.COLOR_GREEN + 8,
  268. "brightyellow": curses.COLOR_YELLOW + 8,
  269. "brightblue": curses.COLOR_BLUE + 8,
  270. "brightmagenta": curses.COLOR_MAGENTA + 8,
  271. "brightcyan": curses.COLOR_CYAN + 8,
  272. "brightwhite": curses.COLOR_WHITE + 8,
  273. # Aliases
  274. "purple": curses.COLOR_MAGENTA,
  275. "brightpurple": curses.COLOR_MAGENTA + 8,
  276. }
  277. def _rgb_to_6cube(rgb):
  278. # Converts an 888 RGB color to a 3-tuple (nice in that it's hashable)
  279. # representing the closest xterm 256-color 6x6x6 color cube color.
  280. #
  281. # The xterm 256-color extension uses a RGB color palette with components in
  282. # the range 0-5 (a 6x6x6 cube). The catch is that the mapping is nonlinear.
  283. # Index 0 in the 6x6x6 cube is mapped to 0, index 1 to 95, then 135, 175,
  284. # etc., in increments of 40. See the links below:
  285. #
  286. # https://commons.wikimedia.org/wiki/File:Xterm_256color_chart.svg
  287. # https://github.com/tmux/tmux/blob/master/colour.c
  288. # 48 is the middle ground between 0 and 95.
  289. return tuple(0 if x < 48 else int(round(max(1, (x - 55)/40))) for x in rgb)
  290. def _6cube_to_rgb(r6g6b6):
  291. # Returns the 888 RGB color for a 666 xterm color cube index
  292. return tuple(0 if x == 0 else 40*x + 55 for x in r6g6b6)
  293. def _rgb_to_gray(rgb):
  294. # Converts an 888 RGB color to the index of an xterm 256-color grayscale
  295. # color with approx. the same perceived brightness
  296. # Calculate the luminance (gray intensity) of the color. See
  297. # https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
  298. # and
  299. # https://www.w3.org/TR/AERT/#color-contrast
  300. luma = 0.299*rgb[0] + 0.587*rgb[1] + 0.114*rgb[2]
  301. # Closest index in the grayscale palette, which starts at RGB 0x080808,
  302. # with stepping 0x0A0A0A
  303. index = int(round((luma - 8)/10))
  304. # Clamp the index to 0-23, corresponding to 232-255
  305. return max(0, min(index, 23))
  306. def _gray_to_rgb(index):
  307. # Convert a grayscale index to its closet single RGB component
  308. return 3*(10*index + 8,) # Returns a 3-tuple
  309. # Obscure Python: We never pass a value for rgb2index, and it keeps pointing to
  310. # the same dict. This avoids a global.
  311. def _alloc_rgb(rgb, rgb2index={}):
  312. # Initialize a new entry in the xterm palette to the given RGB color,
  313. # returning its index. If the color has already been initialized, the index
  314. # of the existing entry is returned.
  315. #
  316. # ncurses is palette-based, so we need to overwrite palette entries to make
  317. # new colors.
  318. #
  319. # The colors from 0 to 15 are user-defined, and there's no way to query
  320. # their RGB values, so we better leave them untouched. Also leave any
  321. # hypothetical colors above 255 untouched (though we're unlikely to
  322. # allocate that many colors anyway).
  323. if rgb in rgb2index:
  324. return rgb2index[rgb]
  325. # Many terminals allow the user to customize the first 16 colors. Avoid
  326. # changing their values.
  327. color_index = 16 + len(rgb2index)
  328. if color_index >= 256:
  329. _warn("Unable to allocate new RGB color ", rgb, ". Too many colors "
  330. "allocated.")
  331. return 0
  332. # Map each RGB component from the range 0-255 to the range 0-1000, which is
  333. # what curses uses
  334. curses.init_color(color_index, *(int(round(1000*x/255)) for x in rgb))
  335. rgb2index[rgb] = color_index
  336. return color_index
  337. def _color_from_num(num):
  338. # Returns the index of a color that looks like color 'num' in the xterm
  339. # 256-color palette (but that might not be 'num', if we're redefining
  340. # colors)
  341. # - _alloc_rgb() won't touch the first 16 colors or any (hypothetical)
  342. # colors above 255, so we can always return them as-is
  343. #
  344. # - If the terminal doesn't support changing color definitions, or if
  345. # curses.COLORS < 256, _alloc_rgb() won't touch any color, and all colors
  346. # can be returned as-is
  347. if num < 16 or num > 255 or not curses.can_change_color() or \
  348. curses.COLORS < 256:
  349. return num
  350. # _alloc_rgb() might redefine colors, so emulate the xterm 256-color
  351. # palette by allocating new colors instead of returning color numbers
  352. # directly
  353. if num < 232:
  354. num -= 16
  355. return _alloc_rgb(_6cube_to_rgb(((num//36)%6, (num//6)%6, num%6)))
  356. return _alloc_rgb(_gray_to_rgb(num - 232))
  357. def _color_from_rgb(rgb):
  358. # Returns the index of a color matching the 888 RGB color 'rgb'. The
  359. # returned color might be an ~exact match or an approximation, depending on
  360. # terminal capabilities.
  361. # Calculates the Euclidean distance between two RGB colors
  362. def dist(r1, r2): return sum((x - y)**2 for x, y in zip(r1, r2))
  363. if curses.COLORS >= 256:
  364. # Assume we're dealing with xterm's 256-color extension
  365. if curses.can_change_color():
  366. # Best case -- the terminal supports changing palette entries via
  367. # curses.init_color(). Initialize an unused palette entry and
  368. # return it.
  369. return _alloc_rgb(rgb)
  370. # Second best case -- pick between the xterm 256-color extension colors
  371. # Closest 6-cube "color" color
  372. c6 = _rgb_to_6cube(rgb)
  373. # Closest gray color
  374. gray = _rgb_to_gray(rgb)
  375. if dist(rgb, _6cube_to_rgb(c6)) < dist(rgb, _gray_to_rgb(gray)):
  376. # Use the "color" color from the 6x6x6 color palette. Calculate the
  377. # color number from the 6-cube index triplet.
  378. return 16 + 36*c6[0] + 6*c6[1] + c6[2]
  379. # Use the color from the gray palette
  380. return 232 + gray
  381. # Terminal not in xterm 256-color mode. This is probably the best we can
  382. # do, or is it? Submit patches. :)
  383. min_dist = float('inf')
  384. best = -1
  385. for color in range(curses.COLORS):
  386. # ncurses uses the range 0..1000. Scale that down to 0..255.
  387. d = dist(rgb, tuple(int(round(255*c/1000))
  388. for c in curses.color_content(color)))
  389. if d < min_dist:
  390. min_dist = d
  391. best = color
  392. return best
  393. def _parse_style(style_str, parsing_default):
  394. # Parses a string with '<element>=<style>' assignments. Anything not
  395. # containing '=' is assumed to be a reference to a built-in style, which is
  396. # treated as if all the assignments from the style were inserted at that
  397. # point in the string.
  398. #
  399. # The parsing_default flag is set to True when we're implicitly parsing the
  400. # 'default'/'monochrome' style, to prevent warnings.
  401. for sline in style_str.split():
  402. # Words without a "=" character represents a style template
  403. if "=" in sline:
  404. key, data = sline.split("=", 1)
  405. # The 'default' style template is assumed to define all keys. We
  406. # run _style_to_curses() for non-existing keys as well, so that we
  407. # print warnings for errors to the right of '=' for those too.
  408. if key not in _style and not parsing_default:
  409. _warn("Ignoring non-existent style", key)
  410. # If data is a reference to another key, copy its style
  411. if data in _style:
  412. _style[key] = _style[data]
  413. else:
  414. _style[key] = _style_to_curses(data)
  415. elif sline in _STYLES:
  416. # Recursively parse style template. Ignore styles that don't exist,
  417. # for backwards/forwards compatibility.
  418. _parse_style(_STYLES[sline], parsing_default)
  419. else:
  420. _warn("Ignoring non-existent style template", sline)
  421. # Dictionary mapping element types to the curses attributes used to display
  422. # them
  423. _style = {}
  424. def _style_to_curses(style_def):
  425. # Parses a style definition string (<element>=<style>), returning
  426. # a (fg_color, bg_color, attributes) tuple.
  427. def parse_color(color_def):
  428. color_def = color_def.split(":", 1)[1]
  429. # HTML format, #RRGGBB
  430. if re.match("#[A-Fa-f0-9]{6}", color_def):
  431. return _color_from_rgb((
  432. int(color_def[1:3], 16),
  433. int(color_def[3:5], 16),
  434. int(color_def[5:7], 16)))
  435. if color_def in _NAMED_COLORS:
  436. color_num = _color_from_num(_NAMED_COLORS[color_def])
  437. else:
  438. try:
  439. color_num = _color_from_num(int(color_def, 0))
  440. except ValueError:
  441. _warn("Ignoring color", color_def, "that's neither "
  442. "predefined nor a number")
  443. return -1
  444. if not -1 <= color_num < curses.COLORS:
  445. _warn("Ignoring color {}, which is outside the range "
  446. "-1..curses.COLORS-1 (-1..{})"
  447. .format(color_def, curses.COLORS - 1))
  448. return -1
  449. return color_num
  450. fg_color = -1
  451. bg_color = -1
  452. attrs = 0
  453. if style_def:
  454. for field in style_def.split(","):
  455. if field.startswith("fg:"):
  456. fg_color = parse_color(field)
  457. elif field.startswith("bg:"):
  458. bg_color = parse_color(field)
  459. elif field == "bold":
  460. # A_BOLD tends to produce faint and hard-to-read text on the
  461. # Windows console, especially with the old color scheme, before
  462. # the introduction of
  463. # https://blogs.msdn.microsoft.com/commandline/2017/08/02/updating-the-windows-console-colors/
  464. attrs |= curses.A_NORMAL if _IS_WINDOWS else curses.A_BOLD
  465. elif field == "standout":
  466. attrs |= curses.A_STANDOUT
  467. elif field == "underline":
  468. attrs |= curses.A_UNDERLINE
  469. else:
  470. _warn("Ignoring unknown style attribute", field)
  471. return _style_attr(fg_color, bg_color, attrs)
  472. def _init_styles():
  473. if curses.has_colors():
  474. try:
  475. curses.use_default_colors()
  476. except curses.error:
  477. # Ignore errors on funky terminals that support colors but not
  478. # using default colors. Worst it can do is break transparency and
  479. # the like. Ran across this with the MSYS2/winpty setup in
  480. # https://github.com/msys2/MINGW-packages/issues/5823, though there
  481. # seems to be a lot of general brokenness there.
  482. pass
  483. # Use the 'default' theme as the base, and add any user-defined style
  484. # settings from the environment
  485. _parse_style("default", True)
  486. if "MENUCONFIG_STYLE" in os.environ:
  487. _parse_style(os.environ["MENUCONFIG_STYLE"], False)
  488. else:
  489. # Force the 'monochrome' theme if the terminal doesn't support colors.
  490. # MENUCONFIG_STYLE is likely to mess things up here (though any colors
  491. # would be ignored), so ignore it.
  492. _parse_style("monochrome", True)
  493. # color_attribs holds the color pairs we've already created, indexed by a
  494. # (<foreground color>, <background color>) tuple.
  495. #
  496. # Obscure Python: We never pass a value for color_attribs, and it keeps
  497. # pointing to the same dict. This avoids a global.
  498. def _style_attr(fg_color, bg_color, attribs, color_attribs={}):
  499. # Returns an attribute with the specified foreground and background color
  500. # and the attributes in 'attribs'. Reuses color pairs already created if
  501. # possible, and creates a new color pair otherwise.
  502. #
  503. # Returns 'attribs' if colors aren't supported.
  504. if not curses.has_colors():
  505. return attribs
  506. if (fg_color, bg_color) not in color_attribs:
  507. # Create new color pair. Color pair number 0 is hardcoded and cannot be
  508. # changed, hence the +1s.
  509. curses.init_pair(len(color_attribs) + 1, fg_color, bg_color)
  510. color_attribs[(fg_color, bg_color)] = \
  511. curses.color_pair(len(color_attribs) + 1)
  512. return color_attribs[(fg_color, bg_color)] | attribs
  513. #
  514. # Main application
  515. #
  516. def _main():
  517. menuconfig(standard_kconfig(__doc__))
  518. def menuconfig(kconf):
  519. """
  520. Launches the configuration interface, returning after the user exits.
  521. kconf:
  522. Kconfig instance to be configured
  523. """
  524. global _kconf
  525. global _conf_filename
  526. global _conf_changed
  527. global _minconf_filename
  528. global _show_all
  529. _kconf = kconf
  530. # Filename to save configuration to
  531. _conf_filename = standard_config_filename()
  532. # Load existing configuration and set _conf_changed True if it is outdated
  533. _conf_changed = _load_config()
  534. # Filename to save minimal configuration to
  535. _minconf_filename = "defconfig"
  536. # Any visible items in the top menu?
  537. _show_all = False
  538. if not _shown_nodes(kconf.top_node):
  539. # Nothing visible. Start in show-all mode and try again.
  540. _show_all = True
  541. if not _shown_nodes(kconf.top_node):
  542. # Give up. The implementation relies on always having a selected
  543. # node.
  544. print("Empty configuration -- nothing to configure.\n"
  545. "Check that environment variables are set properly.")
  546. return
  547. # Disable warnings. They get mangled in curses mode, and we deal with
  548. # errors ourselves.
  549. kconf.warn = False
  550. # Make curses use the locale settings specified in the environment
  551. locale.setlocale(locale.LC_ALL, "")
  552. # Try to fix Unicode issues on systems with bad defaults
  553. if _CHANGE_C_LC_CTYPE_TO_UTF8:
  554. _change_c_lc_ctype_to_utf8()
  555. # Get rid of the delay between pressing ESC and jumping to the parent menu,
  556. # unless the user has set ESCDELAY (see ncurses(3)). This makes the UI much
  557. # smoother to work with.
  558. #
  559. # Note: This is strictly pretty iffy, since escape codes for e.g. cursor
  560. # keys start with ESC, but I've never seen it cause problems in practice
  561. # (probably because it's unlikely that the escape code for a key would get
  562. # split up across read()s, at least with a terminal emulator). Please
  563. # report if you run into issues. Some suitable small default value could be
  564. # used here instead in that case. Maybe it's silly to not put in the
  565. # smallest imperceptible delay here already, though I don't like guessing.
  566. #
  567. # (From a quick glance at the ncurses source code, ESCDELAY might only be
  568. # relevant for mouse events there, so maybe escapes are assumed to arrive
  569. # in one piece already...)
  570. os.environ.setdefault("ESCDELAY", "0")
  571. # Enter curses mode. _menuconfig() returns a string to print on exit, after
  572. # curses has been de-initialized.
  573. print(curses.wrapper(_menuconfig))
  574. def _load_config():
  575. # Loads any existing .config file. See the Kconfig.load_config() docstring.
  576. #
  577. # Returns True if .config is missing or outdated. We always prompt for
  578. # saving the configuration in that case.
  579. print(_kconf.load_config())
  580. if not os.path.exists(_conf_filename):
  581. # No .config
  582. return True
  583. return _needs_save()
  584. def _needs_save():
  585. # Returns True if a just-loaded .config file is outdated (would get
  586. # modified when saving)
  587. if _kconf.missing_syms:
  588. # Assignments to undefined symbols in the .config
  589. return True
  590. for sym in _kconf.unique_defined_syms:
  591. if sym.user_value is None:
  592. if sym.config_string:
  593. # Unwritten symbol
  594. return True
  595. elif sym.orig_type in (BOOL, TRISTATE):
  596. if sym.tri_value != sym.user_value:
  597. # Written bool/tristate symbol, new value
  598. return True
  599. elif sym.str_value != sym.user_value:
  600. # Written string/int/hex symbol, new value
  601. return True
  602. # No need to prompt for save
  603. return False
  604. # Global variables used below:
  605. #
  606. # _stdscr:
  607. # stdscr from curses
  608. #
  609. # _cur_menu:
  610. # Menu node of the menu (or menuconfig symbol, or choice) currently being
  611. # shown
  612. #
  613. # _shown:
  614. # List of items in _cur_menu that are shown (ignoring scrolling). In
  615. # show-all mode, this list contains all items in _cur_menu. Otherwise, it
  616. # contains just the visible items.
  617. #
  618. # _sel_node_i:
  619. # Index in _shown of the currently selected node
  620. #
  621. # _menu_scroll:
  622. # Index in _shown of the top row of the main display
  623. #
  624. # _parent_screen_rows:
  625. # List/stack of the row numbers that the selections in the parent menus
  626. # appeared on. This is used to prevent the scrolling from jumping around
  627. # when going in and out of menus.
  628. #
  629. # _show_help/_show_name/_show_all:
  630. # If True, the corresponding mode is on. See the module docstring.
  631. #
  632. # _conf_filename:
  633. # File to save the configuration to
  634. #
  635. # _minconf_filename:
  636. # File to save minimal configurations to
  637. #
  638. # _conf_changed:
  639. # True if the configuration has been changed. If False, we don't bother
  640. # showing the save-and-quit dialog.
  641. #
  642. # We reset this to False whenever the configuration is saved explicitly
  643. # from the save dialog.
  644. def _menuconfig(stdscr):
  645. # Logic for the main display, with the list of symbols, etc.
  646. global _stdscr
  647. global _conf_filename
  648. global _conf_changed
  649. global _minconf_filename
  650. global _show_help
  651. global _show_name
  652. _stdscr = stdscr
  653. _init()
  654. while True:
  655. _draw_main()
  656. curses.doupdate()
  657. c = _getch_compat(_menu_win)
  658. if c == curses.KEY_RESIZE:
  659. _resize_main()
  660. elif c in (curses.KEY_DOWN, "j", "J"):
  661. _select_next_menu_entry()
  662. elif c in (curses.KEY_UP, "k", "K"):
  663. _select_prev_menu_entry()
  664. elif c in (curses.KEY_NPAGE, "\x04"): # Page Down/Ctrl-D
  665. # Keep it simple. This way we get sane behavior for small windows,
  666. # etc., for free.
  667. for _ in range(_PG_JUMP):
  668. _select_next_menu_entry()
  669. elif c in (curses.KEY_PPAGE, "\x15"): # Page Up/Ctrl-U
  670. for _ in range(_PG_JUMP):
  671. _select_prev_menu_entry()
  672. elif c in (curses.KEY_END, "G"):
  673. _select_last_menu_entry()
  674. elif c in (curses.KEY_HOME, "g"):
  675. _select_first_menu_entry()
  676. elif c == " ":
  677. # Toggle the node if possible
  678. sel_node = _shown[_sel_node_i]
  679. if not _change_node(sel_node):
  680. _enter_menu(sel_node)
  681. elif c in (curses.KEY_RIGHT, "\n", "l", "L"):
  682. # Enter the node if possible
  683. sel_node = _shown[_sel_node_i]
  684. if not _enter_menu(sel_node):
  685. _change_node(sel_node)
  686. elif c in ("n", "N"):
  687. _set_sel_node_tri_val(0)
  688. elif c in ("m", "M"):
  689. _set_sel_node_tri_val(1)
  690. elif c in ("y", "Y"):
  691. _set_sel_node_tri_val(2)
  692. elif c in (curses.KEY_LEFT, curses.KEY_BACKSPACE, _ERASE_CHAR,
  693. "\x1B", "h", "H"): # \x1B = ESC
  694. if c == "\x1B" and _cur_menu is _kconf.top_node:
  695. res = _quit_dialog()
  696. if res:
  697. return res
  698. else:
  699. _leave_menu()
  700. elif c in ("o", "O"):
  701. _load_dialog()
  702. elif c in ("s", "S"):
  703. filename = _save_dialog(_kconf.write_config, _conf_filename,
  704. "configuration")
  705. if filename:
  706. _conf_filename = filename
  707. _conf_changed = False
  708. elif c in ("d", "D"):
  709. filename = _save_dialog(_kconf.write_min_config, _minconf_filename,
  710. "minimal configuration")
  711. if filename:
  712. _minconf_filename = filename
  713. elif c == "/":
  714. _jump_to_dialog()
  715. # The terminal might have been resized while the fullscreen jump-to
  716. # dialog was open
  717. _resize_main()
  718. elif c == "?":
  719. _info_dialog(_shown[_sel_node_i], False)
  720. # The terminal might have been resized while the fullscreen info
  721. # dialog was open
  722. _resize_main()
  723. elif c in ("f", "F"):
  724. _show_help = not _show_help
  725. _set_style(_help_win, "show-help" if _show_help else "help")
  726. _resize_main()
  727. elif c in ("c", "C"):
  728. _show_name = not _show_name
  729. elif c in ("a", "A"):
  730. _toggle_show_all()
  731. elif c in ("q", "Q"):
  732. res = _quit_dialog()
  733. if res:
  734. return res
  735. def _quit_dialog():
  736. if not _conf_changed:
  737. return "No changes to save (for '{}')".format(_conf_filename)
  738. while True:
  739. c = _key_dialog(
  740. "Quit",
  741. " Save configuration?\n"
  742. "\n"
  743. "(Y)es (N)o (C)ancel",
  744. "ync")
  745. if c is None or c == "c":
  746. return None
  747. if c == "y":
  748. # Returns a message to print
  749. msg = _try_save(_kconf.write_config, _conf_filename, "configuration")
  750. if msg:
  751. return msg
  752. elif c == "n":
  753. return "Configuration ({}) was not saved".format(_conf_filename)
  754. def _init():
  755. # Initializes the main display with the list of symbols, etc. Also does
  756. # misc. global initialization that needs to happen after initializing
  757. # curses.
  758. global _ERASE_CHAR
  759. global _path_win
  760. global _top_sep_win
  761. global _menu_win
  762. global _bot_sep_win
  763. global _help_win
  764. global _parent_screen_rows
  765. global _cur_menu
  766. global _shown
  767. global _sel_node_i
  768. global _menu_scroll
  769. global _show_help
  770. global _show_name
  771. # Looking for this in addition to KEY_BACKSPACE (which is unreliable) makes
  772. # backspace work with TERM=vt100. That makes it likely to work in sane
  773. # environments.
  774. _ERASE_CHAR = curses.erasechar()
  775. if sys.version_info[0] >= 3:
  776. # erasechar() returns a one-byte bytes object on Python 3. This sets
  777. # _ERASE_CHAR to a blank string if it can't be decoded, which should be
  778. # harmless.
  779. _ERASE_CHAR = _ERASE_CHAR.decode("utf-8", "ignore")
  780. _init_styles()
  781. # Hide the cursor
  782. _safe_curs_set(0)
  783. # Initialize windows
  784. # Top row, with menu path
  785. _path_win = _styled_win("path")
  786. # Separator below menu path, with title and arrows pointing up
  787. _top_sep_win = _styled_win("separator")
  788. # List of menu entries with symbols, etc.
  789. _menu_win = _styled_win("list")
  790. _menu_win.keypad(True)
  791. # Row below menu list, with arrows pointing down
  792. _bot_sep_win = _styled_win("separator")
  793. # Help window with keys at the bottom. Shows help texts in show-help mode.
  794. _help_win = _styled_win("help")
  795. # The rows we'd like the nodes in the parent menus to appear on. This
  796. # prevents the scroll from jumping around when going in and out of menus.
  797. _parent_screen_rows = []
  798. # Initial state
  799. _cur_menu = _kconf.top_node
  800. _shown = _shown_nodes(_cur_menu)
  801. _sel_node_i = _menu_scroll = 0
  802. _show_help = _show_name = False
  803. # Give windows their initial size
  804. _resize_main()
  805. def _resize_main():
  806. # Resizes the main display, with the list of symbols, etc., to fill the
  807. # terminal
  808. global _menu_scroll
  809. screen_height, screen_width = _stdscr.getmaxyx()
  810. _path_win.resize(1, screen_width)
  811. _top_sep_win.resize(1, screen_width)
  812. _bot_sep_win.resize(1, screen_width)
  813. help_win_height = _SHOW_HELP_HEIGHT if _show_help else \
  814. len(_MAIN_HELP_LINES)
  815. menu_win_height = screen_height - help_win_height - 3
  816. if menu_win_height >= 1:
  817. _menu_win.resize(menu_win_height, screen_width)
  818. _help_win.resize(help_win_height, screen_width)
  819. _top_sep_win.mvwin(1, 0)
  820. _menu_win.mvwin(2, 0)
  821. _bot_sep_win.mvwin(2 + menu_win_height, 0)
  822. _help_win.mvwin(2 + menu_win_height + 1, 0)
  823. else:
  824. # Degenerate case. Give up on nice rendering and just prevent errors.
  825. menu_win_height = 1
  826. _menu_win.resize(1, screen_width)
  827. _help_win.resize(1, screen_width)
  828. for win in _top_sep_win, _menu_win, _bot_sep_win, _help_win:
  829. win.mvwin(0, 0)
  830. # Adjust the scroll so that the selected node is still within the window,
  831. # if needed
  832. if _sel_node_i - _menu_scroll >= menu_win_height:
  833. _menu_scroll = _sel_node_i - menu_win_height + 1
  834. def _height(win):
  835. # Returns the height of 'win'
  836. return win.getmaxyx()[0]
  837. def _width(win):
  838. # Returns the width of 'win'
  839. return win.getmaxyx()[1]
  840. def _enter_menu(menu):
  841. # Makes 'menu' the currently displayed menu. In addition to actual 'menu's,
  842. # "menu" here includes choices and symbols defined with the 'menuconfig'
  843. # keyword.
  844. #
  845. # Returns False if 'menu' can't be entered.
  846. global _cur_menu
  847. global _shown
  848. global _sel_node_i
  849. global _menu_scroll
  850. if not menu.is_menuconfig:
  851. return False # Not a menu
  852. shown_sub = _shown_nodes(menu)
  853. # Never enter empty menus. We depend on having a current node.
  854. if not shown_sub:
  855. return False
  856. # Remember where the current node appears on the screen, so we can try
  857. # to get it to appear in the same place when we leave the menu
  858. _parent_screen_rows.append(_sel_node_i - _menu_scroll)
  859. # Jump into menu
  860. _cur_menu = menu
  861. _shown = shown_sub
  862. _sel_node_i = _menu_scroll = 0
  863. if isinstance(menu.item, Choice):
  864. _select_selected_choice_sym()
  865. return True
  866. def _select_selected_choice_sym():
  867. # Puts the cursor on the currently selected (y-valued) choice symbol, if
  868. # any. Does nothing if if the choice has no selection (is not visible/in y
  869. # mode).
  870. global _sel_node_i
  871. choice = _cur_menu.item
  872. if choice.selection:
  873. # Search through all menu nodes to handle choice symbols being defined
  874. # in multiple locations
  875. for node in choice.selection.nodes:
  876. if node in _shown:
  877. _sel_node_i = _shown.index(node)
  878. _center_vertically()
  879. return
  880. def _jump_to(node):
  881. # Jumps directly to the menu node 'node'
  882. global _cur_menu
  883. global _shown
  884. global _sel_node_i
  885. global _menu_scroll
  886. global _show_all
  887. global _parent_screen_rows
  888. # Clear remembered menu locations. We might not even have been in the
  889. # parent menus before.
  890. _parent_screen_rows = []
  891. old_show_all = _show_all
  892. jump_into = (isinstance(node.item, Choice) or node.item == MENU) and \
  893. node.list
  894. # If we're jumping to a non-empty choice or menu, jump to the first entry
  895. # in it instead of jumping to its menu node
  896. if jump_into:
  897. _cur_menu = node
  898. node = node.list
  899. else:
  900. _cur_menu = _parent_menu(node)
  901. _shown = _shown_nodes(_cur_menu)
  902. if node not in _shown:
  903. # The node wouldn't be shown. Turn on show-all to show it.
  904. _show_all = True
  905. _shown = _shown_nodes(_cur_menu)
  906. _sel_node_i = _shown.index(node)
  907. if jump_into and not old_show_all and _show_all:
  908. # If we're jumping into a choice or menu and were forced to turn on
  909. # show-all because the first entry wasn't visible, try turning it off.
  910. # That will land us at the first visible node if there are visible
  911. # nodes, and is a no-op otherwise.
  912. _toggle_show_all()
  913. _center_vertically()
  914. # If we're jumping to a non-empty choice, jump to the selected symbol, if
  915. # any
  916. if jump_into and isinstance(_cur_menu.item, Choice):
  917. _select_selected_choice_sym()
  918. def _leave_menu():
  919. # Jumps to the parent menu of the current menu. Does nothing if we're in
  920. # the top menu.
  921. global _cur_menu
  922. global _shown
  923. global _sel_node_i
  924. global _menu_scroll
  925. if _cur_menu is _kconf.top_node:
  926. return
  927. # Jump to parent menu
  928. parent = _parent_menu(_cur_menu)
  929. _shown = _shown_nodes(parent)
  930. _sel_node_i = _shown.index(_cur_menu)
  931. _cur_menu = parent
  932. # Try to make the menu entry appear on the same row on the screen as it did
  933. # before we entered the menu.
  934. if _parent_screen_rows:
  935. # The terminal might have shrunk since we were last in the parent menu
  936. screen_row = min(_parent_screen_rows.pop(), _height(_menu_win) - 1)
  937. _menu_scroll = max(_sel_node_i - screen_row, 0)
  938. else:
  939. # No saved parent menu locations, meaning we jumped directly to some
  940. # node earlier
  941. _center_vertically()
  942. def _select_next_menu_entry():
  943. # Selects the menu entry after the current one, adjusting the scroll if
  944. # necessary. Does nothing if we're already at the last menu entry.
  945. global _sel_node_i
  946. global _menu_scroll
  947. if _sel_node_i < len(_shown) - 1:
  948. # Jump to the next node
  949. _sel_node_i += 1
  950. # If the new node is sufficiently close to the edge of the menu window
  951. # (as determined by _SCROLL_OFFSET), increase the scroll by one. This
  952. # gives nice and non-jumpy behavior even when
  953. # _SCROLL_OFFSET >= _height(_menu_win).
  954. if _sel_node_i >= _menu_scroll + _height(_menu_win) - _SCROLL_OFFSET \
  955. and _menu_scroll < _max_scroll(_shown, _menu_win):
  956. _menu_scroll += 1
  957. def _select_prev_menu_entry():
  958. # Selects the menu entry before the current one, adjusting the scroll if
  959. # necessary. Does nothing if we're already at the first menu entry.
  960. global _sel_node_i
  961. global _menu_scroll
  962. if _sel_node_i > 0:
  963. # Jump to the previous node
  964. _sel_node_i -= 1
  965. # See _select_next_menu_entry()
  966. if _sel_node_i < _menu_scroll + _SCROLL_OFFSET:
  967. _menu_scroll = max(_menu_scroll - 1, 0)
  968. def _select_last_menu_entry():
  969. # Selects the last menu entry in the current menu
  970. global _sel_node_i
  971. global _menu_scroll
  972. _sel_node_i = len(_shown) - 1
  973. _menu_scroll = _max_scroll(_shown, _menu_win)
  974. def _select_first_menu_entry():
  975. # Selects the first menu entry in the current menu
  976. global _sel_node_i
  977. global _menu_scroll
  978. _sel_node_i = _menu_scroll = 0
  979. def _toggle_show_all():
  980. # Toggles show-all mode on/off. If turning it off would give no visible
  981. # items in the current menu, it is left on.
  982. global _show_all
  983. global _shown
  984. global _sel_node_i
  985. global _menu_scroll
  986. # Row on the screen the cursor is on. Preferably we want the same row to
  987. # stay highlighted.
  988. old_row = _sel_node_i - _menu_scroll
  989. _show_all = not _show_all
  990. # List of new nodes to be shown after toggling _show_all
  991. new_shown = _shown_nodes(_cur_menu)
  992. # Find a good node to select. The selected node might disappear if show-all
  993. # mode is turned off.
  994. # Select the previously selected node itself if it is still visible. If
  995. # there are visible nodes before it, select the closest one.
  996. for node in _shown[_sel_node_i::-1]:
  997. if node in new_shown:
  998. _sel_node_i = new_shown.index(node)
  999. break
  1000. else:
  1001. # No visible nodes before the previously selected node. Select the
  1002. # closest visible node after it instead.
  1003. for node in _shown[_sel_node_i + 1:]:
  1004. if node in new_shown:
  1005. _sel_node_i = new_shown.index(node)
  1006. break
  1007. else:
  1008. # No visible nodes at all, meaning show-all was turned off inside
  1009. # an invisible menu. Don't allow that, as the implementation relies
  1010. # on always having a selected node.
  1011. _show_all = True
  1012. return
  1013. _shown = new_shown
  1014. # Try to make the cursor stay on the same row in the menu window. This
  1015. # might be impossible if too many nodes have disappeared above the node.
  1016. _menu_scroll = max(_sel_node_i - old_row, 0)
  1017. def _center_vertically():
  1018. # Centers the selected node vertically, if possible
  1019. global _menu_scroll
  1020. _menu_scroll = min(max(_sel_node_i - _height(_menu_win)//2, 0),
  1021. _max_scroll(_shown, _menu_win))
  1022. def _draw_main():
  1023. # Draws the "main" display, with the list of symbols, the header, and the
  1024. # footer.
  1025. #
  1026. # This could be optimized to only update the windows that have actually
  1027. # changed, but keep it simple for now and let curses sort it out.
  1028. term_width = _width(_stdscr)
  1029. #
  1030. # Update the separator row below the menu path
  1031. #
  1032. _top_sep_win.erase()
  1033. # Draw arrows pointing up if the symbol window is scrolled down. Draw them
  1034. # before drawing the title, so the title ends up on top for small windows.
  1035. if _menu_scroll > 0:
  1036. _safe_hline(_top_sep_win, 0, 4, curses.ACS_UARROW, _N_SCROLL_ARROWS)
  1037. # Add the 'mainmenu' text as the title, centered at the top
  1038. _safe_addstr(_top_sep_win,
  1039. 0, max((term_width - len(_kconf.mainmenu_text))//2, 0),
  1040. _kconf.mainmenu_text)
  1041. _top_sep_win.noutrefresh()
  1042. # Note: The menu path at the top is deliberately updated last. See below.
  1043. #
  1044. # Update the symbol window
  1045. #
  1046. _menu_win.erase()
  1047. # Draw the _shown nodes starting from index _menu_scroll up to either as
  1048. # many as fit in the window, or to the end of _shown
  1049. for i in range(_menu_scroll,
  1050. min(_menu_scroll + _height(_menu_win), len(_shown))):
  1051. node = _shown[i]
  1052. # The 'not _show_all' test avoids showing invisible items in red
  1053. # outside show-all mode, which could look confusing/broken. Invisible
  1054. # symbols show up outside show-all mode if an invisible symbol has
  1055. # visible children in an implicit (indented) menu.
  1056. if _visible(node) or not _show_all:
  1057. style = _style["selection" if i == _sel_node_i else "list"]
  1058. else:
  1059. style = _style["inv-selection" if i == _sel_node_i else "inv-list"]
  1060. _safe_addstr(_menu_win, i - _menu_scroll, 0, _node_str(node), style)
  1061. _menu_win.noutrefresh()
  1062. #
  1063. # Update the bottom separator window
  1064. #
  1065. _bot_sep_win.erase()
  1066. # Draw arrows pointing down if the symbol window is scrolled up
  1067. if _menu_scroll < _max_scroll(_shown, _menu_win):
  1068. _safe_hline(_bot_sep_win, 0, 4, curses.ACS_DARROW, _N_SCROLL_ARROWS)
  1069. # Indicate when show-name/show-help/show-all mode is enabled
  1070. enabled_modes = []
  1071. if _show_help:
  1072. enabled_modes.append("show-help (toggle with [F])")
  1073. if _show_name:
  1074. enabled_modes.append("show-name")
  1075. if _show_all:
  1076. enabled_modes.append("show-all")
  1077. if enabled_modes:
  1078. s = " and ".join(enabled_modes) + " mode enabled"
  1079. _safe_addstr(_bot_sep_win, 0, max(term_width - len(s) - 2, 0), s)
  1080. _bot_sep_win.noutrefresh()
  1081. #
  1082. # Update the help window, which shows either key bindings or help texts
  1083. #
  1084. _help_win.erase()
  1085. if _show_help:
  1086. node = _shown[_sel_node_i]
  1087. if isinstance(node.item, (Symbol, Choice)) and node.help:
  1088. help_lines = textwrap.wrap(node.help, _width(_help_win))
  1089. for i in range(min(_height(_help_win), len(help_lines))):
  1090. _safe_addstr(_help_win, i, 0, help_lines[i])
  1091. else:
  1092. _safe_addstr(_help_win, 0, 0, "(no help)")
  1093. else:
  1094. for i, line in enumerate(_MAIN_HELP_LINES):
  1095. _safe_addstr(_help_win, i, 0, line)
  1096. _help_win.noutrefresh()
  1097. #
  1098. # Update the top row with the menu path.
  1099. #
  1100. # Doing this last leaves the cursor on the top row, which avoids some minor
  1101. # annoying jumpiness in gnome-terminal when reducing the height of the
  1102. # terminal. It seems to happen whenever the row with the cursor on it
  1103. # disappears.
  1104. #
  1105. _path_win.erase()
  1106. # Draw the menu path ("(Top) -> Menu -> Submenu -> ...")
  1107. menu_prompts = []
  1108. menu = _cur_menu
  1109. while menu is not _kconf.top_node:
  1110. # Promptless choices can be entered in show-all mode. Use
  1111. # standard_sc_expr_str() for them, so they show up as
  1112. # '<choice (name if any)>'.
  1113. menu_prompts.append(menu.prompt[0] if menu.prompt else
  1114. standard_sc_expr_str(menu.item))
  1115. menu = menu.parent
  1116. menu_prompts.append("(Top)")
  1117. menu_prompts.reverse()
  1118. # Hack: We can't put ACS_RARROW directly in the string. Temporarily
  1119. # represent it with NULL.
  1120. menu_path_str = " \0 ".join(menu_prompts)
  1121. # Scroll the menu path to the right if needed to make the current menu's
  1122. # title visible
  1123. if len(menu_path_str) > term_width:
  1124. menu_path_str = menu_path_str[len(menu_path_str) - term_width:]
  1125. # Print the path with the arrows reinserted
  1126. split_path = menu_path_str.split("\0")
  1127. _safe_addstr(_path_win, split_path[0])
  1128. for s in split_path[1:]:
  1129. _safe_addch(_path_win, curses.ACS_RARROW)
  1130. _safe_addstr(_path_win, s)
  1131. _path_win.noutrefresh()
  1132. def _parent_menu(node):
  1133. # Returns the menu node of the menu that contains 'node'. In addition to
  1134. # proper 'menu's, this might also be a 'menuconfig' symbol or a 'choice'.
  1135. # "Menu" here means a menu in the interface.
  1136. menu = node.parent
  1137. while not menu.is_menuconfig:
  1138. menu = menu.parent
  1139. return menu
  1140. def _shown_nodes(menu):
  1141. # Returns the list of menu nodes from 'menu' (see _parent_menu()) that
  1142. # would be shown when entering it
  1143. def rec(node):
  1144. res = []
  1145. while node:
  1146. if _visible(node) or _show_all:
  1147. res.append(node)
  1148. if node.list and not node.is_menuconfig:
  1149. # Nodes from implicit menu created from dependencies. Will
  1150. # be shown indented. Note that is_menuconfig is True for
  1151. # menus and choices as well as 'menuconfig' symbols.
  1152. res += rec(node.list)
  1153. elif node.list and isinstance(node.item, Symbol):
  1154. # Show invisible symbols if they have visible children. This
  1155. # can happen for an m/y-valued symbol with an optional prompt
  1156. # ('prompt "foo" is COND') that is currently disabled. Note
  1157. # that it applies to both 'config' and 'menuconfig' symbols.
  1158. shown_children = rec(node.list)
  1159. if shown_children:
  1160. res.append(node)
  1161. if not node.is_menuconfig:
  1162. res += shown_children
  1163. node = node.next
  1164. return res
  1165. if isinstance(menu.item, Choice):
  1166. # For named choices defined in multiple locations, entering the choice
  1167. # at a particular menu node would normally only show the choice symbols
  1168. # defined there (because that's what the MenuNode tree looks like).
  1169. #
  1170. # That might look confusing, and makes extending choices by defining
  1171. # them in multiple locations less useful. Instead, gather all the child
  1172. # menu nodes for all the choices whenever a choice is entered. That
  1173. # makes all choice symbols visible at all locations.
  1174. #
  1175. # Choices can contain non-symbol items (people do all sorts of weird
  1176. # stuff with them), hence the generality here. We really need to
  1177. # preserve the menu tree at each choice location.
  1178. #
  1179. # Note: Named choices are pretty broken in the C tools, and this is
  1180. # super obscure, so you probably won't find much that relies on this.
  1181. # This whole 'if' could be deleted if you don't care about defining
  1182. # choices in multiple locations to add symbols (which will still work,
  1183. # just with things being displayed in a way that might be unexpected).
  1184. # Do some additional work to avoid listing choice symbols twice if all
  1185. # or part of the choice is copied in multiple locations (e.g. by
  1186. # including some Kconfig file multiple times). We give the prompts at
  1187. # the current location precedence.
  1188. seen_syms = {node.item for node in rec(menu.list)
  1189. if isinstance(node.item, Symbol)}
  1190. res = []
  1191. for choice_node in menu.item.nodes:
  1192. for node in rec(choice_node.list):
  1193. # 'choice_node is menu' checks if we're dealing with the
  1194. # current location
  1195. if node.item not in seen_syms or choice_node is menu:
  1196. res.append(node)
  1197. if isinstance(node.item, Symbol):
  1198. seen_syms.add(node.item)
  1199. return res
  1200. return rec(menu.list)
  1201. def _visible(node):
  1202. # Returns True if the node should appear in the menu (outside show-all
  1203. # mode)
  1204. return node.prompt and expr_value(node.prompt[1]) and not \
  1205. (node.item == MENU and not expr_value(node.visibility))
  1206. def _change_node(node):
  1207. # Changes the value of the menu node 'node' if it is a symbol. Bools and
  1208. # tristates are toggled, while other symbol types pop up a text entry
  1209. # dialog.
  1210. #
  1211. # Returns False if the value of 'node' can't be changed.
  1212. if not _changeable(node):
  1213. return False
  1214. # sc = symbol/choice
  1215. sc = node.item
  1216. if sc.orig_type in (INT, HEX, STRING):
  1217. s = sc.str_value
  1218. while True:
  1219. s = _input_dialog(
  1220. "{} ({})".format(node.prompt[0], TYPE_TO_STR[sc.orig_type]),
  1221. s, _range_info(sc))
  1222. if s is None:
  1223. break
  1224. if sc.orig_type in (INT, HEX):
  1225. s = s.strip()
  1226. # 'make menuconfig' does this too. Hex values not starting with
  1227. # '0x' are accepted when loading .config files though.
  1228. if sc.orig_type == HEX and not s.startswith(("0x", "0X")):
  1229. s = "0x" + s
  1230. if _check_valid(sc, s):
  1231. _set_val(sc, s)
  1232. break
  1233. elif len(sc.assignable) == 1:
  1234. # Handles choice symbols for choices in y mode, which are a special
  1235. # case: .assignable can be (2,) while .tri_value is 0.
  1236. _set_val(sc, sc.assignable[0])
  1237. else:
  1238. # Set the symbol to the value after the current value in
  1239. # sc.assignable, with wrapping
  1240. val_index = sc.assignable.index(sc.tri_value)
  1241. _set_val(sc, sc.assignable[(val_index + 1) % len(sc.assignable)])
  1242. if _is_y_mode_choice_sym(sc) and not node.list:
  1243. # Immediately jump to the parent menu after making a choice selection,
  1244. # like 'make menuconfig' does, except if the menu node has children
  1245. # (which can happen if a symbol 'depends on' a choice symbol that
  1246. # immediately precedes it).
  1247. _leave_menu()
  1248. return True
  1249. def _changeable(node):
  1250. # Returns True if the value if 'node' can be changed
  1251. sc = node.item
  1252. if not isinstance(sc, (Symbol, Choice)):
  1253. return False
  1254. # This will hit for invisible symbols, which appear in show-all mode and
  1255. # when an invisible symbol has visible children (which can happen e.g. for
  1256. # symbols with optional prompts)
  1257. if not (node.prompt and expr_value(node.prompt[1])):
  1258. return False
  1259. return sc.orig_type in (STRING, INT, HEX) or len(sc.assignable) > 1 \
  1260. or _is_y_mode_choice_sym(sc)
  1261. def _set_sel_node_tri_val(tri_val):
  1262. # Sets the value of the currently selected menu entry to 'tri_val', if that
  1263. # value can be assigned
  1264. sc = _shown[_sel_node_i].item
  1265. if isinstance(sc, (Symbol, Choice)) and tri_val in sc.assignable:
  1266. _set_val(sc, tri_val)
  1267. def _set_val(sc, val):
  1268. # Wrapper around Symbol/Choice.set_value() for updating the menu state and
  1269. # _conf_changed
  1270. global _conf_changed
  1271. # Use the string representation of tristate values. This makes the format
  1272. # consistent for all symbol types.
  1273. if val in TRI_TO_STR:
  1274. val = TRI_TO_STR[val]
  1275. if val != sc.str_value:
  1276. sc.set_value(val)
  1277. _conf_changed = True
  1278. # Changing the value of the symbol might have changed what items in the
  1279. # current menu are visible. Recalculate the state.
  1280. _update_menu()
  1281. def _update_menu():
  1282. # Updates the current menu after the value of a symbol or choice has been
  1283. # changed. Changing a value might change which items in the menu are
  1284. # visible.
  1285. #
  1286. # If possible, preserves the location of the cursor on the screen when
  1287. # items are added/removed above the selected item.
  1288. global _shown
  1289. global _sel_node_i
  1290. global _menu_scroll
  1291. # Row on the screen the cursor was on
  1292. old_row = _sel_node_i - _menu_scroll
  1293. sel_node = _shown[_sel_node_i]
  1294. # New visible nodes
  1295. _shown = _shown_nodes(_cur_menu)
  1296. # New index of selected node
  1297. _sel_node_i = _shown.index(sel_node)
  1298. # Try to make the cursor stay on the same row in the menu window. This
  1299. # might be impossible if too many nodes have disappeared above the node.
  1300. _menu_scroll = max(_sel_node_i - old_row, 0)
  1301. def _input_dialog(title, initial_text, info_text=None):
  1302. # Pops up a dialog that prompts the user for a string
  1303. #
  1304. # title:
  1305. # Title to display at the top of the dialog window's border
  1306. #
  1307. # initial_text:
  1308. # Initial text to prefill the input field with
  1309. #
  1310. # info_text:
  1311. # String to show next to the input field. If None, just the input field
  1312. # is shown.
  1313. win = _styled_win("body")
  1314. win.keypad(True)
  1315. info_lines = info_text.split("\n") if info_text else []
  1316. # Give the input dialog its initial size
  1317. _resize_input_dialog(win, title, info_lines)
  1318. _safe_curs_set(2)
  1319. # Input field text
  1320. s = initial_text
  1321. # Cursor position
  1322. i = len(initial_text)
  1323. def edit_width():
  1324. return _width(win) - 4
  1325. # Horizontal scroll offset
  1326. hscroll = max(i - edit_width() + 1, 0)
  1327. while True:
  1328. # Draw the "main" display with the menu, etc., so that resizing still
  1329. # works properly. This is like a stack of windows, only hardcoded for
  1330. # now.
  1331. _draw_main()
  1332. _draw_input_dialog(win, title, info_lines, s, i, hscroll)
  1333. curses.doupdate()
  1334. c = _getch_compat(win)
  1335. if c == curses.KEY_RESIZE:
  1336. # Resize the main display too. The dialog floats above it.
  1337. _resize_main()
  1338. _resize_input_dialog(win, title, info_lines)
  1339. elif c == "\n":
  1340. _safe_curs_set(0)
  1341. return s
  1342. elif c == "\x1B": # \x1B = ESC
  1343. _safe_curs_set(0)
  1344. return None
  1345. else:
  1346. s, i, hscroll = _edit_text(c, s, i, hscroll, edit_width())
  1347. def _resize_input_dialog(win, title, info_lines):
  1348. # Resizes the input dialog to a size appropriate for the terminal size
  1349. screen_height, screen_width = _stdscr.getmaxyx()
  1350. win_height = 5
  1351. if info_lines:
  1352. win_height += len(info_lines) + 1
  1353. win_height = min(win_height, screen_height)
  1354. win_width = max(_INPUT_DIALOG_MIN_WIDTH,
  1355. len(title) + 4,
  1356. *(len(line) + 4 for line in info_lines))
  1357. win_width = min(win_width, screen_width)
  1358. win.resize(win_height, win_width)
  1359. win.mvwin((screen_height - win_height)//2,
  1360. (screen_width - win_width)//2)
  1361. def _draw_input_dialog(win, title, info_lines, s, i, hscroll):
  1362. edit_width = _width(win) - 4
  1363. win.erase()
  1364. # Note: Perhaps having a separate window for the input field would be nicer
  1365. visible_s = s[hscroll:hscroll + edit_width]
  1366. _safe_addstr(win, 2, 2, visible_s + " "*(edit_width - len(visible_s)),
  1367. _style["edit"])
  1368. for linenr, line in enumerate(info_lines):
  1369. _safe_addstr(win, 4 + linenr, 2, line)
  1370. # Draw the frame last so that it overwrites the body text for small windows
  1371. _draw_frame(win, title)
  1372. _safe_move(win, 2, 2 + i - hscroll)
  1373. win.noutrefresh()
  1374. def _load_dialog():
  1375. # Dialog for loading a new configuration
  1376. global _conf_changed
  1377. global _conf_filename
  1378. global _show_all
  1379. if _conf_changed:
  1380. c = _key_dialog(
  1381. "Load",
  1382. "You have unsaved changes. Load new\n"
  1383. "configuration anyway?\n"
  1384. "\n"
  1385. " (O)K (C)ancel",
  1386. "oc")
  1387. if c is None or c == "c":
  1388. return
  1389. filename = _conf_filename
  1390. while True:
  1391. filename = _input_dialog("File to load", filename, _load_save_info())
  1392. if filename is None:
  1393. return
  1394. filename = os.path.expanduser(filename)
  1395. if _try_load(filename):
  1396. _conf_filename = filename
  1397. _conf_changed = _needs_save()
  1398. # Turn on show-all mode if the selected node is not visible after
  1399. # loading the new configuration. _shown still holds the old state.
  1400. if _shown[_sel_node_i] not in _shown_nodes(_cur_menu):
  1401. _show_all = True
  1402. _update_menu()
  1403. # The message dialog indirectly updates the menu display, so _msg()
  1404. # must be called after the new state has been initialized
  1405. _msg("Success", "Loaded " + filename)
  1406. return
  1407. def _try_load(filename):
  1408. # Tries to load a configuration file. Pops up an error and returns False on
  1409. # failure.
  1410. #
  1411. # filename:
  1412. # Configuration file to load
  1413. try:
  1414. _kconf.load_config(filename)
  1415. return True
  1416. except EnvironmentError as e:
  1417. _error("Error loading '{}'\n\n{} (errno: {})"
  1418. .format(filename, e.strerror, errno.errorcode[e.errno]))
  1419. return False
  1420. def _save_dialog(save_fn, default_filename, description):
  1421. # Dialog for saving the current configuration
  1422. #
  1423. # save_fn:
  1424. # Function to call with 'filename' to save the file
  1425. #
  1426. # default_filename:
  1427. # Prefilled filename in the input field
  1428. #
  1429. # description:
  1430. # String describing the thing being saved
  1431. #
  1432. # Return value:
  1433. # The path to the saved file, or None if no file was saved
  1434. filename = default_filename
  1435. while True:
  1436. filename = _input_dialog("Filename to save {} to".format(description),
  1437. filename, _load_save_info())
  1438. if filename is None:
  1439. return None
  1440. filename = os.path.expanduser(filename)
  1441. msg = _try_save(save_fn, filename, description)
  1442. if msg:
  1443. _msg("Success", msg)
  1444. return filename
  1445. def _try_save(save_fn, filename, description):
  1446. # Tries to save a configuration file. Returns a message to print on
  1447. # success.
  1448. #
  1449. # save_fn:
  1450. # Function to call with 'filename' to save the file
  1451. #
  1452. # description:
  1453. # String describing the thing being saved
  1454. #
  1455. # Return value:
  1456. # A message to print on success, and None on failure
  1457. try:
  1458. # save_fn() returns a message to print
  1459. return save_fn(filename)
  1460. except EnvironmentError as e:
  1461. _error("Error saving {} to '{}'\n\n{} (errno: {})"
  1462. .format(description, e.filename, e.strerror,
  1463. errno.errorcode[e.errno]))
  1464. return None
  1465. def _key_dialog(title, text, keys):
  1466. # Pops up a dialog that can be closed by pressing a key
  1467. #
  1468. # title:
  1469. # Title to display at the top of the dialog window's border
  1470. #
  1471. # text:
  1472. # Text to show in the dialog
  1473. #
  1474. # keys:
  1475. # List of keys that will close the dialog. Other keys (besides ESC) are
  1476. # ignored. The caller is responsible for providing a hint about which
  1477. # keys can be pressed in 'text'.
  1478. #
  1479. # Return value:
  1480. # The key that was pressed to close the dialog. Uppercase characters are
  1481. # converted to lowercase. ESC will always close the dialog, and returns
  1482. # None.
  1483. win = _styled_win("body")
  1484. win.keypad(True)
  1485. _resize_key_dialog(win, text)
  1486. while True:
  1487. # See _input_dialog()
  1488. _draw_main()
  1489. _draw_key_dialog(win, title, text)
  1490. curses.doupdate()
  1491. c = _getch_compat(win)
  1492. if c == curses.KEY_RESIZE:
  1493. # Resize the main display too. The dialog floats above it.
  1494. _resize_main()
  1495. _resize_key_dialog(win, text)
  1496. elif c == "\x1B": # \x1B = ESC
  1497. return None
  1498. elif isinstance(c, str):
  1499. c = c.lower()
  1500. if c in keys:
  1501. return c
  1502. def _resize_key_dialog(win, text):
  1503. # Resizes the key dialog to a size appropriate for the terminal size
  1504. screen_height, screen_width = _stdscr.getmaxyx()
  1505. lines = text.split("\n")
  1506. win_height = min(len(lines) + 4, screen_height)
  1507. win_width = min(max(len(line) for line in lines) + 4, screen_width)
  1508. win.resize(win_height, win_width)
  1509. win.mvwin((screen_height - win_height)//2,
  1510. (screen_width - win_width)//2)
  1511. def _draw_key_dialog(win, title, text):
  1512. win.erase()
  1513. for i, line in enumerate(text.split("\n")):
  1514. _safe_addstr(win, 2 + i, 2, line)
  1515. # Draw the frame last so that it overwrites the body text for small windows
  1516. _draw_frame(win, title)
  1517. win.noutrefresh()
  1518. def _draw_frame(win, title):
  1519. # Draw a frame around the inner edges of 'win', with 'title' at the top
  1520. win_height, win_width = win.getmaxyx()
  1521. win.attron(_style["frame"])
  1522. # Draw top/bottom edge
  1523. _safe_hline(win, 0, 0, " ", win_width)
  1524. _safe_hline(win, win_height - 1, 0, " ", win_width)
  1525. # Draw left/right edge
  1526. _safe_vline(win, 0, 0, " ", win_height)
  1527. _safe_vline(win, 0, win_width - 1, " ", win_height)
  1528. # Draw title
  1529. _safe_addstr(win, 0, max((win_width - len(title))//2, 0), title)
  1530. win.attroff(_style["frame"])
  1531. def _jump_to_dialog():
  1532. # Implements the jump-to dialog, where symbols can be looked up via
  1533. # incremental search and jumped to.
  1534. #
  1535. # Returns True if the user jumped to a symbol, and False if the dialog was
  1536. # canceled.
  1537. s = "" # Search text
  1538. prev_s = None # Previous search text
  1539. s_i = 0 # Search text cursor position
  1540. hscroll = 0 # Horizontal scroll offset
  1541. sel_node_i = 0 # Index of selected row
  1542. scroll = 0 # Index in 'matches' of the top row of the list
  1543. # Edit box at the top
  1544. edit_box = _styled_win("jump-edit")
  1545. edit_box.keypad(True)
  1546. # List of matches
  1547. matches_win = _styled_win("list")
  1548. # Bottom separator, with arrows pointing down
  1549. bot_sep_win = _styled_win("separator")
  1550. # Help window with instructions at the bottom
  1551. help_win = _styled_win("help")
  1552. # Give windows their initial size
  1553. _resize_jump_to_dialog(edit_box, matches_win, bot_sep_win, help_win,
  1554. sel_node_i, scroll)
  1555. _safe_curs_set(2)
  1556. # Logic duplication with _select_{next,prev}_menu_entry(), except we do a
  1557. # functional variant that returns the new (sel_node_i, scroll) values to
  1558. # avoid 'nonlocal'. TODO: Can this be factored out in some nice way?
  1559. def select_next_match():
  1560. if sel_node_i == len(matches) - 1:
  1561. return sel_node_i, scroll
  1562. if sel_node_i + 1 >= scroll + _height(matches_win) - _SCROLL_OFFSET \
  1563. and scroll < _max_scroll(matches, matches_win):
  1564. return sel_node_i + 1, scroll + 1
  1565. return sel_node_i + 1, scroll
  1566. def select_prev_match():
  1567. if sel_node_i == 0:
  1568. return sel_node_i, scroll
  1569. if sel_node_i - 1 < scroll + _SCROLL_OFFSET:
  1570. return sel_node_i - 1, max(scroll - 1, 0)
  1571. return sel_node_i - 1, scroll
  1572. while True:
  1573. if s != prev_s:
  1574. # The search text changed. Find new matching nodes.
  1575. prev_s = s
  1576. try:
  1577. # We could use re.IGNORECASE here instead of lower(), but this
  1578. # is noticeably less jerky while inputting regexes like
  1579. # '.*debug$' (though the '.*' is redundant there). Those
  1580. # probably have bad interactions with re.search(), which
  1581. # matches anywhere in the string.
  1582. #
  1583. # It's not horrible either way. Just a bit smoother.
  1584. regex_searches = [re.compile(regex).search
  1585. for regex in s.lower().split()]
  1586. # No exception thrown, so the regexes are okay
  1587. bad_re = None
  1588. # List of matching nodes
  1589. matches = []
  1590. add_match = matches.append
  1591. # Search symbols and choices
  1592. for node in _sorted_sc_nodes():
  1593. # Symbol/choice
  1594. sc = node.item
  1595. for search in regex_searches:
  1596. # Both the name and the prompt might be missing, since
  1597. # we're searching both symbols and choices
  1598. # Does the regex match either the symbol name or the
  1599. # prompt (if any)?
  1600. if not (sc.name and search(sc.name.lower()) or
  1601. node.prompt and search(node.prompt[0].lower())):
  1602. # Give up on the first regex that doesn't match, to
  1603. # speed things up a bit when multiple regexes are
  1604. # entered
  1605. break
  1606. else:
  1607. add_match(node)
  1608. # Search menus and comments
  1609. for node in _sorted_menu_comment_nodes():
  1610. for search in regex_searches:
  1611. if not search(node.prompt[0].lower()):
  1612. break
  1613. else:
  1614. add_match(node)
  1615. except re.error as e:
  1616. # Bad regex. Remember the error message so we can show it.
  1617. bad_re = "Bad regular expression"
  1618. # re.error.msg was added in Python 3.5
  1619. if hasattr(e, "msg"):
  1620. bad_re += ": " + e.msg
  1621. matches = []
  1622. # Reset scroll and jump to the top of the list of matches
  1623. sel_node_i = scroll = 0
  1624. _draw_jump_to_dialog(edit_box, matches_win, bot_sep_win, help_win,
  1625. s, s_i, hscroll,
  1626. bad_re, matches, sel_node_i, scroll)
  1627. curses.doupdate()
  1628. c = _getch_compat(edit_box)
  1629. if c == "\n":
  1630. if matches:
  1631. _jump_to(matches[sel_node_i])
  1632. _safe_curs_set(0)
  1633. return True
  1634. elif c == "\x1B": # \x1B = ESC
  1635. _safe_curs_set(0)
  1636. return False
  1637. elif c == curses.KEY_RESIZE:
  1638. # We adjust the scroll so that the selected node stays visible in
  1639. # the list when the terminal is resized, hence the 'scroll'
  1640. # assignment
  1641. scroll = _resize_jump_to_dialog(
  1642. edit_box, matches_win, bot_sep_win, help_win,
  1643. sel_node_i, scroll)
  1644. elif c == "\x06": # \x06 = Ctrl-F
  1645. if matches:
  1646. _safe_curs_set(0)
  1647. _info_dialog(matches[sel_node_i], True)
  1648. _safe_curs_set(2)
  1649. scroll = _resize_jump_to_dialog(
  1650. edit_box, matches_win, bot_sep_win, help_win,
  1651. sel_node_i, scroll)
  1652. elif c == curses.KEY_DOWN:
  1653. sel_node_i, scroll = select_next_match()
  1654. elif c == curses.KEY_UP:
  1655. sel_node_i, scroll = select_prev_match()
  1656. elif c in (curses.KEY_NPAGE, "\x04"): # Page Down/Ctrl-D
  1657. # Keep it simple. This way we get sane behavior for small windows,
  1658. # etc., for free.
  1659. for _ in range(_PG_JUMP):
  1660. sel_node_i, scroll = select_next_match()
  1661. # Page Up (no Ctrl-U, as it's already used by the edit box)
  1662. elif c == curses.KEY_PPAGE:
  1663. for _ in range(_PG_JUMP):
  1664. sel_node_i, scroll = select_prev_match()
  1665. elif c == curses.KEY_END:
  1666. sel_node_i = len(matches) - 1
  1667. scroll = _max_scroll(matches, matches_win)
  1668. elif c == curses.KEY_HOME:
  1669. sel_node_i = scroll = 0
  1670. else:
  1671. s, s_i, hscroll = _edit_text(c, s, s_i, hscroll,
  1672. _width(edit_box) - 2)
  1673. # Obscure Python: We never pass a value for cached_nodes, and it keeps pointing
  1674. # to the same list. This avoids a global.
  1675. def _sorted_sc_nodes(cached_nodes=[]):
  1676. # Returns a sorted list of symbol and choice nodes to search. The symbol
  1677. # nodes appear first, sorted by name, and then the choice nodes, sorted by
  1678. # prompt and (secondarily) name.
  1679. if not cached_nodes:
  1680. # Add symbol nodes
  1681. for sym in sorted(_kconf.unique_defined_syms,
  1682. key=lambda sym: sym.name):
  1683. # += is in-place for lists
  1684. cached_nodes += sym.nodes
  1685. # Add choice nodes
  1686. choices = sorted(_kconf.unique_choices,
  1687. key=lambda choice: choice.name or "")
  1688. cached_nodes += sorted(
  1689. [node for choice in choices for node in choice.nodes],
  1690. key=lambda node: node.prompt[0] if node.prompt else "")
  1691. return cached_nodes
  1692. def _sorted_menu_comment_nodes(cached_nodes=[]):
  1693. # Returns a list of menu and comment nodes to search, sorted by prompt,
  1694. # with the menus first
  1695. if not cached_nodes:
  1696. def prompt_text(mc):
  1697. return mc.prompt[0]
  1698. cached_nodes += sorted(_kconf.menus, key=prompt_text)
  1699. cached_nodes += sorted(_kconf.comments, key=prompt_text)
  1700. return cached_nodes
  1701. def _resize_jump_to_dialog(edit_box, matches_win, bot_sep_win, help_win,
  1702. sel_node_i, scroll):
  1703. # Resizes the jump-to dialog to fill the terminal.
  1704. #
  1705. # Returns the new scroll index. We adjust the scroll if needed so that the
  1706. # selected node stays visible.
  1707. screen_height, screen_width = _stdscr.getmaxyx()
  1708. bot_sep_win.resize(1, screen_width)
  1709. help_win_height = len(_JUMP_TO_HELP_LINES)
  1710. matches_win_height = screen_height - help_win_height - 4
  1711. if matches_win_height >= 1:
  1712. edit_box.resize(3, screen_width)
  1713. matches_win.resize(matches_win_height, screen_width)
  1714. help_win.resize(help_win_height, screen_width)
  1715. matches_win.mvwin(3, 0)
  1716. bot_sep_win.mvwin(3 + matches_win_height, 0)
  1717. help_win.mvwin(3 + matches_win_height + 1, 0)
  1718. else:
  1719. # Degenerate case. Give up on nice rendering and just prevent errors.
  1720. matches_win_height = 1
  1721. edit_box.resize(screen_height, screen_width)
  1722. matches_win.resize(1, screen_width)
  1723. help_win.resize(1, screen_width)
  1724. for win in matches_win, bot_sep_win, help_win:
  1725. win.mvwin(0, 0)
  1726. # Adjust the scroll so that the selected row is still within the window, if
  1727. # needed
  1728. if sel_node_i - scroll >= matches_win_height:
  1729. return sel_node_i - matches_win_height + 1
  1730. return scroll
  1731. def _draw_jump_to_dialog(edit_box, matches_win, bot_sep_win, help_win,
  1732. s, s_i, hscroll,
  1733. bad_re, matches, sel_node_i, scroll):
  1734. edit_width = _width(edit_box) - 2
  1735. #
  1736. # Update list of matches
  1737. #
  1738. matches_win.erase()
  1739. if matches:
  1740. for i in range(scroll,
  1741. min(scroll + _height(matches_win), len(matches))):
  1742. node = matches[i]
  1743. if isinstance(node.item, (Symbol, Choice)):
  1744. node_str = _name_and_val_str(node.item)
  1745. if node.prompt:
  1746. node_str += ' "{}"'.format(node.prompt[0])
  1747. elif node.item == MENU:
  1748. node_str = 'menu "{}"'.format(node.prompt[0])
  1749. else: # node.item == COMMENT
  1750. node_str = 'comment "{}"'.format(node.prompt[0])
  1751. _safe_addstr(matches_win, i - scroll, 0, node_str,
  1752. _style["selection" if i == sel_node_i else "list"])
  1753. else:
  1754. # bad_re holds the error message from the re.error exception on errors
  1755. _safe_addstr(matches_win, 0, 0, bad_re or "No matches")
  1756. matches_win.noutrefresh()
  1757. #
  1758. # Update bottom separator line
  1759. #
  1760. bot_sep_win.erase()
  1761. # Draw arrows pointing down if the symbol list is scrolled up
  1762. if scroll < _max_scroll(matches, matches_win):
  1763. _safe_hline(bot_sep_win, 0, 4, curses.ACS_DARROW, _N_SCROLL_ARROWS)
  1764. bot_sep_win.noutrefresh()
  1765. #
  1766. # Update help window at bottom
  1767. #
  1768. help_win.erase()
  1769. for i, line in enumerate(_JUMP_TO_HELP_LINES):
  1770. _safe_addstr(help_win, i, 0, line)
  1771. help_win.noutrefresh()
  1772. #
  1773. # Update edit box. We do this last since it makes it handy to position the
  1774. # cursor.
  1775. #
  1776. edit_box.erase()
  1777. _draw_frame(edit_box, "Jump to symbol/choice/menu/comment")
  1778. # Draw arrows pointing up if the symbol list is scrolled down
  1779. if scroll > 0:
  1780. # TODO: Bit ugly that _style["frame"] is repeated here
  1781. _safe_hline(edit_box, 2, 4, curses.ACS_UARROW, _N_SCROLL_ARROWS,
  1782. _style["frame"])
  1783. visible_s = s[hscroll:hscroll + edit_width]
  1784. _safe_addstr(edit_box, 1, 1, visible_s)
  1785. _safe_move(edit_box, 1, 1 + s_i - hscroll)
  1786. edit_box.noutrefresh()
  1787. def _info_dialog(node, from_jump_to_dialog):
  1788. # Shows a fullscreen window with information about 'node'.
  1789. #
  1790. # If 'from_jump_to_dialog' is True, the information dialog was opened from
  1791. # within the jump-to-dialog. In this case, we make '/' from within the
  1792. # information dialog just return, to avoid a confusing recursive invocation
  1793. # of the jump-to-dialog.
  1794. # Top row, with title and arrows point up
  1795. top_line_win = _styled_win("separator")
  1796. # Text display
  1797. text_win = _styled_win("text")
  1798. text_win.keypad(True)
  1799. # Bottom separator, with arrows pointing down
  1800. bot_sep_win = _styled_win("separator")
  1801. # Help window with keys at the bottom
  1802. help_win = _styled_win("help")
  1803. # Give windows their initial size
  1804. _resize_info_dialog(top_line_win, text_win, bot_sep_win, help_win)
  1805. # Get lines of help text
  1806. lines = _info_str(node).split("\n")
  1807. # Index of first row in 'lines' to show
  1808. scroll = 0
  1809. while True:
  1810. _draw_info_dialog(node, lines, scroll, top_line_win, text_win,
  1811. bot_sep_win, help_win)
  1812. curses.doupdate()
  1813. c = _getch_compat(text_win)
  1814. if c == curses.KEY_RESIZE:
  1815. _resize_info_dialog(top_line_win, text_win, bot_sep_win, help_win)
  1816. elif c in (curses.KEY_DOWN, "j", "J"):
  1817. if scroll < _max_scroll(lines, text_win):
  1818. scroll += 1
  1819. elif c in (curses.KEY_NPAGE, "\x04"): # Page Down/Ctrl-D
  1820. scroll = min(scroll + _PG_JUMP, _max_scroll(lines, text_win))
  1821. elif c in (curses.KEY_PPAGE, "\x15"): # Page Up/Ctrl-U
  1822. scroll = max(scroll - _PG_JUMP, 0)
  1823. elif c in (curses.KEY_END, "G"):
  1824. scroll = _max_scroll(lines, text_win)
  1825. elif c in (curses.KEY_HOME, "g"):
  1826. scroll = 0
  1827. elif c in (curses.KEY_UP, "k", "K"):
  1828. if scroll > 0:
  1829. scroll -= 1
  1830. elif c == "/":
  1831. # Support starting a search from within the information dialog
  1832. if from_jump_to_dialog:
  1833. return # Avoid recursion
  1834. if _jump_to_dialog():
  1835. return # Jumped to a symbol. Cancel the information dialog.
  1836. # Stay in the information dialog if the jump-to dialog was
  1837. # canceled. Resize it in case the terminal was resized while the
  1838. # fullscreen jump-to dialog was open.
  1839. _resize_info_dialog(top_line_win, text_win, bot_sep_win, help_win)
  1840. elif c in (curses.KEY_LEFT, curses.KEY_BACKSPACE, _ERASE_CHAR,
  1841. "\x1B", # \x1B = ESC
  1842. "q", "Q", "h", "H"):
  1843. return
  1844. def _resize_info_dialog(top_line_win, text_win, bot_sep_win, help_win):
  1845. # Resizes the info dialog to fill the terminal
  1846. screen_height, screen_width = _stdscr.getmaxyx()
  1847. top_line_win.resize(1, screen_width)
  1848. bot_sep_win.resize(1, screen_width)
  1849. help_win_height = len(_INFO_HELP_LINES)
  1850. text_win_height = screen_height - help_win_height - 2
  1851. if text_win_height >= 1:
  1852. text_win.resize(text_win_height, screen_width)
  1853. help_win.resize(help_win_height, screen_width)
  1854. text_win.mvwin(1, 0)
  1855. bot_sep_win.mvwin(1 + text_win_height, 0)
  1856. help_win.mvwin(1 + text_win_height + 1, 0)
  1857. else:
  1858. # Degenerate case. Give up on nice rendering and just prevent errors.
  1859. text_win.resize(1, screen_width)
  1860. help_win.resize(1, screen_width)
  1861. for win in text_win, bot_sep_win, help_win:
  1862. win.mvwin(0, 0)
  1863. def _draw_info_dialog(node, lines, scroll, top_line_win, text_win,
  1864. bot_sep_win, help_win):
  1865. text_win_height, text_win_width = text_win.getmaxyx()
  1866. # Note: The top row is deliberately updated last. See _draw_main().
  1867. #
  1868. # Update text display
  1869. #
  1870. text_win.erase()
  1871. for i, line in enumerate(lines[scroll:scroll + text_win_height]):
  1872. _safe_addstr(text_win, i, 0, line)
  1873. text_win.noutrefresh()
  1874. #
  1875. # Update bottom separator line
  1876. #
  1877. bot_sep_win.erase()
  1878. # Draw arrows pointing down if the symbol window is scrolled up
  1879. if scroll < _max_scroll(lines, text_win):
  1880. _safe_hline(bot_sep_win, 0, 4, curses.ACS_DARROW, _N_SCROLL_ARROWS)
  1881. bot_sep_win.noutrefresh()
  1882. #
  1883. # Update help window at bottom
  1884. #
  1885. help_win.erase()
  1886. for i, line in enumerate(_INFO_HELP_LINES):
  1887. _safe_addstr(help_win, i, 0, line)
  1888. help_win.noutrefresh()
  1889. #
  1890. # Update top row
  1891. #
  1892. top_line_win.erase()
  1893. # Draw arrows pointing up if the information window is scrolled down. Draw
  1894. # them before drawing the title, so the title ends up on top for small
  1895. # windows.
  1896. if scroll > 0:
  1897. _safe_hline(top_line_win, 0, 4, curses.ACS_UARROW, _N_SCROLL_ARROWS)
  1898. title = ("Symbol" if isinstance(node.item, Symbol) else
  1899. "Choice" if isinstance(node.item, Choice) else
  1900. "Menu" if node.item == MENU else
  1901. "Comment") + " information"
  1902. _safe_addstr(top_line_win, 0, max((text_win_width - len(title))//2, 0),
  1903. title)
  1904. top_line_win.noutrefresh()
  1905. def _info_str(node):
  1906. # Returns information about the menu node 'node' as a string.
  1907. #
  1908. # The helper functions are responsible for adding newlines. This allows
  1909. # them to return "" if they don't want to add any output.
  1910. if isinstance(node.item, Symbol):
  1911. sym = node.item
  1912. return (
  1913. _name_info(sym) +
  1914. _prompt_info(sym) +
  1915. "Type: {}\n".format(TYPE_TO_STR[sym.type]) +
  1916. _value_info(sym) +
  1917. _help_info(sym) +
  1918. _direct_dep_info(sym) +
  1919. _defaults_info(sym) +
  1920. _select_imply_info(sym) +
  1921. _kconfig_def_info(sym)
  1922. )
  1923. if isinstance(node.item, Choice):
  1924. choice = node.item
  1925. return (
  1926. _name_info(choice) +
  1927. _prompt_info(choice) +
  1928. "Type: {}\n".format(TYPE_TO_STR[choice.type]) +
  1929. 'Mode: {}\n'.format(choice.str_value) +
  1930. _help_info(choice) +
  1931. _choice_syms_info(choice) +
  1932. _direct_dep_info(choice) +
  1933. _defaults_info(choice) +
  1934. _kconfig_def_info(choice)
  1935. )
  1936. return _kconfig_def_info(node) # node.item in (MENU, COMMENT)
  1937. def _name_info(sc):
  1938. # Returns a string with the name of the symbol/choice. Names are optional
  1939. # for choices.
  1940. return "Name: {}\n".format(sc.name) if sc.name else ""
  1941. def _prompt_info(sc):
  1942. # Returns a string listing the prompts of 'sc' (Symbol or Choice)
  1943. s = ""
  1944. for node in sc.nodes:
  1945. if node.prompt:
  1946. s += "Prompt: {}\n".format(node.prompt[0])
  1947. return s
  1948. def _value_info(sym):
  1949. # Returns a string showing 'sym's value
  1950. # Only put quotes around the value for string symbols
  1951. return "Value: {}\n".format(
  1952. '"{}"'.format(sym.str_value)
  1953. if sym.orig_type == STRING
  1954. else sym.str_value)
  1955. def _choice_syms_info(choice):
  1956. # Returns a string listing the choice symbols in 'choice'. Adds
  1957. # "(selected)" next to the selected one.
  1958. s = "Choice symbols:\n"
  1959. for sym in choice.syms:
  1960. s += " - " + sym.name
  1961. if sym is choice.selection:
  1962. s += " (selected)"
  1963. s += "\n"
  1964. return s + "\n"
  1965. def _help_info(sc):
  1966. # Returns a string with the help text(s) of 'sc' (Symbol or Choice).
  1967. # Symbols and choices defined in multiple locations can have multiple help
  1968. # texts.
  1969. s = "\n"
  1970. for node in sc.nodes:
  1971. if node.help is not None:
  1972. s += "Help:\n\n{}\n\n".format(_indent(node.help, 2))
  1973. return s
  1974. def _direct_dep_info(sc):
  1975. # Returns a string describing the direct dependencies of 'sc' (Symbol or
  1976. # Choice). The direct dependencies are the OR of the dependencies from each
  1977. # definition location. The dependencies at each definition location come
  1978. # from 'depends on' and dependencies inherited from parent items.
  1979. return "" if sc.direct_dep is _kconf.y else \
  1980. 'Direct dependencies (={}):\n{}\n' \
  1981. .format(TRI_TO_STR[expr_value(sc.direct_dep)],
  1982. _split_expr_info(sc.direct_dep, 2))
  1983. def _defaults_info(sc):
  1984. # Returns a string describing the defaults of 'sc' (Symbol or Choice)
  1985. if not sc.defaults:
  1986. return ""
  1987. s = "Default"
  1988. if len(sc.defaults) > 1:
  1989. s += "s"
  1990. s += ":\n"
  1991. for val, cond in sc.orig_defaults:
  1992. s += " - "
  1993. if isinstance(sc, Symbol):
  1994. s += _expr_str(val)
  1995. # Skip the tristate value hint if the expression is just a single
  1996. # symbol. _expr_str() already shows its value as a string.
  1997. #
  1998. # This also avoids showing the tristate value for string/int/hex
  1999. # defaults, which wouldn't make any sense.
  2000. if isinstance(val, tuple):
  2001. s += ' (={})'.format(TRI_TO_STR[expr_value(val)])
  2002. else:
  2003. # Don't print the value next to the symbol name for choice
  2004. # defaults, as it looks a bit confusing
  2005. s += val.name
  2006. s += "\n"
  2007. if cond is not _kconf.y:
  2008. s += " Condition (={}):\n{}" \
  2009. .format(TRI_TO_STR[expr_value(cond)],
  2010. _split_expr_info(cond, 4))
  2011. return s + "\n"
  2012. def _split_expr_info(expr, indent):
  2013. # Returns a string with 'expr' split into its top-level && or || operands,
  2014. # with one operand per line, together with the operand's value. This is
  2015. # usually enough to get something readable for long expressions. A fancier
  2016. # recursive thingy would be possible too.
  2017. #
  2018. # indent:
  2019. # Number of leading spaces to add before the split expression.
  2020. if len(split_expr(expr, AND)) > 1:
  2021. split_op = AND
  2022. op_str = "&&"
  2023. else:
  2024. split_op = OR
  2025. op_str = "||"
  2026. s = ""
  2027. for i, term in enumerate(split_expr(expr, split_op)):
  2028. s += "{}{} {}".format(indent*" ",
  2029. " " if i == 0 else op_str,
  2030. _expr_str(term))
  2031. # Don't bother showing the value hint if the expression is just a
  2032. # single symbol. _expr_str() already shows its value.
  2033. if isinstance(term, tuple):
  2034. s += " (={})".format(TRI_TO_STR[expr_value(term)])
  2035. s += "\n"
  2036. return s
  2037. def _select_imply_info(sym):
  2038. # Returns a string with information about which symbols 'select' or 'imply'
  2039. # 'sym'. The selecting/implying symbols are grouped according to which
  2040. # value they select/imply 'sym' to (n/m/y).
  2041. def sis(expr, val, title):
  2042. # sis = selects/implies
  2043. sis = [si for si in split_expr(expr, OR) if expr_value(si) == val]
  2044. if not sis:
  2045. return ""
  2046. res = title
  2047. for si in sis:
  2048. res += " - {}\n".format(split_expr(si, AND)[0].name)
  2049. return res + "\n"
  2050. s = ""
  2051. if sym.rev_dep is not _kconf.n:
  2052. s += sis(sym.rev_dep, 2,
  2053. "Symbols currently y-selecting this symbol:\n")
  2054. s += sis(sym.rev_dep, 1,
  2055. "Symbols currently m-selecting this symbol:\n")
  2056. s += sis(sym.rev_dep, 0,
  2057. "Symbols currently n-selecting this symbol (no effect):\n")
  2058. if sym.weak_rev_dep is not _kconf.n:
  2059. s += sis(sym.weak_rev_dep, 2,
  2060. "Symbols currently y-implying this symbol:\n")
  2061. s += sis(sym.weak_rev_dep, 1,
  2062. "Symbols currently m-implying this symbol:\n")
  2063. s += sis(sym.weak_rev_dep, 0,
  2064. "Symbols currently n-implying this symbol (no effect):\n")
  2065. return s
  2066. def _kconfig_def_info(item):
  2067. # Returns a string with the definition of 'item' in Kconfig syntax,
  2068. # together with the definition location(s) and their include and menu paths
  2069. nodes = [item] if isinstance(item, MenuNode) else item.nodes
  2070. s = "Kconfig definition{}, with parent deps. propagated to 'depends on'\n" \
  2071. .format("s" if len(nodes) > 1 else "")
  2072. s += (len(s) - 1)*"="
  2073. for node in nodes:
  2074. s += "\n\n" \
  2075. "At {}:{}\n" \
  2076. "{}" \
  2077. "Menu path: {}\n\n" \
  2078. "{}" \
  2079. .format(node.filename, node.linenr,
  2080. _include_path_info(node),
  2081. _menu_path_info(node),
  2082. _indent(node.custom_str(_name_and_val_str), 2))
  2083. return s
  2084. def _include_path_info(node):
  2085. if not node.include_path:
  2086. # In the top-level Kconfig file
  2087. return ""
  2088. return "Included via {}\n".format(
  2089. " -> ".join("{}:{}".format(filename, linenr)
  2090. for filename, linenr in node.include_path))
  2091. def _menu_path_info(node):
  2092. # Returns a string describing the menu path leading up to 'node'
  2093. path = ""
  2094. while node.parent is not _kconf.top_node:
  2095. node = node.parent
  2096. # Promptless choices might appear among the parents. Use
  2097. # standard_sc_expr_str() for them, so that they show up as
  2098. # '<choice (name if any)>'.
  2099. path = " -> " + (node.prompt[0] if node.prompt else
  2100. standard_sc_expr_str(node.item)) + path
  2101. return "(Top)" + path
  2102. def _indent(s, n):
  2103. # Returns 's' with each line indented 'n' spaces. textwrap.indent() is not
  2104. # available in Python 2 (it's 3.3+).
  2105. return "\n".join(n*" " + line for line in s.split("\n"))
  2106. def _name_and_val_str(sc):
  2107. # Custom symbol/choice printer that shows symbol values after symbols
  2108. # Show the values of non-constant (non-quoted) symbols that don't look like
  2109. # numbers. Things like 123 are actually symbol references, and only work as
  2110. # expected due to undefined symbols getting their name as their value.
  2111. # Showing the symbol value for those isn't helpful though.
  2112. if isinstance(sc, Symbol) and not sc.is_constant and not _is_num(sc.name):
  2113. if not sc.nodes:
  2114. # Undefined symbol reference
  2115. return "{}(undefined/n)".format(sc.name)
  2116. return '{}(={})'.format(sc.name, sc.str_value)
  2117. # For other items, use the standard format
  2118. return standard_sc_expr_str(sc)
  2119. def _expr_str(expr):
  2120. # Custom expression printer that shows symbol values
  2121. return expr_str(expr, _name_and_val_str)
  2122. def _styled_win(style):
  2123. # Returns a new curses window with style 'style' and space as the fill
  2124. # character. The initial dimensions are (1, 1), so the window needs to be
  2125. # sized and positioned separately.
  2126. win = curses.newwin(1, 1)
  2127. _set_style(win, style)
  2128. return win
  2129. def _set_style(win, style):
  2130. # Changes the style of an existing window
  2131. win.bkgdset(" ", _style[style])
  2132. def _max_scroll(lst, win):
  2133. # Assuming 'lst' is a list of items to be displayed in 'win',
  2134. # returns the maximum number of steps 'win' can be scrolled down.
  2135. # We stop scrolling when the bottom item is visible.
  2136. return max(0, len(lst) - _height(win))
  2137. def _edit_text(c, s, i, hscroll, width):
  2138. # Implements text editing commands for edit boxes. Takes a character (which
  2139. # could also be e.g. curses.KEY_LEFT) and the edit box state, and returns
  2140. # the new state after the character has been processed.
  2141. #
  2142. # c:
  2143. # Character from user
  2144. #
  2145. # s:
  2146. # Current contents of string
  2147. #
  2148. # i:
  2149. # Current cursor index in string
  2150. #
  2151. # hscroll:
  2152. # Index in s of the leftmost character in the edit box, for horizontal
  2153. # scrolling
  2154. #
  2155. # width:
  2156. # Width in characters of the edit box
  2157. #
  2158. # Return value:
  2159. # An (s, i, hscroll) tuple for the new state
  2160. if c == curses.KEY_LEFT:
  2161. if i > 0:
  2162. i -= 1
  2163. elif c == curses.KEY_RIGHT:
  2164. if i < len(s):
  2165. i += 1
  2166. elif c in (curses.KEY_HOME, "\x01"): # \x01 = CTRL-A
  2167. i = 0
  2168. elif c in (curses.KEY_END, "\x05"): # \x05 = CTRL-E
  2169. i = len(s)
  2170. elif c in (curses.KEY_BACKSPACE, _ERASE_CHAR):
  2171. if i > 0:
  2172. s = s[:i-1] + s[i:]
  2173. i -= 1
  2174. elif c == curses.KEY_DC:
  2175. s = s[:i] + s[i+1:]
  2176. elif c == "\x17": # \x17 = CTRL-W
  2177. # The \W removes characters like ',' one at a time
  2178. new_i = re.search(r"(?:\w*|\W)\s*$", s[:i]).start()
  2179. s = s[:new_i] + s[i:]
  2180. i = new_i
  2181. elif c == "\x0B": # \x0B = CTRL-K
  2182. s = s[:i]
  2183. elif c == "\x15": # \x15 = CTRL-U
  2184. s = s[i:]
  2185. i = 0
  2186. elif isinstance(c, str):
  2187. # Insert character
  2188. s = s[:i] + c + s[i:]
  2189. i += 1
  2190. # Adjust the horizontal scroll so that the cursor never touches the left or
  2191. # right edges of the edit box, except when it's at the beginning or the end
  2192. # of the string
  2193. if i < hscroll + _SCROLL_OFFSET:
  2194. hscroll = max(i - _SCROLL_OFFSET, 0)
  2195. elif i >= hscroll + width - _SCROLL_OFFSET:
  2196. max_scroll = max(len(s) - width + 1, 0)
  2197. hscroll = min(i - width + _SCROLL_OFFSET + 1, max_scroll)
  2198. return s, i, hscroll
  2199. def _load_save_info():
  2200. # Returns an information string for load/save dialog boxes
  2201. return "(Relative to {})\n\nRefer to your home directory with ~" \
  2202. .format(os.path.join(os.getcwd(), ""))
  2203. def _msg(title, text):
  2204. # Pops up a message dialog that can be dismissed with Space/Enter/ESC
  2205. _key_dialog(title, text, " \n")
  2206. def _error(text):
  2207. # Pops up an error dialog that can be dismissed with Space/Enter/ESC
  2208. _msg("Error", text)
  2209. def _node_str(node):
  2210. # Returns the complete menu entry text for a menu node.
  2211. #
  2212. # Example return value: "[*] Support for X"
  2213. # Calculate the indent to print the item with by checking how many levels
  2214. # above it the closest 'menuconfig' item is (this includes menus and
  2215. # choices as well as menuconfig symbols)
  2216. indent = 0
  2217. parent = node.parent
  2218. while not parent.is_menuconfig:
  2219. indent += _SUBMENU_INDENT
  2220. parent = parent.parent
  2221. # This approach gives nice alignment for empty string symbols ("() Foo")
  2222. s = "{:{}}".format(_value_str(node), 3 + indent)
  2223. if _should_show_name(node):
  2224. if isinstance(node.item, Symbol):
  2225. s += " <{}>".format(node.item.name)
  2226. else:
  2227. # For choices, use standard_sc_expr_str(). That way they show up as
  2228. # '<choice (name if any)>'.
  2229. s += " " + standard_sc_expr_str(node.item)
  2230. if node.prompt:
  2231. if node.item == COMMENT:
  2232. s += " *** {} ***".format(node.prompt[0])
  2233. else:
  2234. s += " " + node.prompt[0]
  2235. if isinstance(node.item, Symbol):
  2236. sym = node.item
  2237. # Print "(NEW)" next to symbols without a user value (from e.g. a
  2238. # .config), but skip it for choice symbols in choices in y mode,
  2239. # and for symbols of UNKNOWN type (which generate a warning though)
  2240. if sym.user_value is None and sym.orig_type and \
  2241. not (sym.choice and sym.choice.tri_value == 2):
  2242. s += " (NEW)"
  2243. if isinstance(node.item, Choice) and node.item.tri_value == 2:
  2244. # Print the prompt of the selected symbol after the choice for
  2245. # choices in y mode
  2246. sym = node.item.selection
  2247. if sym:
  2248. for sym_node in sym.nodes:
  2249. # Use the prompt used at this choice location, in case the
  2250. # choice symbol is defined in multiple locations
  2251. if sym_node.parent is node and sym_node.prompt:
  2252. s += " ({})".format(sym_node.prompt[0])
  2253. break
  2254. else:
  2255. # If the symbol isn't defined at this choice location, then
  2256. # just use whatever prompt we can find for it
  2257. for sym_node in sym.nodes:
  2258. if sym_node.prompt:
  2259. s += " ({})".format(sym_node.prompt[0])
  2260. break
  2261. # Print "--->" next to nodes that have menus that can potentially be
  2262. # entered. Print "----" if the menu is empty. We don't allow those to be
  2263. # entered.
  2264. if node.is_menuconfig:
  2265. s += " --->" if _shown_nodes(node) else " ----"
  2266. return s
  2267. def _should_show_name(node):
  2268. # Returns True if 'node' is a symbol or choice whose name should shown (if
  2269. # any, as names are optional for choices)
  2270. # The 'not node.prompt' case only hits in show-all mode, for promptless
  2271. # symbols and choices
  2272. return not node.prompt or \
  2273. (_show_name and isinstance(node.item, (Symbol, Choice)))
  2274. def _value_str(node):
  2275. # Returns the value part ("[*]", "<M>", "(foo)" etc.) of a menu node
  2276. item = node.item
  2277. if item in (MENU, COMMENT):
  2278. return ""
  2279. # Wouldn't normally happen, and generates a warning
  2280. if not item.orig_type:
  2281. return ""
  2282. if item.orig_type in (STRING, INT, HEX):
  2283. return "({})".format(item.str_value)
  2284. # BOOL or TRISTATE
  2285. if _is_y_mode_choice_sym(item):
  2286. return "(X)" if item.choice.selection is item else "( )"
  2287. tri_val_str = (" ", "M", "*")[item.tri_value]
  2288. if len(item.assignable) <= 1:
  2289. # Pinned to a single value
  2290. return "" if isinstance(item, Choice) else "-{}-".format(tri_val_str)
  2291. if item.type == BOOL:
  2292. return "[{}]".format(tri_val_str)
  2293. # item.type == TRISTATE
  2294. if item.assignable == (1, 2):
  2295. return "{{{}}}".format(tri_val_str) # {M}/{*}
  2296. return "<{}>".format(tri_val_str)
  2297. def _is_y_mode_choice_sym(item):
  2298. # The choice mode is an upper bound on the visibility of choice symbols, so
  2299. # we can check the choice symbols' own visibility to see if the choice is
  2300. # in y mode
  2301. return isinstance(item, Symbol) and item.choice and item.visibility == 2
  2302. def _check_valid(sym, s):
  2303. # Returns True if the string 's' is a well-formed value for 'sym'.
  2304. # Otherwise, displays an error and returns False.
  2305. if sym.orig_type not in (INT, HEX):
  2306. return True # Anything goes for non-int/hex symbols
  2307. base = 10 if sym.orig_type == INT else 16
  2308. try:
  2309. int(s, base)
  2310. except ValueError:
  2311. _error("'{}' is a malformed {} value"
  2312. .format(s, TYPE_TO_STR[sym.orig_type]))
  2313. return False
  2314. for low_sym, high_sym, cond in sym.ranges:
  2315. if expr_value(cond):
  2316. low_s = low_sym.str_value
  2317. high_s = high_sym.str_value
  2318. if not int(low_s, base) <= int(s, base) <= int(high_s, base):
  2319. _error("{} is outside the range {}-{}"
  2320. .format(s, low_s, high_s))
  2321. return False
  2322. break
  2323. return True
  2324. def _range_info(sym):
  2325. # Returns a string with information about the valid range for the symbol
  2326. # 'sym', or None if 'sym' doesn't have a range
  2327. if sym.orig_type in (INT, HEX):
  2328. for low, high, cond in sym.ranges:
  2329. if expr_value(cond):
  2330. return "Range: {}-{}".format(low.str_value, high.str_value)
  2331. return None
  2332. def _is_num(name):
  2333. # Heuristic to see if a symbol name looks like a number, for nicer output
  2334. # when printing expressions. Things like 16 are actually symbol names, only
  2335. # they get their name as their value when the symbol is undefined.
  2336. try:
  2337. int(name)
  2338. except ValueError:
  2339. if not name.startswith(("0x", "0X")):
  2340. return False
  2341. try:
  2342. int(name, 16)
  2343. except ValueError:
  2344. return False
  2345. return True
  2346. def _getch_compat(win):
  2347. # Uses get_wch() if available (Python 3.3+) and getch() otherwise.
  2348. #
  2349. # Also falls back on getch() if get_wch() raises curses.error, to work
  2350. # around an issue when resizing the terminal on at least macOS Catalina.
  2351. # See https://github.com/ulfalizer/Kconfiglib/issues/84.
  2352. #
  2353. # Also handles a PDCurses resizing quirk.
  2354. try:
  2355. c = win.get_wch()
  2356. except (AttributeError, curses.error):
  2357. c = win.getch()
  2358. if 0 <= c <= 255:
  2359. c = chr(c)
  2360. # Decent resizing behavior on PDCurses requires calling resize_term(0, 0)
  2361. # after receiving KEY_RESIZE, while ncurses (usually) handles terminal
  2362. # resizing automatically in get(_w)ch() (see the end of the
  2363. # resizeterm(3NCURSES) man page).
  2364. #
  2365. # resize_term(0, 0) reliably fails and does nothing on ncurses, so this
  2366. # hack gives ncurses/PDCurses compatibility for resizing. I don't know
  2367. # whether it would cause trouble for other implementations.
  2368. if c == curses.KEY_RESIZE:
  2369. try:
  2370. curses.resize_term(0, 0)
  2371. except curses.error:
  2372. pass
  2373. return c
  2374. def _warn(*args):
  2375. # Temporarily returns from curses to shell mode and prints a warning to
  2376. # stderr. The warning would get lost in curses mode.
  2377. curses.endwin()
  2378. print("menuconfig warning: ", end="", file=sys.stderr)
  2379. print(*args, file=sys.stderr)
  2380. curses.doupdate()
  2381. # Ignore exceptions from some functions that might fail, e.g. for small
  2382. # windows. They usually do reasonable things anyway.
  2383. def _safe_curs_set(visibility):
  2384. try:
  2385. curses.curs_set(visibility)
  2386. except curses.error:
  2387. pass
  2388. def _safe_addstr(win, *args):
  2389. # Clip the line to avoid wrapping to the next line, which looks glitchy.
  2390. # addchstr() would do it for us, but it's not available in the 'curses'
  2391. # module.
  2392. attr = None
  2393. if isinstance(args[0], str):
  2394. y, x = win.getyx()
  2395. s = args[0]
  2396. if len(args) == 2:
  2397. attr = args[1]
  2398. else:
  2399. y, x, s = args[:3]
  2400. if len(args) == 4:
  2401. attr = args[3]
  2402. maxlen = _width(win) - x
  2403. s = s.expandtabs()
  2404. try:
  2405. # The 'curses' module uses wattr_set() internally if you pass 'attr',
  2406. # overwriting the background style, so setting 'attr' to 0 in the first
  2407. # case won't do the right thing
  2408. if attr is None:
  2409. win.addnstr(y, x, s, maxlen)
  2410. else:
  2411. win.addnstr(y, x, s, maxlen, attr)
  2412. except curses.error:
  2413. pass
  2414. def _safe_addch(win, *args):
  2415. try:
  2416. win.addch(*args)
  2417. except curses.error:
  2418. pass
  2419. def _safe_hline(win, *args):
  2420. try:
  2421. win.hline(*args)
  2422. except curses.error:
  2423. pass
  2424. def _safe_vline(win, *args):
  2425. try:
  2426. win.vline(*args)
  2427. except curses.error:
  2428. pass
  2429. def _safe_move(win, *args):
  2430. try:
  2431. win.move(*args)
  2432. except curses.error:
  2433. pass
  2434. def _change_c_lc_ctype_to_utf8():
  2435. # See _CHANGE_C_LC_CTYPE_TO_UTF8
  2436. if _IS_WINDOWS:
  2437. # Windows rarely has issues here, and the PEP 538 implementation avoids
  2438. # changing the locale on it. None of the UTF-8 locales below were
  2439. # supported from some quick testing either. Play it safe.
  2440. return
  2441. def try_set_locale(loc):
  2442. try:
  2443. locale.setlocale(locale.LC_CTYPE, loc)
  2444. return True
  2445. except locale.Error:
  2446. return False
  2447. # Is LC_CTYPE set to the C locale?
  2448. if locale.setlocale(locale.LC_CTYPE) == "C":
  2449. # This list was taken from the PEP 538 implementation in the CPython
  2450. # code, in Python/pylifecycle.c
  2451. for loc in "C.UTF-8", "C.utf8", "UTF-8":
  2452. if try_set_locale(loc):
  2453. # LC_CTYPE successfully changed
  2454. return
  2455. if __name__ == "__main__":
  2456. _main()