guiconfig.py 72 KB

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