menuconfig.py 100 KB

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