menuconfig.py 102 KB

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