guiconfig.py 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2019, Ulf Magnusson
  3. # SPDX-License-Identifier: ISC
  4. """
  5. Overview
  6. ========
  7. A Tkinter-based menuconfig implementation, based around a treeview control and
  8. a help display. The interface should feel familiar to people used to qconf
  9. ('make xconfig'). Compatible with both Python 2 and Python 3.
  10. The display can be toggled between showing the full tree and showing just a
  11. single menu (like menuconfig.py). Only single-menu mode distinguishes between
  12. symbols defined with 'config' and symbols defined with 'menuconfig'.
  13. A show-all mode is available that shows invisible items in red.
  14. Supports both mouse and keyboard controls. The following keyboard shortcuts are
  15. available:
  16. Ctrl-S : Save configuration
  17. Ctrl-O : Open configuration
  18. Ctrl-A : Toggle show-all mode
  19. Ctrl-N : Toggle show-name mode
  20. Ctrl-M : Toggle single-menu mode
  21. Ctrl-F, /: Open jump-to dialog
  22. ESC : Close
  23. Running
  24. =======
  25. guiconfig.py can be run either as a standalone executable or by calling the
  26. menuconfig() function with an existing Kconfig instance. The second option is a
  27. bit inflexible in that it will still load and save .config, etc.
  28. When run in standalone mode, the top-level Kconfig file to load can be passed
  29. as a command-line argument. With no argument, it defaults to "Kconfig".
  30. The KCONFIG_CONFIG environment variable specifies the .config file to load (if
  31. it exists) and save. If KCONFIG_CONFIG is unset, ".config" is used.
  32. When overwriting a configuration file, the old version is saved to
  33. <filename>.old (e.g. .config.old).
  34. $srctree is supported through Kconfiglib.
  35. """
  36. # Note: There's some code duplication with menuconfig.py below, especially for
  37. # the help text. Maybe some of it could be moved into kconfiglib.py or a shared
  38. # helper script, but OTOH it's pretty nice to have things standalone and
  39. # customizable.
  40. import errno
  41. import os
  42. import sys
  43. _PY2 = sys.version_info[0] < 3
  44. if _PY2:
  45. # Python 2
  46. from Tkinter import *
  47. import ttk
  48. import tkFont as font
  49. import tkFileDialog as filedialog
  50. import tkMessageBox as messagebox
  51. else:
  52. # Python 3
  53. from tkinter import *
  54. import tkinter.ttk as ttk
  55. import tkinter.font as font
  56. from tkinter import filedialog, messagebox
  57. from kconfiglib import Symbol, Choice, MENU, COMMENT, MenuNode, \
  58. BOOL, TRISTATE, STRING, INT, HEX, \
  59. AND, OR, \
  60. expr_str, expr_value, split_expr, \
  61. standard_sc_expr_str, \
  62. TRI_TO_STR, TYPE_TO_STR, \
  63. standard_kconfig, standard_config_filename
  64. # If True, use GIF image data embedded in this file instead of separate GIF
  65. # files. See _load_images().
  66. _USE_EMBEDDED_IMAGES = True
  67. # Help text for the jump-to dialog
  68. _JUMP_TO_HELP = """\
  69. Type one or more strings/regexes and press Enter to list items that match all
  70. of them. Python's regex flavor is used (see the 're' module). Double-clicking
  71. an item will jump to it. Item values can be toggled directly within the dialog.\
  72. """
  73. def _main():
  74. menuconfig(standard_kconfig(__doc__))
  75. # Global variables used below:
  76. #
  77. # _root:
  78. # The Toplevel instance for the main window
  79. #
  80. # _tree:
  81. # The Treeview in the main window
  82. #
  83. # _jump_to_tree:
  84. # The Treeview in the jump-to dialog. None if the jump-to dialog isn't
  85. # open. Doubles as a flag.
  86. #
  87. # _jump_to_matches:
  88. # List of Nodes shown in the jump-to dialog
  89. #
  90. # _menupath:
  91. # The Label that shows the menu path of the selected item
  92. #
  93. # _backbutton:
  94. # The button shown in single-menu mode for jumping to the parent menu
  95. #
  96. # _status_label:
  97. # Label with status text shown at the bottom of the main window
  98. # ("Modified", "Saved to ...", etc.)
  99. #
  100. # _id_to_node:
  101. # We can't use Node objects directly as Treeview item IDs, so we use their
  102. # id()s instead. This dictionary maps Node id()s back to Nodes. (The keys
  103. # are actually str(id(node)), just to simplify lookups.)
  104. #
  105. # _cur_menu:
  106. # The current menu. Ignored outside single-menu mode.
  107. #
  108. # _show_all_var/_show_name_var/_single_menu_var:
  109. # Tkinter Variable instances bound to the corresponding checkboxes
  110. #
  111. # _show_all/_single_menu:
  112. # Plain Python bools that track _show_all_var and _single_menu_var, to
  113. # speed up and simplify things a bit
  114. #
  115. # _conf_filename:
  116. # File to save the configuration to
  117. #
  118. # _minconf_filename:
  119. # File to save minimal configurations to
  120. #
  121. # _conf_changed:
  122. # True if the configuration has been changed. If False, we don't bother
  123. # showing the save-and-quit dialog.
  124. #
  125. # We reset this to False whenever the configuration is saved.
  126. #
  127. # _*_img:
  128. # PhotoImage instances for images
  129. def menuconfig(kconf):
  130. """
  131. Launches the configuration interface, returning after the user exits.
  132. kconf:
  133. Kconfig instance to be configured
  134. """
  135. global _kconf
  136. global _conf_filename
  137. global _minconf_filename
  138. global _jump_to_tree
  139. global _cur_menu
  140. _kconf = kconf
  141. _jump_to_tree = None
  142. _create_id_to_node()
  143. _create_ui()
  144. # Filename to save configuration to
  145. _conf_filename = standard_config_filename()
  146. # Load existing configuration and check if it's outdated
  147. _set_conf_changed(_load_config())
  148. # Filename to save minimal configuration to
  149. _minconf_filename = "defconfig"
  150. # Current menu in single-menu mode
  151. _cur_menu = _kconf.top_node
  152. # Any visible items in the top menu?
  153. if not _shown_menu_nodes(kconf.top_node):
  154. # Nothing visible. Start in show-all mode and try again.
  155. _show_all_var.set(True)
  156. if not _shown_menu_nodes(kconf.top_node):
  157. # Give up and show an error. It's nice to be able to assume that
  158. # the tree is non-empty in the rest of the code.
  159. _root.wait_visibility()
  160. messagebox.showerror(
  161. "Error",
  162. "Empty configuration -- nothing to configure.\n\n"
  163. "Check that environment variables are set properly.")
  164. _root.destroy()
  165. return
  166. # Build the initial tree
  167. _update_tree()
  168. # Select the first item and focus the Treeview, so that keyboard controls
  169. # work immediately
  170. _select(_tree, _tree.get_children()[0])
  171. _tree.focus_set()
  172. # Make geometry information available for centering the window. This
  173. # indirectly creates the window, so hide it so that it's never shown at the
  174. # old location.
  175. _root.withdraw()
  176. _root.update_idletasks()
  177. # Center the window
  178. _root.geometry("+{}+{}".format(
  179. (_root.winfo_screenwidth() - _root.winfo_reqwidth())//2,
  180. (_root.winfo_screenheight() - _root.winfo_reqheight())//2))
  181. # Show it
  182. _root.deiconify()
  183. # Prevent the window from being automatically resized. Otherwise, it
  184. # changes size when scrollbars appear/disappear before the user has
  185. # manually resized it.
  186. _root.geometry(_root.geometry())
  187. _root.mainloop()
  188. def _load_config():
  189. # Loads any existing .config file. See the Kconfig.load_config() docstring.
  190. #
  191. # Returns True if .config is missing or outdated. We always prompt for
  192. # saving the configuration in that case.
  193. print(_kconf.load_config())
  194. if not os.path.exists(_conf_filename):
  195. # No .config
  196. return True
  197. return _needs_save()
  198. def _needs_save():
  199. # Returns True if a just-loaded .config file is outdated (would get
  200. # modified when saving)
  201. if _kconf.missing_syms:
  202. # Assignments to undefined symbols in the .config
  203. return True
  204. for sym in _kconf.unique_defined_syms:
  205. if sym.user_value is None:
  206. if sym.config_string:
  207. # Unwritten symbol
  208. return True
  209. elif sym.orig_type in (BOOL, TRISTATE):
  210. if sym.tri_value != sym.user_value:
  211. # Written bool/tristate symbol, new value
  212. return True
  213. elif sym.str_value != sym.user_value:
  214. # Written string/int/hex symbol, new value
  215. return True
  216. # No need to prompt for save
  217. return False
  218. def _create_id_to_node():
  219. global _id_to_node
  220. _id_to_node = {str(id(node)): node for node in _kconf.node_iter()}
  221. def _create_ui():
  222. # Creates the main window UI
  223. global _root
  224. global _tree
  225. # Create the root window. This initializes Tkinter and makes e.g.
  226. # PhotoImage available, so do it early.
  227. _root = Tk()
  228. _load_images()
  229. _init_misc_ui()
  230. _fix_treeview_issues()
  231. _create_top_widgets()
  232. # Create the pane with the Kconfig tree and description text
  233. panedwindow, _tree = _create_kconfig_tree_and_desc(_root)
  234. panedwindow.grid(column=0, row=1, sticky="nsew")
  235. _create_status_bar()
  236. _root.columnconfigure(0, weight=1)
  237. # Only the pane with the Kconfig tree and description grows vertically
  238. _root.rowconfigure(1, weight=1)
  239. # Start with show-name disabled
  240. _do_showname()
  241. _tree.bind("<Left>", _tree_left_key)
  242. _tree.bind("<Right>", _tree_right_key)
  243. # Note: Binding this for the jump-to tree as well would cause issues due to
  244. # the Tk bug mentioned in _tree_open()
  245. _tree.bind("<<TreeviewOpen>>", _tree_open)
  246. # add=True to avoid overriding the description text update
  247. _tree.bind("<<TreeviewSelect>>", _update_menu_path, add=True)
  248. _root.bind("<Control-s>", _save)
  249. _root.bind("<Control-o>", _open)
  250. _root.bind("<Control-a>", _toggle_showall)
  251. _root.bind("<Control-n>", _toggle_showname)
  252. _root.bind("<Control-m>", _toggle_tree_mode)
  253. _root.bind("<Control-f>", _jump_to_dialog)
  254. _root.bind("/", _jump_to_dialog)
  255. _root.bind("<Escape>", _on_quit)
  256. def _load_images():
  257. # Loads GIF images, creating the global _*_img PhotoImage variables.
  258. # Base64-encoded images embedded in this script are used if
  259. # _USE_EMBEDDED_IMAGES is True, and separate image files in the same
  260. # directory as the script otherwise.
  261. #
  262. # Using a global variable indirectly prevents the image from being
  263. # garbage-collected. Passing an image to a Tkinter function isn't enough to
  264. # keep it alive.
  265. def load_image(name, data):
  266. var_name = "_{}_img".format(name)
  267. if _USE_EMBEDDED_IMAGES:
  268. globals()[var_name] = PhotoImage(data=data, format="gif")
  269. else:
  270. globals()[var_name] = PhotoImage(
  271. file=os.path.join(os.path.dirname(__file__), name + ".gif"),
  272. format="gif")
  273. # Note: Base64 data can be put on the clipboard with
  274. # $ base64 -w0 foo.gif | xclip
  275. load_image("icon", "R0lGODlhMAAwAPEDAAAAAADQAO7u7v///yH5BAUKAAMALAAAAAAwADAAAAL/nI+gy+2Pokyv2jazuZxryQjiSJZmyXxHeLbumH6sEATvW8OLNtf5bfLZRLFITzgEipDJ4mYxYv6A0ubuqYhWk66tVTE4enHer7jcKvt0LLUw6P45lvEprT6c0+v7OBuqhYdHohcoqIbSAHc4ljhDwrh1UlgSydRCWWlp5wiYZvmSuSh4IzrqV6p4cwhkCsmY+nhK6uJ6t1mrOhuJqfu6+WYiCiwl7HtLjNSZZZis/MeM7NY3TaRKS40ooDeoiVqIultsrav92bi9c3a5KkkOsOJZpSS99m4k/0zPng4Gks9JSbB+8DIcoQfnjwpZCHv5W+ip4aQrKrB0uOikYhiMCBw1/uPoQUMBADs=")
  276. load_image("n_bool", "R0lGODdhEAAQAPAAAAgICP///ywAAAAAEAAQAAACIISPacHtvp5kcb5qG85hZ2+BkyiRF8BBaEqtrKkqslEAADs=")
  277. load_image("y_bool", "R0lGODdhEAAQAPEAAAgICADQAP///wAAACwAAAAAEAAQAAACMoSPacLtvlh4YrIYsst2cV19AvaVF9CUXBNJJoum7ymrsKuCnhiupIWjSSjAFuWhSCIKADs=")
  278. load_image("n_tri", "R0lGODlhEAAQAPD/AAEBAf///yH5BAUKAAIALAAAAAAQABAAAAInlI+pBrAKQnCPSUlXvFhznlkfeGwjKZhnJ65h6nrfi6h0st2QXikFADs=")
  279. load_image("m_tri", "R0lGODlhEAAQAPEDAAEBAeQMuv///wAAACH5BAUKAAMALAAAAAAQABAAAAI5nI+pBrAWAhPCjYhiAJQCnWmdoElHGVBoiK5M21ofXFpXRIrgiecqxkuNciZIhNOZFRNI24PhfEoLADs=")
  280. load_image("y_tri", "R0lGODlhEAAQAPEDAAICAgDQAP///wAAACH5BAUKAAMALAAAAAAQABAAAAI0nI+pBrAYBhDCRRUypfmergmgZ4xjMpmaw2zmxk7cCB+pWiVqp4MzDwn9FhGZ5WFjIZeGAgA7")
  281. load_image("m_my", "R0lGODlhEAAQAPEDAAAAAOQMuv///wAAACH5BAUKAAMALAAAAAAQABAAAAI5nIGpxiAPI2ghxFinq/ZygQhc94zgZopmOLYf67anGr+oZdp02emfV5n9MEHN5QhqICETxkABbQ4KADs=")
  282. load_image("y_my", "R0lGODlhEAAQAPH/AAAAAADQAAPRA////yH5BAUKAAQALAAAAAAQABAAAAM+SArcrhCMSSuIM9Q8rxxBWIXawIBkmWonupLd565Um9G1PIs59fKmzw8WnAlusBYR2SEIN6DmAmqBLBxYSAIAOw==")
  283. load_image("n_locked", "R0lGODlhEAAQAPABAAAAAP///yH5BAUKAAEALAAAAAAQABAAAAIgjB8AyKwN04pu0vMutpqqz4Hih4ydlnUpyl2r23pxUAAAOw==")
  284. load_image("m_locked", "R0lGODlhEAAQAPD/AAAAAOQMuiH5BAUKAAIALAAAAAAQABAAAAIylC8AyKwN04ohnGcqqlZmfXDWI26iInZoyiore05walolV39ftxsYHgL9QBBMBGFEFAAAOw==")
  285. load_image("y_locked", "R0lGODlhEAAQAPD/AAAAAADQACH5BAUKAAIALAAAAAAQABAAAAIylC8AyKzNgnlCtoDTwvZwrHydIYpQmR3KWq4uK74IOnp0HQPmnD3cOVlUIAgKsShkFAAAOw==")
  286. load_image("not_selected", "R0lGODlhEAAQAPD/AAAAAP///yH5BAUKAAIALAAAAAAQABAAAAIrlA2px6IBw2IpWglOvTYhzmUbGD3kNZ5QqrKn2YrqigCxZoMelU6No9gdCgA7")
  287. load_image("selected", "R0lGODlhEAAQAPD/AAAAAP///yH5BAUKAAIALAAAAAAQABAAAAIzlA2px6IBw2IpWglOvTah/kTZhimASJomiqonlLov1qptHTsgKSEzh9H8QI0QzNPwmRoFADs=")
  288. load_image("edit", "R0lGODlhEAAQAPIFAAAAAKOLAMuuEPvXCvrxvgAAAAAAAAAAACH5BAUKAAUALAAAAAAQABAAAANCWLqw/gqMBp8cszJxcwVC2FEOEIAi5kVBi3IqWZhuCGMyfdpj2e4pnK+WAshmvxeAcETWlsxPkkBtsqBMa8TIBSQAADs=")
  289. def _fix_treeview_issues():
  290. # Fixes some Treeview issues
  291. global _treeview_rowheight
  292. style = ttk.Style()
  293. # The treeview rowheight isn't adjusted automatically on high-DPI displays,
  294. # so do it ourselves. The font will probably always be TkDefaultFont, but
  295. # play it safe and look it up.
  296. _treeview_rowheight = font.Font(font=style.lookup("Treeview", "font")) \
  297. .metrics("linespace") + 2
  298. style.configure("Treeview", rowheight=_treeview_rowheight)
  299. # Work around regression in https://core.tcl.tk/tk/tktview?name=509cafafae,
  300. # which breaks tag background colors
  301. for option in "foreground", "background":
  302. # Filter out any styles starting with ("!disabled", "!selected", ...).
  303. # style.map() returns an empty list for missing options, so this should
  304. # be future-safe.
  305. style.map(
  306. "Treeview",
  307. **{option: [elm for elm in style.map("Treeview", query_opt=option)
  308. if elm[:2] != ("!disabled", "!selected")]})
  309. def _init_misc_ui():
  310. # Does misc. UI initialization, like setting the title, icon, and theme
  311. _root.title(_kconf.mainmenu_text)
  312. # iconphoto() isn't available in Python 2's Tkinter
  313. _root.tk.call("wm", "iconphoto", _root._w, "-default", _icon_img)
  314. # Reducing the width of the window to 1 pixel makes it move around, at
  315. # least on GNOME. Prevent weird stuff like that.
  316. _root.minsize(128, 128)
  317. _root.protocol("WM_DELETE_WINDOW", _on_quit)
  318. # Use the 'clam' theme on *nix if it's available. It looks nicer than the
  319. # 'default' theme.
  320. if _root.tk.call("tk", "windowingsystem") == "x11":
  321. style = ttk.Style()
  322. if "clam" in style.theme_names():
  323. style.theme_use("clam")
  324. def _create_top_widgets():
  325. # Creates the controls above the Kconfig tree in the main window
  326. global _show_all_var
  327. global _show_name_var
  328. global _single_menu_var
  329. global _menupath
  330. global _backbutton
  331. topframe = ttk.Frame(_root)
  332. topframe.grid(column=0, row=0, sticky="ew")
  333. ttk.Button(topframe, text="Save", command=_save) \
  334. .grid(column=0, row=0, sticky="ew", padx=".05c", pady=".05c")
  335. ttk.Button(topframe, text="Save as...", command=_save_as) \
  336. .grid(column=1, row=0, sticky="ew")
  337. ttk.Button(topframe, text="Save minimal (advanced)...",
  338. command=_save_minimal) \
  339. .grid(column=2, row=0, sticky="ew", padx=".05c")
  340. ttk.Button(topframe, text="Open...", command=_open) \
  341. .grid(column=3, row=0)
  342. ttk.Button(topframe, text="Jump to...", command=_jump_to_dialog) \
  343. .grid(column=4, row=0, padx=".05c")
  344. _show_name_var = BooleanVar()
  345. ttk.Checkbutton(topframe, text="Show name", command=_do_showname,
  346. variable=_show_name_var) \
  347. .grid(column=0, row=1, sticky="nsew", padx=".05c", pady="0 .05c",
  348. ipady=".2c")
  349. _show_all_var = BooleanVar()
  350. ttk.Checkbutton(topframe, text="Show all", command=_do_showall,
  351. variable=_show_all_var) \
  352. .grid(column=1, row=1, sticky="nsew", pady="0 .05c")
  353. # Allow the show-all and single-menu status to be queried via plain global
  354. # Python variables, which is faster and simpler
  355. def show_all_updated(*_):
  356. global _show_all
  357. _show_all = _show_all_var.get()
  358. _trace_write(_show_all_var, show_all_updated)
  359. _show_all_var.set(False)
  360. _single_menu_var = BooleanVar()
  361. ttk.Checkbutton(topframe, text="Single-menu mode", command=_do_tree_mode,
  362. variable=_single_menu_var) \
  363. .grid(column=2, row=1, sticky="nsew", padx=".05c", pady="0 .05c")
  364. _backbutton = ttk.Button(topframe, text="<--", command=_leave_menu,
  365. state="disabled")
  366. _backbutton.grid(column=0, row=4, sticky="nsew", padx=".05c", pady="0 .05c")
  367. def tree_mode_updated(*_):
  368. global _single_menu
  369. _single_menu = _single_menu_var.get()
  370. if _single_menu:
  371. _backbutton.grid()
  372. else:
  373. _backbutton.grid_remove()
  374. _trace_write(_single_menu_var, tree_mode_updated)
  375. _single_menu_var.set(False)
  376. # Column to the right of the buttons that the menu path extends into, so
  377. # that it can grow wider than the buttons
  378. topframe.columnconfigure(5, weight=1)
  379. _menupath = ttk.Label(topframe)
  380. _menupath.grid(column=0, row=3, columnspan=6, sticky="w", padx="0.05c",
  381. pady="0 .05c")
  382. def _create_kconfig_tree_and_desc(parent):
  383. # Creates a Panedwindow with a Treeview that shows Kconfig nodes and a Text
  384. # that shows a description of the selected node. Returns a tuple with the
  385. # Panedwindow and the Treeview. This code is shared between the main window
  386. # and the jump-to dialog.
  387. panedwindow = ttk.Panedwindow(parent, orient=VERTICAL)
  388. tree_frame, tree = _create_kconfig_tree(panedwindow)
  389. desc_frame, desc = _create_kconfig_desc(panedwindow)
  390. panedwindow.add(tree_frame, weight=1)
  391. panedwindow.add(desc_frame)
  392. def tree_select(_):
  393. # The Text widget does not allow editing the text in its disabled
  394. # state. We need to temporarily enable it.
  395. desc["state"] = "normal"
  396. sel = tree.selection()
  397. if not sel:
  398. desc.delete("1.0", "end")
  399. desc["state"] = "disabled"
  400. return
  401. # Text.replace() is not available in Python 2's Tkinter
  402. desc.delete("1.0", "end")
  403. desc.insert("end", _info_str(_id_to_node[sel[0]]))
  404. desc["state"] = "disabled"
  405. tree.bind("<<TreeviewSelect>>", tree_select)
  406. tree.bind("<1>", _tree_click)
  407. tree.bind("<Double-1>", _tree_double_click)
  408. tree.bind("<Return>", _tree_enter)
  409. tree.bind("<KP_Enter>", _tree_enter)
  410. tree.bind("<space>", _tree_toggle)
  411. tree.bind("n", _tree_set_val(0))
  412. tree.bind("m", _tree_set_val(1))
  413. tree.bind("y", _tree_set_val(2))
  414. return panedwindow, tree
  415. def _create_kconfig_tree(parent):
  416. # Creates a Treeview for showing Kconfig nodes
  417. frame = ttk.Frame(parent)
  418. tree = ttk.Treeview(frame, selectmode="browse", height=20,
  419. columns=("name",))
  420. tree.heading("#0", text="Option", anchor="w")
  421. tree.heading("name", text="Name", anchor="w")
  422. tree.tag_configure("n-bool", image=_n_bool_img)
  423. tree.tag_configure("y-bool", image=_y_bool_img)
  424. tree.tag_configure("m-tri", image=_m_tri_img)
  425. tree.tag_configure("n-tri", image=_n_tri_img)
  426. tree.tag_configure("m-tri", image=_m_tri_img)
  427. tree.tag_configure("y-tri", image=_y_tri_img)
  428. tree.tag_configure("m-my", image=_m_my_img)
  429. tree.tag_configure("y-my", image=_y_my_img)
  430. tree.tag_configure("n-locked", image=_n_locked_img)
  431. tree.tag_configure("m-locked", image=_m_locked_img)
  432. tree.tag_configure("y-locked", image=_y_locked_img)
  433. tree.tag_configure("not-selected", image=_not_selected_img)
  434. tree.tag_configure("selected", image=_selected_img)
  435. tree.tag_configure("edit", image=_edit_img)
  436. tree.tag_configure("invisible", foreground="red")
  437. tree.grid(column=0, row=0, sticky="nsew")
  438. _add_vscrollbar(frame, tree)
  439. frame.columnconfigure(0, weight=1)
  440. frame.rowconfigure(0, weight=1)
  441. # Create items for all menu nodes. These can be detached/moved later.
  442. # Micro-optimize this a bit.
  443. insert = tree.insert
  444. id_ = id
  445. Symbol_ = Symbol
  446. for node in _kconf.node_iter():
  447. item = node.item
  448. insert("", "end", iid=id_(node),
  449. values=item.name if item.__class__ is Symbol_ else "")
  450. return frame, tree
  451. def _create_kconfig_desc(parent):
  452. # Creates a Text for showing the description of the selected Kconfig node
  453. frame = ttk.Frame(parent)
  454. desc = Text(frame, height=12, wrap="none", borderwidth=0,
  455. state="disabled")
  456. desc.grid(column=0, row=0, sticky="nsew")
  457. # Work around not being to Ctrl-C/V text from a disabled Text widget, with a
  458. # tip found in https://stackoverflow.com/questions/3842155/is-there-a-way-to-make-the-tkinter-text-widget-read-only
  459. desc.bind("<1>", lambda _: desc.focus_set())
  460. _add_vscrollbar(frame, desc)
  461. frame.columnconfigure(0, weight=1)
  462. frame.rowconfigure(0, weight=1)
  463. return frame, desc
  464. def _add_vscrollbar(parent, widget):
  465. # Adds a vertical scrollbar to 'widget' that's only shown as needed
  466. vscrollbar = ttk.Scrollbar(parent, orient="vertical",
  467. command=widget.yview)
  468. vscrollbar.grid(column=1, row=0, sticky="ns")
  469. def yscrollcommand(first, last):
  470. # Only show the scrollbar when needed. 'first' and 'last' are
  471. # strings.
  472. if float(first) <= 0.0 and float(last) >= 1.0:
  473. vscrollbar.grid_remove()
  474. else:
  475. vscrollbar.grid()
  476. vscrollbar.set(first, last)
  477. widget["yscrollcommand"] = yscrollcommand
  478. def _create_status_bar():
  479. # Creates the status bar at the bottom of the main window
  480. global _status_label
  481. _status_label = ttk.Label(_root, anchor="e", padding="0 0 0.4c 0")
  482. _status_label.grid(column=0, row=3, sticky="ew")
  483. def _set_status(s):
  484. # Sets the text in the status bar to 's'
  485. _status_label["text"] = s
  486. def _set_conf_changed(changed):
  487. # Updates the status re. whether there are unsaved changes
  488. global _conf_changed
  489. _conf_changed = changed
  490. if changed:
  491. _set_status("Modified")
  492. def _update_tree():
  493. # Updates the Kconfig tree in the main window by first detaching all nodes
  494. # and then updating and reattaching them. The tree structure might have
  495. # changed.
  496. # If a selected/focused item is detached and later reattached, it stays
  497. # selected/focused. That can give multiple selections even though
  498. # selectmode=browse. Save and later restore the selection and focus as a
  499. # workaround.
  500. old_selection = _tree.selection()
  501. old_focus = _tree.focus()
  502. # Detach all tree items before re-stringing them. This is relatively fast,
  503. # luckily.
  504. _tree.detach(*_id_to_node.keys())
  505. if _single_menu:
  506. _build_menu_tree()
  507. else:
  508. _build_full_tree(_kconf.top_node)
  509. _tree.selection_set(old_selection)
  510. _tree.focus(old_focus)
  511. def _build_full_tree(menu):
  512. # Updates the tree starting from menu.list, in full-tree mode. To speed
  513. # things up, only open menus are updated. The menu-at-a-time logic here is
  514. # to deal with invisible items that can show up outside show-all mode (see
  515. # _shown_full_nodes()).
  516. for node in _shown_full_nodes(menu):
  517. _add_to_tree(node, _kconf.top_node)
  518. # _shown_full_nodes() includes nodes from menus rooted at symbols, so
  519. # we only need to check "real" menus/choices here
  520. if node.list and not isinstance(node.item, Symbol):
  521. if _tree.item(id(node), "open"):
  522. _build_full_tree(node)
  523. else:
  524. # We're just probing here, so _shown_menu_nodes() will work
  525. # fine, and might be a bit faster
  526. shown = _shown_menu_nodes(node)
  527. if shown:
  528. # Dummy element to make the open/closed toggle appear
  529. _tree.move(id(shown[0]), id(shown[0].parent), "end")
  530. def _shown_full_nodes(menu):
  531. # Returns the list of menu nodes shown in 'menu' (a menu node for a menu)
  532. # for full-tree mode. A tricky detail is that invisible items need to be
  533. # shown if they have visible children.
  534. def rec(node):
  535. res = []
  536. while node:
  537. if _visible(node) or _show_all:
  538. res.append(node)
  539. if node.list and isinstance(node.item, Symbol):
  540. # Nodes from menu created from dependencies
  541. res += rec(node.list)
  542. elif node.list and isinstance(node.item, Symbol):
  543. # Show invisible symbols (defined with either 'config' and
  544. # 'menuconfig') if they have visible children. This can happen
  545. # for an m/y-valued symbol with an optional prompt
  546. # ('prompt "foo" is COND') that is currently disabled.
  547. shown_children = rec(node.list)
  548. if shown_children:
  549. res.append(node)
  550. res += shown_children
  551. node = node.next
  552. return res
  553. return rec(menu.list)
  554. def _build_menu_tree():
  555. # Updates the tree in single-menu mode. See _build_full_tree() as well.
  556. for node in _shown_menu_nodes(_cur_menu):
  557. _add_to_tree(node, _cur_menu)
  558. def _shown_menu_nodes(menu):
  559. # Used for single-menu mode. Similar to _shown_full_nodes(), but doesn't
  560. # include children of symbols defined with 'menuconfig'.
  561. def rec(node):
  562. res = []
  563. while node:
  564. if _visible(node) or _show_all:
  565. res.append(node)
  566. if node.list and not node.is_menuconfig:
  567. res += rec(node.list)
  568. elif node.list and isinstance(node.item, Symbol):
  569. shown_children = rec(node.list)
  570. if shown_children:
  571. # Invisible item with visible children
  572. res.append(node)
  573. if not node.is_menuconfig:
  574. res += shown_children
  575. node = node.next
  576. return res
  577. return rec(menu.list)
  578. def _visible(node):
  579. # Returns True if the node should appear in the menu (outside show-all
  580. # mode)
  581. return node.prompt and expr_value(node.prompt[1]) and not \
  582. (node.item == MENU and not expr_value(node.visibility))
  583. def _add_to_tree(node, top):
  584. # Adds 'node' to the tree, at the end of its menu. We rely on going through
  585. # the nodes linearly to get the correct order. 'top' holds the menu that
  586. # corresponds to the top-level menu, and can vary in single-menu mode.
  587. parent = node.parent
  588. _tree.move(id(node), "" if parent is top else id(parent), "end")
  589. _tree.item(
  590. id(node),
  591. text=_node_str(node),
  592. # The _show_all test avoids showing invisible items in red outside
  593. # show-all mode, which could look confusing/broken. Invisible symbols
  594. # are shown outside show-all mode if an invisible symbol has visible
  595. # children in an implicit menu.
  596. tags=_img_tag(node) if _visible(node) or not _show_all else
  597. _img_tag(node) + " invisible")
  598. def _node_str(node):
  599. # Returns the string shown to the right of the image (if any) for the node
  600. if node.prompt:
  601. if node.item == COMMENT:
  602. s = "*** {} ***".format(node.prompt[0])
  603. else:
  604. s = node.prompt[0]
  605. if isinstance(node.item, Symbol):
  606. sym = node.item
  607. # Print "(NEW)" next to symbols without a user value (from e.g. a
  608. # .config), but skip it for choice symbols in choices in y mode,
  609. # and for symbols of UNKNOWN type (which generate a warning though)
  610. if sym.user_value is None and sym.type and not \
  611. (sym.choice and sym.choice.tri_value == 2):
  612. s += " (NEW)"
  613. elif isinstance(node.item, Symbol):
  614. # Symbol without prompt (can show up in show-all)
  615. s = "<{}>".format(node.item.name)
  616. else:
  617. # Choice without prompt. Use standard_sc_expr_str() so that it shows up
  618. # as '<choice (name if any)>'.
  619. s = standard_sc_expr_str(node.item)
  620. if isinstance(node.item, Symbol):
  621. sym = node.item
  622. if sym.orig_type == STRING:
  623. s += ": " + sym.str_value
  624. elif sym.orig_type in (INT, HEX):
  625. s = "({}) {}".format(sym.str_value, s)
  626. elif isinstance(node.item, Choice) and node.item.tri_value == 2:
  627. # Print the prompt of the selected symbol after the choice for
  628. # choices in y mode
  629. sym = node.item.selection
  630. if sym:
  631. for sym_node in sym.nodes:
  632. # Use the prompt used at this choice location, in case the
  633. # choice symbol is defined in multiple locations
  634. if sym_node.parent is node and sym_node.prompt:
  635. s += " ({})".format(sym_node.prompt[0])
  636. break
  637. else:
  638. # If the symbol isn't defined at this choice location, then
  639. # just use whatever prompt we can find for it
  640. for sym_node in sym.nodes:
  641. if sym_node.prompt:
  642. s += " ({})".format(sym_node.prompt[0])
  643. break
  644. # In single-menu mode, print "--->" next to nodes that have menus that can
  645. # potentially be entered. Print "----" if the menu is empty. We don't allow
  646. # those to be entered.
  647. if _single_menu and node.is_menuconfig:
  648. s += " --->" if _shown_menu_nodes(node) else " ----"
  649. return s
  650. def _img_tag(node):
  651. # Returns the tag for the image that should be shown next to 'node', or the
  652. # empty string if it shouldn't have an image
  653. item = node.item
  654. if item in (MENU, COMMENT) or not item.orig_type:
  655. return ""
  656. if item.orig_type in (STRING, INT, HEX):
  657. return "edit"
  658. # BOOL or TRISTATE
  659. if _is_y_mode_choice_sym(item):
  660. # Choice symbol in y-mode choice
  661. return "selected" if item.choice.selection is item else "not-selected"
  662. if len(item.assignable) <= 1:
  663. # Pinned to a single value
  664. return "" if isinstance(item, Choice) else item.str_value + "-locked"
  665. if item.type == BOOL:
  666. return item.str_value + "-bool"
  667. # item.type == TRISTATE
  668. if item.assignable == (1, 2):
  669. return item.str_value + "-my"
  670. return item.str_value + "-tri"
  671. def _is_y_mode_choice_sym(item):
  672. # The choice mode is an upper bound on the visibility of choice symbols, so
  673. # we can check the choice symbols' own visibility to see if the choice is
  674. # in y mode
  675. return isinstance(item, Symbol) and item.choice and item.visibility == 2
  676. def _tree_click(event):
  677. # Click on the Kconfig Treeview
  678. tree = event.widget
  679. if tree.identify_element(event.x, event.y) == "image":
  680. item = tree.identify_row(event.y)
  681. # Select the item before possibly popping up a dialog for
  682. # string/int/hex items, so that its help is visible
  683. _select(tree, item)
  684. _change_node(_id_to_node[item], tree.winfo_toplevel())
  685. return "break"
  686. def _tree_double_click(event):
  687. # Double-click on the Kconfig treeview
  688. # Do an extra check to avoid weirdness when double-clicking in the tree
  689. # heading area
  690. if not _in_heading(event):
  691. return _tree_enter(event)
  692. def _in_heading(event):
  693. # Returns True if 'event' took place in the tree heading
  694. tree = event.widget
  695. return hasattr(tree, "identify_region") and \
  696. tree.identify_region(event.x, event.y) in ("heading", "separator")
  697. def _tree_enter(event):
  698. # Enter press or double-click within the Kconfig treeview. Prefer to
  699. # open/close/enter menus, but toggle the value if that's not possible.
  700. tree = event.widget
  701. sel = tree.focus()
  702. if sel:
  703. node = _id_to_node[sel]
  704. if tree.get_children(sel):
  705. _tree_toggle_open(sel)
  706. elif _single_menu_mode_menu(node, tree):
  707. _enter_menu_and_select_first(node)
  708. else:
  709. _change_node(node, tree.winfo_toplevel())
  710. return "break"
  711. def _tree_toggle(event):
  712. # Space press within the Kconfig treeview. Prefer to toggle the value, but
  713. # open/close/enter the menu if that's not possible.
  714. tree = event.widget
  715. sel = tree.focus()
  716. if sel:
  717. node = _id_to_node[sel]
  718. if _changeable(node):
  719. _change_node(node, tree.winfo_toplevel())
  720. elif _single_menu_mode_menu(node, tree):
  721. _enter_menu_and_select_first(node)
  722. elif tree.get_children(sel):
  723. _tree_toggle_open(sel)
  724. return "break"
  725. def _tree_left_key(_):
  726. # Left arrow key press within the Kconfig treeview
  727. if _single_menu:
  728. # Leave the current menu in single-menu mode
  729. _leave_menu()
  730. return "break"
  731. # Otherwise, default action
  732. def _tree_right_key(_):
  733. # Right arrow key press within the Kconfig treeview
  734. sel = _tree.focus()
  735. if sel:
  736. node = _id_to_node[sel]
  737. # If the node can be entered in single-menu mode, do it
  738. if _single_menu_mode_menu(node, _tree):
  739. _enter_menu_and_select_first(node)
  740. return "break"
  741. # Otherwise, default action
  742. def _single_menu_mode_menu(node, tree):
  743. # Returns True if single-menu mode is on and 'node' is an (interface)
  744. # menu that can be entered
  745. return _single_menu and tree is _tree and node.is_menuconfig and \
  746. _shown_menu_nodes(node)
  747. def _changeable(node):
  748. # Returns True if 'node' is a Symbol/Choice whose value can be changed
  749. sc = node.item
  750. if not isinstance(sc, (Symbol, Choice)):
  751. return False
  752. # This will hit for invisible symbols, which appear in show-all mode and
  753. # when an invisible symbol has visible children (which can happen e.g. for
  754. # symbols with optional prompts)
  755. if not (node.prompt and expr_value(node.prompt[1])):
  756. return False
  757. return sc.orig_type in (STRING, INT, HEX) or len(sc.assignable) > 1 \
  758. or _is_y_mode_choice_sym(sc)
  759. def _tree_toggle_open(item):
  760. # Opens/closes the Treeview item 'item'
  761. if _tree.item(item, "open"):
  762. _tree.item(item, open=False)
  763. else:
  764. node = _id_to_node[item]
  765. if not isinstance(node.item, Symbol):
  766. # Can only get here in full-tree mode
  767. _build_full_tree(node)
  768. _tree.item(item, open=True)
  769. def _tree_set_val(tri_val):
  770. def tree_set_val(event):
  771. # n/m/y press within the Kconfig treeview
  772. # Sets the value of the currently selected item to 'tri_val', if that
  773. # value can be assigned
  774. sel = event.widget.focus()
  775. if sel:
  776. sc = _id_to_node[sel].item
  777. if isinstance(sc, (Symbol, Choice)) and tri_val in sc.assignable:
  778. _set_val(sc, tri_val)
  779. return tree_set_val
  780. def _tree_open(_):
  781. # Lazily populates the Kconfig tree when menus are opened in full-tree mode
  782. if _single_menu:
  783. # Work around https://core.tcl.tk/tk/tktview?name=368fa4561e
  784. # ("ttk::treeview open/closed indicators can be toggled while hidden").
  785. # Clicking on the hidden indicator will call _build_full_tree() in
  786. # single-menu mode otherwise.
  787. return
  788. node = _id_to_node[_tree.focus()]
  789. # _shown_full_nodes() includes nodes from menus rooted at symbols, so we
  790. # only need to check "real" menus and choices here
  791. if not isinstance(node.item, Symbol):
  792. _build_full_tree(node)
  793. def _update_menu_path(_):
  794. # Updates the displayed menu path when nodes are selected in the Kconfig
  795. # treeview
  796. sel = _tree.selection()
  797. _menupath["text"] = _menu_path_info(_id_to_node[sel[0]]) if sel else ""
  798. def _item_row(item):
  799. # Returns the row number 'item' appears on within the Kconfig treeview,
  800. # starting from the top of the tree. Used to preserve scrolling.
  801. #
  802. # ttkTreeview.c in the Tk sources defines a RowNumber() function that does
  803. # the same thing, but it's not exposed.
  804. row = 0
  805. while True:
  806. prev = _tree.prev(item)
  807. if prev:
  808. item = prev
  809. row += _n_rows(item)
  810. else:
  811. item = _tree.parent(item)
  812. if not item:
  813. return row
  814. row += 1
  815. def _n_rows(item):
  816. # _item_row() helper. Returns the number of rows occupied by 'item' and #
  817. # its children.
  818. rows = 1
  819. if _tree.item(item, "open"):
  820. for child in _tree.get_children(item):
  821. rows += _n_rows(child)
  822. return rows
  823. def _attached(item):
  824. # Heuristic for checking if a Treeview item is attached. Doesn't seem to be
  825. # good APIs for this. Might fail for super-obscure cases with tiny trees,
  826. # but you'd just get a small scroll mess-up.
  827. return bool(_tree.next(item) or _tree.prev(item) or _tree.parent(item))
  828. def _change_node(node, parent):
  829. # Toggles/changes the value of 'node'. 'parent' is the parent window
  830. # (either the main window or the jump-to dialog), in case we need to pop up
  831. # a dialog.
  832. if not _changeable(node):
  833. return
  834. # sc = symbol/choice
  835. sc = node.item
  836. if sc.type in (INT, HEX, STRING):
  837. s = _set_val_dialog(node, parent)
  838. # Tkinter can return 'unicode' strings on Python 2, which Kconfiglib
  839. # can't deal with. UTF-8-encode the string to work around it.
  840. if _PY2 and isinstance(s, unicode):
  841. s = s.encode("utf-8", "ignore")
  842. if s is not None:
  843. _set_val(sc, s)
  844. elif len(sc.assignable) == 1:
  845. # Handles choice symbols for choices in y mode, which are a special
  846. # case: .assignable can be (2,) while .tri_value is 0.
  847. _set_val(sc, sc.assignable[0])
  848. else:
  849. # Set the symbol to the value after the current value in
  850. # sc.assignable, with wrapping
  851. val_index = sc.assignable.index(sc.tri_value)
  852. _set_val(sc, sc.assignable[(val_index + 1) % len(sc.assignable)])
  853. def _set_val(sc, val):
  854. # Wrapper around Symbol/Choice.set_value() for updating the menu state and
  855. # _conf_changed
  856. # Use the string representation of tristate values. This makes the format
  857. # consistent for all symbol types.
  858. if val in TRI_TO_STR:
  859. val = TRI_TO_STR[val]
  860. if val != sc.str_value:
  861. sc.set_value(val)
  862. _set_conf_changed(True)
  863. # Update the tree and try to preserve the scroll. Do a cheaper variant
  864. # than in the show-all case, that might mess up the scroll slightly in
  865. # rare cases, but is fast and flicker-free.
  866. stayput = _loc_ref_item() # Item to preserve scroll for
  867. old_row = _item_row(stayput)
  868. _update_tree()
  869. # If the reference item disappeared (can happen if the change was done
  870. # from the jump-to dialog), then avoid messing with the scroll and hope
  871. # for the best
  872. if _attached(stayput):
  873. _tree.yview_scroll(_item_row(stayput) - old_row, "units")
  874. if _jump_to_tree:
  875. _update_jump_to_display()
  876. def _set_val_dialog(node, parent):
  877. # Pops up a dialog for setting the value of the string/int/hex
  878. # symbol at node 'node'. 'parent' is the parent window.
  879. def ok(_=None):
  880. # No 'nonlocal' in Python 2
  881. global _entry_res
  882. s = entry.get()
  883. if sym.type == HEX and not s.startswith(("0x", "0X")):
  884. s = "0x" + s
  885. if _check_valid(dialog, entry, sym, s):
  886. _entry_res = s
  887. dialog.destroy()
  888. def cancel(_=None):
  889. global _entry_res
  890. _entry_res = None
  891. dialog.destroy()
  892. sym = node.item
  893. dialog = Toplevel(parent)
  894. dialog.title("Enter {} value".format(TYPE_TO_STR[sym.type]))
  895. dialog.resizable(False, False)
  896. dialog.transient(parent)
  897. dialog.protocol("WM_DELETE_WINDOW", cancel)
  898. ttk.Label(dialog, text=node.prompt[0] + ":") \
  899. .grid(column=0, row=0, columnspan=2, sticky="w", padx=".3c",
  900. pady=".2c .05c")
  901. entry = ttk.Entry(dialog, width=30)
  902. # Start with the previous value in the editbox, selected
  903. entry.insert(0, sym.str_value)
  904. entry.selection_range(0, "end")
  905. entry.grid(column=0, row=1, columnspan=2, sticky="ew", padx=".3c")
  906. entry.focus_set()
  907. range_info = _range_info(sym)
  908. if range_info:
  909. ttk.Label(dialog, text=range_info) \
  910. .grid(column=0, row=2, columnspan=2, sticky="w", padx=".3c",
  911. pady=".2c 0")
  912. ttk.Button(dialog, text="OK", command=ok) \
  913. .grid(column=0, row=4 if range_info else 3, sticky="e", padx=".3c",
  914. pady=".4c")
  915. ttk.Button(dialog, text="Cancel", command=cancel) \
  916. .grid(column=1, row=4 if range_info else 3, padx="0 .3c")
  917. # Give all horizontal space to the grid cell with the OK button, so that
  918. # Cancel moves to the right
  919. dialog.columnconfigure(0, weight=1)
  920. _center_on_root(dialog)
  921. # Hack to scroll the entry so that the end of the text is shown, from
  922. # https://stackoverflow.com/questions/29334544/why-does-tkinters-entry-xview-moveto-fail.
  923. # Related Tk ticket: https://core.tcl.tk/tk/info/2513186fff
  924. def scroll_entry(_):
  925. _root.update_idletasks()
  926. entry.unbind("<Expose>")
  927. entry.xview_moveto(1)
  928. entry.bind("<Expose>", scroll_entry)
  929. # The dialog must be visible before we can grab the input
  930. dialog.wait_visibility()
  931. dialog.grab_set()
  932. dialog.bind("<Return>", ok)
  933. dialog.bind("<KP_Enter>", ok)
  934. dialog.bind("<Escape>", cancel)
  935. # Wait for the user to be done with the dialog
  936. parent.wait_window(dialog)
  937. # Regrab the input in the parent
  938. parent.grab_set()
  939. return _entry_res
  940. def _center_on_root(dialog):
  941. # Centers 'dialog' on the root window. It often ends up at some bad place
  942. # like the top-left corner of the screen otherwise. See the menuconfig()
  943. # function, which has similar logic.
  944. dialog.withdraw()
  945. _root.update_idletasks()
  946. dialog_width = dialog.winfo_reqwidth()
  947. dialog_height = dialog.winfo_reqheight()
  948. screen_width = _root.winfo_screenwidth()
  949. screen_height = _root.winfo_screenheight()
  950. x = _root.winfo_rootx() + (_root.winfo_width() - dialog_width)//2
  951. y = _root.winfo_rooty() + (_root.winfo_height() - dialog_height)//2
  952. # Clamp so that no part of the dialog is outside the screen
  953. if x + dialog_width > screen_width:
  954. x = screen_width - dialog_width
  955. elif x < 0:
  956. x = 0
  957. if y + dialog_height > screen_height:
  958. y = screen_height - dialog_height
  959. elif y < 0:
  960. y = 0
  961. dialog.geometry("+{}+{}".format(x, y))
  962. dialog.deiconify()
  963. def _check_valid(dialog, entry, sym, s):
  964. # Returns True if the string 's' is a well-formed value for 'sym'.
  965. # Otherwise, pops up an error and returns False.
  966. if sym.type not in (INT, HEX):
  967. # Anything goes for non-int/hex symbols
  968. return True
  969. base = 10 if sym.type == INT else 16
  970. try:
  971. int(s, base)
  972. except ValueError:
  973. messagebox.showerror(
  974. "Bad value",
  975. "'{}' is a malformed {} value".format(
  976. s, TYPE_TO_STR[sym.type]),
  977. parent=dialog)
  978. entry.focus_set()
  979. return False
  980. for low_sym, high_sym, cond in sym.ranges:
  981. if expr_value(cond):
  982. low_s = low_sym.str_value
  983. high_s = high_sym.str_value
  984. if not int(low_s, base) <= int(s, base) <= int(high_s, base):
  985. messagebox.showerror(
  986. "Value out of range",
  987. "{} is outside the range {}-{}".format(s, low_s, high_s),
  988. parent=dialog)
  989. entry.focus_set()
  990. return False
  991. break
  992. return True
  993. def _range_info(sym):
  994. # Returns a string with information about the valid range for the symbol
  995. # 'sym', or None if 'sym' doesn't have a range
  996. if sym.type in (INT, HEX):
  997. for low, high, cond in sym.ranges:
  998. if expr_value(cond):
  999. return "Range: {}-{}".format(low.str_value, high.str_value)
  1000. return None
  1001. def _save(_=None):
  1002. # Tries to save the configuration
  1003. if _try_save(_kconf.write_config, _conf_filename, "configuration"):
  1004. _set_conf_changed(False)
  1005. _tree.focus_set()
  1006. def _save_as():
  1007. # Pops up a dialog for saving the configuration to a specific location
  1008. global _conf_filename
  1009. filename = _conf_filename
  1010. while True:
  1011. filename = filedialog.asksaveasfilename(
  1012. title="Save configuration as",
  1013. initialdir=os.path.dirname(filename),
  1014. initialfile=os.path.basename(filename),
  1015. parent=_root)
  1016. if not filename:
  1017. break
  1018. if _try_save(_kconf.write_config, filename, "configuration"):
  1019. _conf_filename = filename
  1020. break
  1021. _tree.focus_set()
  1022. def _save_minimal():
  1023. # Pops up a dialog for saving a minimal configuration (defconfig) to a
  1024. # specific location
  1025. global _minconf_filename
  1026. filename = _minconf_filename
  1027. while True:
  1028. filename = filedialog.asksaveasfilename(
  1029. title="Save minimal configuration as",
  1030. initialdir=os.path.dirname(filename),
  1031. initialfile=os.path.basename(filename),
  1032. parent=_root)
  1033. if not filename:
  1034. break
  1035. if _try_save(_kconf.write_min_config, filename,
  1036. "minimal configuration"):
  1037. _minconf_filename = filename
  1038. break
  1039. _tree.focus_set()
  1040. def _open(_=None):
  1041. # Pops up a dialog for loading a configuration
  1042. global _conf_filename
  1043. if _conf_changed and \
  1044. not messagebox.askokcancel(
  1045. "Unsaved changes",
  1046. "You have unsaved changes. Load new configuration anyway?"):
  1047. return
  1048. filename = _conf_filename
  1049. while True:
  1050. filename = filedialog.askopenfilename(
  1051. title="Open configuration",
  1052. initialdir=os.path.dirname(filename),
  1053. initialfile=os.path.basename(filename),
  1054. parent=_root)
  1055. if not filename:
  1056. break
  1057. if _try_load(filename):
  1058. # Maybe something fancier could be done here later to try to
  1059. # preserve the scroll
  1060. _conf_filename = filename
  1061. _set_conf_changed(_needs_save())
  1062. if _single_menu and not _shown_menu_nodes(_cur_menu):
  1063. # Turn on show-all if we're in single-menu mode and would end
  1064. # up with an empty menu
  1065. _show_all_var.set(True)
  1066. _update_tree()
  1067. break
  1068. _tree.focus_set()
  1069. def _toggle_showname(_):
  1070. # Toggles show-name mode on/off
  1071. _show_name_var.set(not _show_name_var.get())
  1072. _do_showname()
  1073. def _do_showname():
  1074. # Updates the UI for the current show-name setting
  1075. # Columns do not automatically shrink/expand, so we have to update
  1076. # column widths ourselves
  1077. tree_width = _tree.winfo_width()
  1078. if _show_name_var.get():
  1079. _tree["displaycolumns"] = ("name",)
  1080. _tree["show"] = "tree headings"
  1081. name_width = tree_width//3
  1082. _tree.column("#0", width=max(tree_width - name_width, 1))
  1083. _tree.column("name", width=name_width)
  1084. else:
  1085. _tree["displaycolumns"] = ()
  1086. _tree["show"] = "tree"
  1087. _tree.column("#0", width=tree_width)
  1088. _tree.focus_set()
  1089. def _toggle_showall(_):
  1090. # Toggles show-all mode on/off
  1091. _show_all_var.set(not _show_all)
  1092. _do_showall()
  1093. def _do_showall():
  1094. # Updates the UI for the current show-all setting
  1095. # Don't allow turning off show-all if we'd end up with no visible nodes
  1096. if _nothing_shown():
  1097. _show_all_var.set(True)
  1098. return
  1099. # Save scroll information. old_scroll can end up negative here, if the
  1100. # reference item isn't shown (only invisible items on the screen, and
  1101. # show-all being turned off).
  1102. stayput = _vis_loc_ref_item()
  1103. # Probe the middle of the first row, to play it safe. identify_row(0) seems
  1104. # to return the row before the top row.
  1105. old_scroll = _item_row(stayput) - \
  1106. _item_row(_tree.identify_row(_treeview_rowheight//2))
  1107. _update_tree()
  1108. if _show_all:
  1109. # Deep magic: Unless we call update_idletasks(), the scroll adjustment
  1110. # below is restricted to the height of the old tree, instead of the
  1111. # height of the new tree. Since the tree with show-all on is guaranteed
  1112. # to be taller, and we want the maximum range, we only call it when
  1113. # turning show-all on.
  1114. #
  1115. # Strictly speaking, something similar ought to be done when changing
  1116. # symbol values, but it causes annoying flicker, and in 99% of cases
  1117. # things work anyway there (with usually minor scroll mess-ups in the
  1118. # 1% case).
  1119. _root.update_idletasks()
  1120. # Restore scroll
  1121. _tree.yview(_item_row(stayput) - old_scroll)
  1122. _tree.focus_set()
  1123. def _nothing_shown():
  1124. # _do_showall() helper. Returns True if no nodes would get
  1125. # shown with the current show-all setting. Also handles the
  1126. # (obscure) case when there are no visible nodes in the entire
  1127. # tree, meaning guiconfig was automatically started in
  1128. # show-all mode, which mustn't be turned off.
  1129. return not _shown_menu_nodes(
  1130. _cur_menu if _single_menu else _kconf.top_node)
  1131. def _toggle_tree_mode(_):
  1132. # Toggles single-menu mode on/off
  1133. _single_menu_var.set(not _single_menu)
  1134. _do_tree_mode()
  1135. def _do_tree_mode():
  1136. # Updates the UI for the current tree mode (full-tree or single-menu)
  1137. loc_ref_node = _id_to_node[_loc_ref_item()]
  1138. if not _single_menu:
  1139. # _jump_to() -> _enter_menu() already updates the tree, but
  1140. # _jump_to() -> load_parents() doesn't, because it isn't always needed.
  1141. # We always need to update the tree here, e.g. to add/remove "--->".
  1142. _update_tree()
  1143. _jump_to(loc_ref_node)
  1144. _tree.focus_set()
  1145. def _enter_menu_and_select_first(menu):
  1146. # Enters the menu 'menu' and selects the first item. Used in single-menu
  1147. # mode.
  1148. _enter_menu(menu)
  1149. _select(_tree, _tree.get_children()[0])
  1150. def _enter_menu(menu):
  1151. # Enters the menu 'menu'. Used in single-menu mode.
  1152. global _cur_menu
  1153. _cur_menu = menu
  1154. _update_tree()
  1155. _backbutton["state"] = "disabled" if menu is _kconf.top_node else "normal"
  1156. def _leave_menu():
  1157. # Leaves the current menu. Used in single-menu mode.
  1158. global _cur_menu
  1159. if _cur_menu is not _kconf.top_node:
  1160. old_menu = _cur_menu
  1161. _cur_menu = _parent_menu(_cur_menu)
  1162. _update_tree()
  1163. _select(_tree, id(old_menu))
  1164. if _cur_menu is _kconf.top_node:
  1165. _backbutton["state"] = "disabled"
  1166. _tree.focus_set()
  1167. def _select(tree, item):
  1168. # Selects, focuses, and see()s 'item' in 'tree'
  1169. tree.selection_set(item)
  1170. tree.focus(item)
  1171. tree.see(item)
  1172. def _loc_ref_item():
  1173. # Returns a Treeview item that can serve as a reference for the current
  1174. # scroll location. We try to make this item stay on the same row on the
  1175. # screen when updating the tree.
  1176. # If the selected item is visible, use that
  1177. sel = _tree.selection()
  1178. if sel and _tree.bbox(sel[0]):
  1179. return sel[0]
  1180. # Otherwise, use the middle item on the screen. If it doesn't exist, the
  1181. # tree is probably really small, so use the first item in the entire tree.
  1182. return _tree.identify_row(_tree.winfo_height()//2) or \
  1183. _tree.get_children()[0]
  1184. def _vis_loc_ref_item():
  1185. # Like _loc_ref_item(), but finds a visible item around the reference item.
  1186. # Used when changing show-all mode, where non-visible (red) items will
  1187. # disappear.
  1188. item = _loc_ref_item()
  1189. vis_before = _vis_before(item)
  1190. if vis_before and _tree.bbox(vis_before):
  1191. return vis_before
  1192. vis_after = _vis_after(item)
  1193. if vis_after and _tree.bbox(vis_after):
  1194. return vis_after
  1195. return vis_before or vis_after
  1196. def _vis_before(item):
  1197. # _vis_loc_ref_item() helper. Returns the first visible (not red) item,
  1198. # searching backwards from 'item'.
  1199. while item:
  1200. if not _tree.tag_has("invisible", item):
  1201. return item
  1202. prev = _tree.prev(item)
  1203. item = prev if prev else _tree.parent(item)
  1204. return None
  1205. def _vis_after(item):
  1206. # _vis_loc_ref_item() helper. Returns the first visible (not red) item,
  1207. # searching forwards from 'item'.
  1208. while item:
  1209. if not _tree.tag_has("invisible", item):
  1210. return item
  1211. next = _tree.next(item)
  1212. if next:
  1213. item = next
  1214. else:
  1215. item = _tree.parent(item)
  1216. if not item:
  1217. break
  1218. item = _tree.next(item)
  1219. return None
  1220. def _on_quit(_=None):
  1221. # Called when the user wants to exit
  1222. if not _conf_changed:
  1223. _quit("No changes to save (for '{}')".format(_conf_filename))
  1224. return
  1225. while True:
  1226. ync = messagebox.askyesnocancel("Quit", "Save changes?")
  1227. if ync is None:
  1228. return
  1229. if not ync:
  1230. _quit("Configuration ({}) was not saved".format(_conf_filename))
  1231. return
  1232. if _try_save(_kconf.write_config, _conf_filename, "configuration"):
  1233. # _try_save() already prints the "Configuration saved to ..."
  1234. # message
  1235. _quit()
  1236. return
  1237. def _quit(msg=None):
  1238. # Quits the application
  1239. # Do not call sys.exit() here, in case we're being run from a script
  1240. _root.destroy()
  1241. if msg:
  1242. print(msg)
  1243. def _try_save(save_fn, filename, description):
  1244. # Tries to save a configuration file. Pops up an error and returns False on
  1245. # failure.
  1246. #
  1247. # save_fn:
  1248. # Function to call with 'filename' to save the file
  1249. #
  1250. # description:
  1251. # String describing the thing being saved
  1252. try:
  1253. # save_fn() returns a message to print
  1254. msg = save_fn(filename)
  1255. _set_status(msg)
  1256. print(msg)
  1257. return True
  1258. except EnvironmentError as e:
  1259. messagebox.showerror(
  1260. "Error saving " + description,
  1261. "Error saving {} to '{}': {} (errno: {})"
  1262. .format(description, e.filename, e.strerror,
  1263. errno.errorcode[e.errno]))
  1264. return False
  1265. def _try_load(filename):
  1266. # Tries to load a configuration file. Pops up an error and returns False on
  1267. # failure.
  1268. #
  1269. # filename:
  1270. # Configuration file to load
  1271. try:
  1272. msg = _kconf.load_config(filename)
  1273. _set_status(msg)
  1274. print(msg)
  1275. return True
  1276. except EnvironmentError as e:
  1277. messagebox.showerror(
  1278. "Error loading configuration",
  1279. "Error loading '{}': {} (errno: {})"
  1280. .format(filename, e.strerror, errno.errorcode[e.errno]))
  1281. return False
  1282. def _jump_to_dialog(_=None):
  1283. # Pops up a dialog for jumping directly to a particular node. Symbol values
  1284. # can also be changed within the dialog.
  1285. #
  1286. # Note: There's nothing preventing this from doing an incremental search
  1287. # like menuconfig.py does, but currently it's a bit jerky for large Kconfig
  1288. # trees, at least when inputting the beginning of the search string. We'd
  1289. # need to somehow only update the tree items that are shown in the Treeview
  1290. # to fix it.
  1291. global _jump_to_tree
  1292. def search(_=None):
  1293. _update_jump_to_matches(msglabel, entry.get())
  1294. def jump_to_selected(event=None):
  1295. # Jumps to the selected node and closes the dialog
  1296. # Ignore double clicks on the image and in the heading area
  1297. if event and (tree.identify_element(event.x, event.y) == "image" or
  1298. _in_heading(event)):
  1299. return
  1300. sel = tree.selection()
  1301. if not sel:
  1302. return
  1303. node = _id_to_node[sel[0]]
  1304. if node not in _shown_menu_nodes(_parent_menu(node)):
  1305. _show_all_var.set(True)
  1306. if not _single_menu:
  1307. # See comment in _do_tree_mode()
  1308. _update_tree()
  1309. _jump_to(node)
  1310. dialog.destroy()
  1311. def tree_select(_):
  1312. jumpto_button["state"] = "normal" if tree.selection() else "disabled"
  1313. dialog = Toplevel(_root)
  1314. dialog.geometry("+{}+{}".format(
  1315. _root.winfo_rootx() + 50, _root.winfo_rooty() + 50))
  1316. dialog.title("Jump to symbol/choice/menu/comment")
  1317. dialog.minsize(128, 128) # See _create_ui()
  1318. dialog.transient(_root)
  1319. ttk.Label(dialog, text=_JUMP_TO_HELP) \
  1320. .grid(column=0, row=0, columnspan=2, sticky="w", padx=".1c",
  1321. pady=".1c")
  1322. entry = ttk.Entry(dialog)
  1323. entry.grid(column=0, row=1, sticky="ew", padx=".1c", pady=".1c")
  1324. entry.focus_set()
  1325. entry.bind("<Return>", search)
  1326. entry.bind("<KP_Enter>", search)
  1327. ttk.Button(dialog, text="Search", command=search) \
  1328. .grid(column=1, row=1, padx="0 .1c", pady="0 .1c")
  1329. msglabel = ttk.Label(dialog)
  1330. msglabel.grid(column=0, row=2, sticky="w", pady="0 .1c")
  1331. panedwindow, tree = _create_kconfig_tree_and_desc(dialog)
  1332. panedwindow.grid(column=0, row=3, columnspan=2, sticky="nsew")
  1333. # Clear tree
  1334. tree.set_children("")
  1335. _jump_to_tree = tree
  1336. jumpto_button = ttk.Button(dialog, text="Jump to selected item",
  1337. state="disabled", command=jump_to_selected)
  1338. jumpto_button.grid(column=0, row=4, columnspan=2, sticky="ns", pady=".1c")
  1339. dialog.columnconfigure(0, weight=1)
  1340. # Only the pane with the Kconfig tree and description grows vertically
  1341. dialog.rowconfigure(3, weight=1)
  1342. # See the menuconfig() function
  1343. _root.update_idletasks()
  1344. dialog.geometry(dialog.geometry())
  1345. # The dialog must be visible before we can grab the input
  1346. dialog.wait_visibility()
  1347. dialog.grab_set()
  1348. tree.bind("<Double-1>", jump_to_selected)
  1349. tree.bind("<Return>", jump_to_selected)
  1350. tree.bind("<KP_Enter>", jump_to_selected)
  1351. # add=True to avoid overriding the description text update
  1352. tree.bind("<<TreeviewSelect>>", tree_select, add=True)
  1353. dialog.bind("<Escape>", lambda _: dialog.destroy())
  1354. # Wait for the user to be done with the dialog
  1355. _root.wait_window(dialog)
  1356. _jump_to_tree = None
  1357. _tree.focus_set()
  1358. def _update_jump_to_matches(msglabel, search_string):
  1359. # Searches for nodes matching the search string and updates
  1360. # _jump_to_matches. Puts a message in 'msglabel' if there are no matches,
  1361. # or regex errors.
  1362. global _jump_to_matches
  1363. _jump_to_tree.selection_set(())
  1364. try:
  1365. # We could use re.IGNORECASE here instead of lower(), but this is
  1366. # faster for regexes like '.*debug$' (though the '.*' is redundant
  1367. # there). Those probably have bad interactions with re.search(), which
  1368. # matches anywhere in the string.
  1369. regex_searches = [re.compile(regex).search
  1370. for regex in search_string.lower().split()]
  1371. except re.error as e:
  1372. msg = "Bad regular expression"
  1373. # re.error.msg was added in Python 3.5
  1374. if hasattr(e, "msg"):
  1375. msg += ": " + e.msg
  1376. msglabel["text"] = msg
  1377. # Clear tree
  1378. _jump_to_tree.set_children("")
  1379. return
  1380. _jump_to_matches = []
  1381. add_match = _jump_to_matches.append
  1382. for node in _sorted_sc_nodes():
  1383. # Symbol/choice
  1384. sc = node.item
  1385. for search in regex_searches:
  1386. # Both the name and the prompt might be missing, since
  1387. # we're searching both symbols and choices
  1388. # Does the regex match either the symbol name or the
  1389. # prompt (if any)?
  1390. if not (sc.name and search(sc.name.lower()) or
  1391. node.prompt and search(node.prompt[0].lower())):
  1392. # Give up on the first regex that doesn't match, to
  1393. # speed things up a bit when multiple regexes are
  1394. # entered
  1395. break
  1396. else:
  1397. add_match(node)
  1398. # Search menus and comments
  1399. for node in _sorted_menu_comment_nodes():
  1400. for search in regex_searches:
  1401. if not search(node.prompt[0].lower()):
  1402. break
  1403. else:
  1404. add_match(node)
  1405. msglabel["text"] = "" if _jump_to_matches else "No matches"
  1406. _update_jump_to_display()
  1407. if _jump_to_matches:
  1408. item = id(_jump_to_matches[0])
  1409. _jump_to_tree.selection_set(item)
  1410. _jump_to_tree.focus(item)
  1411. def _update_jump_to_display():
  1412. # Updates the images and text for the items in _jump_to_matches, and sets
  1413. # them as the items of _jump_to_tree
  1414. # Micro-optimize a bit
  1415. item = _jump_to_tree.item
  1416. id_ = id
  1417. node_str = _node_str
  1418. img_tag = _img_tag
  1419. visible = _visible
  1420. for node in _jump_to_matches:
  1421. item(id_(node),
  1422. text=node_str(node),
  1423. tags=img_tag(node) if visible(node) else
  1424. img_tag(node) + " invisible")
  1425. _jump_to_tree.set_children("", *map(id, _jump_to_matches))
  1426. def _jump_to(node):
  1427. # Jumps directly to 'node' and selects it
  1428. if _single_menu:
  1429. _enter_menu(_parent_menu(node))
  1430. else:
  1431. _load_parents(node)
  1432. _select(_tree, id(node))
  1433. # Obscure Python: We never pass a value for cached_nodes, and it keeps pointing
  1434. # to the same list. This avoids a global.
  1435. def _sorted_sc_nodes(cached_nodes=[]):
  1436. # Returns a sorted list of symbol and choice nodes to search. The symbol
  1437. # nodes appear first, sorted by name, and then the choice nodes, sorted by
  1438. # prompt and (secondarily) name.
  1439. if not cached_nodes:
  1440. # Add symbol nodes
  1441. for sym in sorted(_kconf.unique_defined_syms,
  1442. key=lambda sym: sym.name):
  1443. # += is in-place for lists
  1444. cached_nodes += sym.nodes
  1445. # Add choice nodes
  1446. choices = sorted(_kconf.unique_choices,
  1447. key=lambda choice: choice.name or "")
  1448. cached_nodes += sorted(
  1449. [node for choice in choices for node in choice.nodes],
  1450. key=lambda node: node.prompt[0] if node.prompt else "")
  1451. return cached_nodes
  1452. def _sorted_menu_comment_nodes(cached_nodes=[]):
  1453. # Returns a list of menu and comment nodes to search, sorted by prompt,
  1454. # with the menus first
  1455. if not cached_nodes:
  1456. def prompt_text(mc):
  1457. return mc.prompt[0]
  1458. cached_nodes += sorted(_kconf.menus, key=prompt_text)
  1459. cached_nodes += sorted(_kconf.comments, key=prompt_text)
  1460. return cached_nodes
  1461. def _load_parents(node):
  1462. # Menus are lazily populated as they're opened in full-tree mode, but
  1463. # jumping to an item needs its parent menus to be populated. This function
  1464. # populates 'node's parents.
  1465. # Get all parents leading up to 'node', sorted with the root first
  1466. parents = []
  1467. cur = node.parent
  1468. while cur is not _kconf.top_node:
  1469. parents.append(cur)
  1470. cur = cur.parent
  1471. parents.reverse()
  1472. for i, parent in enumerate(parents):
  1473. if not _tree.item(id(parent), "open"):
  1474. # Found a closed menu. Populate it and all the remaining menus
  1475. # leading up to 'node'.
  1476. for parent in parents[i:]:
  1477. # We only need to populate "real" menus/choices. Implicit menus
  1478. # are populated when their parents menus are entered.
  1479. if not isinstance(parent.item, Symbol):
  1480. _build_full_tree(parent)
  1481. return
  1482. def _parent_menu(node):
  1483. # Returns the menu node of the menu that contains 'node'. In addition to
  1484. # proper 'menu's, this might also be a 'menuconfig' symbol or a 'choice'.
  1485. # "Menu" here means a menu in the interface.
  1486. menu = node.parent
  1487. while not menu.is_menuconfig:
  1488. menu = menu.parent
  1489. return menu
  1490. def _trace_write(var, fn):
  1491. # Makes fn() be called whenever the Tkinter Variable 'var' changes value
  1492. # trace_variable() is deprecated according to the docstring,
  1493. # which recommends trace_add()
  1494. if hasattr(var, "trace_add"):
  1495. var.trace_add("write", fn)
  1496. else:
  1497. var.trace_variable("w", fn)
  1498. def _info_str(node):
  1499. # Returns information about the menu node 'node' as a string.
  1500. #
  1501. # The helper functions are responsible for adding newlines. This allows
  1502. # them to return "" if they don't want to add any output.
  1503. if isinstance(node.item, Symbol):
  1504. sym = node.item
  1505. return (
  1506. _name_info(sym) +
  1507. _help_info(sym) +
  1508. _direct_dep_info(sym) +
  1509. _defaults_info(sym) +
  1510. _select_imply_info(sym) +
  1511. _kconfig_def_info(sym)
  1512. )
  1513. if isinstance(node.item, Choice):
  1514. choice = node.item
  1515. return (
  1516. _name_info(choice) +
  1517. _help_info(choice) +
  1518. 'Mode: {}\n\n'.format(choice.str_value) +
  1519. _choice_syms_info(choice) +
  1520. _direct_dep_info(choice) +
  1521. _defaults_info(choice) +
  1522. _kconfig_def_info(choice)
  1523. )
  1524. # node.item in (MENU, COMMENT)
  1525. return _kconfig_def_info(node)
  1526. def _name_info(sc):
  1527. # Returns a string with the name of the symbol/choice. Choices are shown as
  1528. # <choice (name if any)>.
  1529. return (sc.name if sc.name else standard_sc_expr_str(sc)) + "\n\n"
  1530. def _value_info(sym):
  1531. # Returns a string showing 'sym's value
  1532. # Only put quotes around the value for string symbols
  1533. return "Value: {}\n".format(
  1534. '"{}"'.format(sym.str_value)
  1535. if sym.orig_type == STRING
  1536. else sym.str_value)
  1537. def _choice_syms_info(choice):
  1538. # Returns a string listing the choice symbols in 'choice'. Adds
  1539. # "(selected)" next to the selected one.
  1540. s = "Choice symbols:\n"
  1541. for sym in choice.syms:
  1542. s += " - " + sym.name
  1543. if sym is choice.selection:
  1544. s += " (selected)"
  1545. s += "\n"
  1546. return s + "\n"
  1547. def _help_info(sc):
  1548. # Returns a string with the help text(s) of 'sc' (Symbol or Choice).
  1549. # Symbols and choices defined in multiple locations can have multiple help
  1550. # texts.
  1551. s = ""
  1552. for node in sc.nodes:
  1553. if node.help is not None:
  1554. s += node.help + "\n\n"
  1555. return s
  1556. def _direct_dep_info(sc):
  1557. # Returns a string describing the direct dependencies of 'sc' (Symbol or
  1558. # Choice). The direct dependencies are the OR of the dependencies from each
  1559. # definition location. The dependencies at each definition location come
  1560. # from 'depends on' and dependencies inherited from parent items.
  1561. return "" if sc.direct_dep is _kconf.y else \
  1562. 'Direct dependencies (={}):\n{}\n' \
  1563. .format(TRI_TO_STR[expr_value(sc.direct_dep)],
  1564. _split_expr_info(sc.direct_dep, 2))
  1565. def _defaults_info(sc):
  1566. # Returns a string describing the defaults of 'sc' (Symbol or Choice)
  1567. if not sc.defaults:
  1568. return ""
  1569. s = "Default"
  1570. if len(sc.defaults) > 1:
  1571. s += "s"
  1572. s += ":\n"
  1573. for val, cond in sc.orig_defaults:
  1574. s += " - "
  1575. if isinstance(sc, Symbol):
  1576. s += _expr_str(val)
  1577. # Skip the tristate value hint if the expression is just a single
  1578. # symbol. _expr_str() already shows its value as a string.
  1579. #
  1580. # This also avoids showing the tristate value for string/int/hex
  1581. # defaults, which wouldn't make any sense.
  1582. if isinstance(val, tuple):
  1583. s += ' (={})'.format(TRI_TO_STR[expr_value(val)])
  1584. else:
  1585. # Don't print the value next to the symbol name for choice
  1586. # defaults, as it looks a bit confusing
  1587. s += val.name
  1588. s += "\n"
  1589. if cond is not _kconf.y:
  1590. s += " Condition (={}):\n{}" \
  1591. .format(TRI_TO_STR[expr_value(cond)],
  1592. _split_expr_info(cond, 4))
  1593. return s + "\n"
  1594. def _split_expr_info(expr, indent):
  1595. # Returns a string with 'expr' split into its top-level && or || operands,
  1596. # with one operand per line, together with the operand's value. This is
  1597. # usually enough to get something readable for long expressions. A fancier
  1598. # recursive thingy would be possible too.
  1599. #
  1600. # indent:
  1601. # Number of leading spaces to add before the split expression.
  1602. if len(split_expr(expr, AND)) > 1:
  1603. split_op = AND
  1604. op_str = "&&"
  1605. else:
  1606. split_op = OR
  1607. op_str = "||"
  1608. s = ""
  1609. for i, term in enumerate(split_expr(expr, split_op)):
  1610. s += "{}{} {}".format(indent*" ",
  1611. " " if i == 0 else op_str,
  1612. _expr_str(term))
  1613. # Don't bother showing the value hint if the expression is just a
  1614. # single symbol. _expr_str() already shows its value.
  1615. if isinstance(term, tuple):
  1616. s += " (={})".format(TRI_TO_STR[expr_value(term)])
  1617. s += "\n"
  1618. return s
  1619. def _select_imply_info(sym):
  1620. # Returns a string with information about which symbols 'select' or 'imply'
  1621. # 'sym'. The selecting/implying symbols are grouped according to which
  1622. # value they select/imply 'sym' to (n/m/y).
  1623. def sis(expr, val, title):
  1624. # sis = selects/implies
  1625. sis = [si for si in split_expr(expr, OR) if expr_value(si) == val]
  1626. if not sis:
  1627. return ""
  1628. res = title
  1629. for si in sis:
  1630. res += " - {}\n".format(split_expr(si, AND)[0].name)
  1631. return res + "\n"
  1632. s = ""
  1633. if sym.rev_dep is not _kconf.n:
  1634. s += sis(sym.rev_dep, 2,
  1635. "Symbols currently y-selecting this symbol:\n")
  1636. s += sis(sym.rev_dep, 1,
  1637. "Symbols currently m-selecting this symbol:\n")
  1638. s += sis(sym.rev_dep, 0,
  1639. "Symbols currently n-selecting this symbol (no effect):\n")
  1640. if sym.weak_rev_dep is not _kconf.n:
  1641. s += sis(sym.weak_rev_dep, 2,
  1642. "Symbols currently y-implying this symbol:\n")
  1643. s += sis(sym.weak_rev_dep, 1,
  1644. "Symbols currently m-implying this symbol:\n")
  1645. s += sis(sym.weak_rev_dep, 0,
  1646. "Symbols currently n-implying this symbol (no effect):\n")
  1647. return s
  1648. def _kconfig_def_info(item):
  1649. # Returns a string with the definition of 'item' in Kconfig syntax,
  1650. # together with the definition location(s) and their include and menu paths
  1651. nodes = [item] if isinstance(item, MenuNode) else item.nodes
  1652. s = "Kconfig definition{}, with parent deps. propagated to 'depends on'\n" \
  1653. .format("s" if len(nodes) > 1 else "")
  1654. s += (len(s) - 1)*"="
  1655. for node in nodes:
  1656. s += "\n\n" \
  1657. "At {}:{}\n" \
  1658. "{}" \
  1659. "Menu path: {}\n\n" \
  1660. "{}" \
  1661. .format(node.filename, node.linenr,
  1662. _include_path_info(node),
  1663. _menu_path_info(node),
  1664. node.custom_str(_name_and_val_str))
  1665. return s
  1666. def _include_path_info(node):
  1667. if not node.include_path:
  1668. # In the top-level Kconfig file
  1669. return ""
  1670. return "Included via {}\n".format(
  1671. " -> ".join("{}:{}".format(filename, linenr)
  1672. for filename, linenr in node.include_path))
  1673. def _menu_path_info(node):
  1674. # Returns a string describing the menu path leading up to 'node'
  1675. path = ""
  1676. while node.parent is not _kconf.top_node:
  1677. node = node.parent
  1678. # Promptless choices might appear among the parents. Use
  1679. # standard_sc_expr_str() for them, so that they show up as
  1680. # '<choice (name if any)>'.
  1681. path = " -> " + (node.prompt[0] if node.prompt else
  1682. standard_sc_expr_str(node.item)) + path
  1683. return "(Top)" + path
  1684. def _name_and_val_str(sc):
  1685. # Custom symbol/choice printer that shows symbol values after symbols
  1686. # Show the values of non-constant (non-quoted) symbols that don't look like
  1687. # numbers. Things like 123 are actually symbol references, and only work as
  1688. # expected due to undefined symbols getting their name as their value.
  1689. # Showing the symbol value for those isn't helpful though.
  1690. if isinstance(sc, Symbol) and not sc.is_constant and not _is_num(sc.name):
  1691. if not sc.nodes:
  1692. # Undefined symbol reference
  1693. return "{}(undefined/n)".format(sc.name)
  1694. return '{}(={})'.format(sc.name, sc.str_value)
  1695. # For other items, use the standard format
  1696. return standard_sc_expr_str(sc)
  1697. def _expr_str(expr):
  1698. # Custom expression printer that shows symbol values
  1699. return expr_str(expr, _name_and_val_str)
  1700. def _is_num(name):
  1701. # Heuristic to see if a symbol name looks like a number, for nicer output
  1702. # when printing expressions. Things like 16 are actually symbol names, only
  1703. # they get their name as their value when the symbol is undefined.
  1704. try:
  1705. int(name)
  1706. except ValueError:
  1707. if not name.startswith(("0x", "0X")):
  1708. return False
  1709. try:
  1710. int(name, 16)
  1711. except ValueError:
  1712. return False
  1713. return True
  1714. if __name__ == "__main__":
  1715. _main()