-
Notifications
You must be signed in to change notification settings - Fork 160
/
guiconfig.py
executable file
·2324 lines (1715 loc) · 71.9 KB
/
guiconfig.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright (c) 2019, Ulf Magnusson
# SPDX-License-Identifier: ISC
"""
Overview
========
A Tkinter-based menuconfig implementation, based around a treeview control and
a help display. The interface should feel familiar to people used to qconf
('make xconfig'). Compatible with both Python 2 and Python 3.
The display can be toggled between showing the full tree and showing just a
single menu (like menuconfig.py). Only single-menu mode distinguishes between
symbols defined with 'config' and symbols defined with 'menuconfig'.
A show-all mode is available that shows invisible items in red.
Supports both mouse and keyboard controls. The following keyboard shortcuts are
available:
Ctrl-S : Save configuration
Ctrl-O : Open configuration
Ctrl-A : Toggle show-all mode
Ctrl-N : Toggle show-name mode
Ctrl-M : Toggle single-menu mode
Ctrl-F, /: Open jump-to dialog
ESC : Close
Running
=======
guiconfig.py can be run either as a standalone executable or by calling the
menuconfig() function with an existing Kconfig instance. The second option is a
bit inflexible in that it will still load and save .config, etc.
When run in standalone mode, the top-level Kconfig file to load can be passed
as a command-line argument. With no argument, it defaults to "Kconfig".
The KCONFIG_CONFIG environment variable specifies the .config file to load (if
it exists) and save. If KCONFIG_CONFIG is unset, ".config" is used.
When overwriting a configuration file, the old version is saved to
<filename>.old (e.g. .config.old).
$srctree is supported through Kconfiglib.
"""
# Note: There's some code duplication with menuconfig.py below, especially for
# the help text. Maybe some of it could be moved into kconfiglib.py or a shared
# helper script, but OTOH it's pretty nice to have things standalone and
# customizable.
import errno
import os
import sys
_PY2 = sys.version_info[0] < 3
if _PY2:
# Python 2
from Tkinter import *
import ttk
import tkFont as font
import tkFileDialog as filedialog
import tkMessageBox as messagebox
else:
# Python 3
from tkinter import *
import tkinter.ttk as ttk
import tkinter.font as font
from tkinter import filedialog, messagebox
from kconfiglib import Symbol, Choice, MENU, COMMENT, MenuNode, \
BOOL, TRISTATE, STRING, INT, HEX, \
AND, OR, \
expr_str, expr_value, split_expr, \
standard_sc_expr_str, \
TRI_TO_STR, TYPE_TO_STR, \
standard_kconfig, standard_config_filename
# If True, use GIF image data embedded in this file instead of separate GIF
# files. See _load_images().
_USE_EMBEDDED_IMAGES = True
# Help text for the jump-to dialog
_JUMP_TO_HELP = """\
Type one or more strings/regexes and press Enter to list items that match all
of them. Python's regex flavor is used (see the 're' module). Double-clicking
an item will jump to it. Item values can be toggled directly within the dialog.\
"""
def _main():
menuconfig(standard_kconfig(__doc__))
# Global variables used below:
#
# _root:
# The Toplevel instance for the main window
#
# _tree:
# The Treeview in the main window
#
# _jump_to_tree:
# The Treeview in the jump-to dialog. None if the jump-to dialog isn't
# open. Doubles as a flag.
#
# _jump_to_matches:
# List of Nodes shown in the jump-to dialog
#
# _menupath:
# The Label that shows the menu path of the selected item
#
# _backbutton:
# The button shown in single-menu mode for jumping to the parent menu
#
# _status_label:
# Label with status text shown at the bottom of the main window
# ("Modified", "Saved to ...", etc.)
#
# _id_to_node:
# We can't use Node objects directly as Treeview item IDs, so we use their
# id()s instead. This dictionary maps Node id()s back to Nodes. (The keys
# are actually str(id(node)), just to simplify lookups.)
#
# _cur_menu:
# The current menu. Ignored outside single-menu mode.
#
# _show_all_var/_show_name_var/_single_menu_var:
# Tkinter Variable instances bound to the corresponding checkboxes
#
# _show_all/_single_menu:
# Plain Python bools that track _show_all_var and _single_menu_var, to
# speed up and simplify things a bit
#
# _conf_filename:
# File to save the configuration to
#
# _minconf_filename:
# File to save minimal configurations to
#
# _conf_changed:
# True if the configuration has been changed. If False, we don't bother
# showing the save-and-quit dialog.
#
# We reset this to False whenever the configuration is saved.
#
# _*_img:
# PhotoImage instances for images
def menuconfig(kconf):
"""
Launches the configuration interface, returning after the user exits.
kconf:
Kconfig instance to be configured
"""
global _kconf
global _conf_filename
global _minconf_filename
global _jump_to_tree
global _cur_menu
_kconf = kconf
_jump_to_tree = None
_create_id_to_node()
_create_ui()
# Filename to save configuration to
_conf_filename = standard_config_filename()
# Load existing configuration and check if it's outdated
_set_conf_changed(_load_config())
# Filename to save minimal configuration to
_minconf_filename = "defconfig"
# Current menu in single-menu mode
_cur_menu = _kconf.top_node
# Any visible items in the top menu?
if not _shown_menu_nodes(kconf.top_node):
# Nothing visible. Start in show-all mode and try again.
_show_all_var.set(True)
if not _shown_menu_nodes(kconf.top_node):
# Give up and show an error. It's nice to be able to assume that
# the tree is non-empty in the rest of the code.
_root.wait_visibility()
messagebox.showerror(
"Error",
"Empty configuration -- nothing to configure.\n\n"
"Check that environment variables are set properly.")
_root.destroy()
return
# Build the initial tree
_update_tree()
# Select the first item and focus the Treeview, so that keyboard controls
# work immediately
_select(_tree, _tree.get_children()[0])
_tree.focus_set()
# Make geometry information available for centering the window. This
# indirectly creates the window, so hide it so that it's never shown at the
# old location.
_root.withdraw()
_root.update_idletasks()
# Center the window
_root.geometry("+{}+{}".format(
(_root.winfo_screenwidth() - _root.winfo_reqwidth())//2,
(_root.winfo_screenheight() - _root.winfo_reqheight())//2))
# Show it
_root.deiconify()
# Prevent the window from being automatically resized. Otherwise, it
# changes size when scrollbars appear/disappear before the user has
# manually resized it.
_root.geometry(_root.geometry())
_root.mainloop()
def _load_config():
# Loads any existing .config file. See the Kconfig.load_config() docstring.
#
# Returns True if .config is missing or outdated. We always prompt for
# saving the configuration in that case.
print(_kconf.load_config())
if not os.path.exists(_conf_filename):
# No .config
return True
return _needs_save()
def _needs_save():
# Returns True if a just-loaded .config file is outdated (would get
# modified when saving)
if _kconf.missing_syms:
# Assignments to undefined symbols in the .config
return True
for sym in _kconf.unique_defined_syms:
if sym.user_value is None:
if sym.config_string:
# Unwritten symbol
return True
elif sym.orig_type in (BOOL, TRISTATE):
if sym.tri_value != sym.user_value:
# Written bool/tristate symbol, new value
return True
elif sym.str_value != sym.user_value:
# Written string/int/hex symbol, new value
return True
# No need to prompt for save
return False
def _create_id_to_node():
global _id_to_node
_id_to_node = {str(id(node)): node for node in _kconf.node_iter()}
def _create_ui():
# Creates the main window UI
global _root
global _tree
# Create the root window. This initializes Tkinter and makes e.g.
# PhotoImage available, so do it early.
_root = Tk()
_load_images()
_init_misc_ui()
_fix_treeview_issues()
_create_top_widgets()
# Create the pane with the Kconfig tree and description text
panedwindow, _tree = _create_kconfig_tree_and_desc(_root)
panedwindow.grid(column=0, row=1, sticky="nsew")
_create_status_bar()
_root.columnconfigure(0, weight=1)
# Only the pane with the Kconfig tree and description grows vertically
_root.rowconfigure(1, weight=1)
# Start with show-name disabled
_do_showname()
_tree.bind("<Left>", _tree_left_key)
_tree.bind("<Right>", _tree_right_key)
# Note: Binding this for the jump-to tree as well would cause issues due to
# the Tk bug mentioned in _tree_open()
_tree.bind("<<TreeviewOpen>>", _tree_open)
# add=True to avoid overriding the description text update
_tree.bind("<<TreeviewSelect>>", _update_menu_path, add=True)
_root.bind("<Control-s>", _save)
_root.bind("<Control-o>", _open)
_root.bind("<Control-a>", _toggle_showall)
_root.bind("<Control-n>", _toggle_showname)
_root.bind("<Control-m>", _toggle_tree_mode)
_root.bind("<Control-f>", _jump_to_dialog)
_root.bind("/", _jump_to_dialog)
_root.bind("<Escape>", _on_quit)
def _load_images():
# Loads GIF images, creating the global _*_img PhotoImage variables.
# Base64-encoded images embedded in this script are used if
# _USE_EMBEDDED_IMAGES is True, and separate image files in the same
# directory as the script otherwise.
#
# Using a global variable indirectly prevents the image from being
# garbage-collected. Passing an image to a Tkinter function isn't enough to
# keep it alive.
def load_image(name, data):
var_name = "_{}_img".format(name)
if _USE_EMBEDDED_IMAGES:
globals()[var_name] = PhotoImage(data=data, format="gif")
else:
globals()[var_name] = PhotoImage(
file=os.path.join(os.path.dirname(__file__), name + ".gif"),
format="gif")
# Note: Base64 data can be put on the clipboard with
# $ base64 -w0 foo.gif | xclip
load_image("icon", "R0lGODlhMAAwAPEDAAAAAADQAO7u7v///yH5BAUKAAMALAAAAAAwADAAAAL/nI+gy+2Pokyv2jazuZxryQjiSJZmyXxHeLbumH6sEATvW8OLNtf5bfLZRLFITzgEipDJ4mYxYv6A0ubuqYhWk66tVTE4enHer7jcKvt0LLUw6P45lvEprT6c0+v7OBuqhYdHohcoqIbSAHc4ljhDwrh1UlgSydRCWWlp5wiYZvmSuSh4IzrqV6p4cwhkCsmY+nhK6uJ6t1mrOhuJqfu6+WYiCiwl7HtLjNSZZZis/MeM7NY3TaRKS40ooDeoiVqIultsrav92bi9c3a5KkkOsOJZpSS99m4k/0zPng4Gks9JSbB+8DIcoQfnjwpZCHv5W+ip4aQrKrB0uOikYhiMCBw1/uPoQUMBADs=")
load_image("n_bool", "R0lGODdhEAAQAPAAAAgICP///ywAAAAAEAAQAAACIISPacHtvp5kcb5qG85hZ2+BkyiRF8BBaEqtrKkqslEAADs=")
load_image("y_bool", "R0lGODdhEAAQAPEAAAgICADQAP///wAAACwAAAAAEAAQAAACMoSPacLtvlh4YrIYsst2cV19AvaVF9CUXBNJJoum7ymrsKuCnhiupIWjSSjAFuWhSCIKADs=")
load_image("n_tri", "R0lGODlhEAAQAPD/AAEBAf///yH5BAUKAAIALAAAAAAQABAAAAInlI+pBrAKQnCPSUlXvFhznlkfeGwjKZhnJ65h6nrfi6h0st2QXikFADs=")
load_image("m_tri", "R0lGODlhEAAQAPEDAAEBAeQMuv///wAAACH5BAUKAAMALAAAAAAQABAAAAI5nI+pBrAWAhPCjYhiAJQCnWmdoElHGVBoiK5M21ofXFpXRIrgiecqxkuNciZIhNOZFRNI24PhfEoLADs=")
load_image("y_tri", "R0lGODlhEAAQAPEDAAICAgDQAP///wAAACH5BAUKAAMALAAAAAAQABAAAAI0nI+pBrAYBhDCRRUypfmergmgZ4xjMpmaw2zmxk7cCB+pWiVqp4MzDwn9FhGZ5WFjIZeGAgA7")
load_image("m_my", "R0lGODlhEAAQAPEDAAAAAOQMuv///wAAACH5BAUKAAMALAAAAAAQABAAAAI5nIGpxiAPI2ghxFinq/ZygQhc94zgZopmOLYf67anGr+oZdp02emfV5n9MEHN5QhqICETxkABbQ4KADs=")
load_image("y_my", "R0lGODlhEAAQAPH/AAAAAADQAAPRA////yH5BAUKAAQALAAAAAAQABAAAAM+SArcrhCMSSuIM9Q8rxxBWIXawIBkmWonupLd565Um9G1PIs59fKmzw8WnAlusBYR2SEIN6DmAmqBLBxYSAIAOw==")
load_image("n_locked", "R0lGODlhEAAQAPABAAAAAP///yH5BAUKAAEALAAAAAAQABAAAAIgjB8AyKwN04pu0vMutpqqz4Hih4ydlnUpyl2r23pxUAAAOw==")
load_image("m_locked", "R0lGODlhEAAQAPD/AAAAAOQMuiH5BAUKAAIALAAAAAAQABAAAAIylC8AyKwN04ohnGcqqlZmfXDWI26iInZoyiore05walolV39ftxsYHgL9QBBMBGFEFAAAOw==")
load_image("y_locked", "R0lGODlhEAAQAPD/AAAAAADQACH5BAUKAAIALAAAAAAQABAAAAIylC8AyKzNgnlCtoDTwvZwrHydIYpQmR3KWq4uK74IOnp0HQPmnD3cOVlUIAgKsShkFAAAOw==")
load_image("not_selected", "R0lGODlhEAAQAPD/AAAAAP///yH5BAUKAAIALAAAAAAQABAAAAIrlA2px6IBw2IpWglOvTYhzmUbGD3kNZ5QqrKn2YrqigCxZoMelU6No9gdCgA7")
load_image("selected", "R0lGODlhEAAQAPD/AAAAAP///yH5BAUKAAIALAAAAAAQABAAAAIzlA2px6IBw2IpWglOvTah/kTZhimASJomiqonlLov1qptHTsgKSEzh9H8QI0QzNPwmRoFADs=")
load_image("edit", "R0lGODlhEAAQAPIFAAAAAKOLAMuuEPvXCvrxvgAAAAAAAAAAACH5BAUKAAUALAAAAAAQABAAAANCWLqw/gqMBp8cszJxcwVC2FEOEIAi5kVBi3IqWZhuCGMyfdpj2e4pnK+WAshmvxeAcETWlsxPkkBtsqBMa8TIBSQAADs=")
def _fix_treeview_issues():
# Fixes some Treeview issues
global _treeview_rowheight
style = ttk.Style()
# The treeview rowheight isn't adjusted automatically on high-DPI displays,
# so do it ourselves. The font will probably always be TkDefaultFont, but
# play it safe and look it up.
_treeview_rowheight = font.Font(font=style.lookup("Treeview", "font")) \
.metrics("linespace") + 2
style.configure("Treeview", rowheight=_treeview_rowheight)
# Work around regression in https://core.tcl.tk/tk/tktview?name=509cafafae,
# which breaks tag background colors
for option in "foreground", "background":
# Filter out any styles starting with ("!disabled", "!selected", ...).
# style.map() returns an empty list for missing options, so this should
# be future-safe.
style.map(
"Treeview",
**{option: [elm for elm in style.map("Treeview", query_opt=option)
if elm[:2] != ("!disabled", "!selected")]})
def _init_misc_ui():
# Does misc. UI initialization, like setting the title, icon, and theme
_root.title(_kconf.mainmenu_text)
# iconphoto() isn't available in Python 2's Tkinter
_root.tk.call("wm", "iconphoto", _root._w, "-default", _icon_img)
# Reducing the width of the window to 1 pixel makes it move around, at
# least on GNOME. Prevent weird stuff like that.
_root.minsize(128, 128)
_root.protocol("WM_DELETE_WINDOW", _on_quit)
# Use the 'clam' theme on *nix if it's available. It looks nicer than the
# 'default' theme.
if _root.tk.call("tk", "windowingsystem") == "x11":
style = ttk.Style()
if "clam" in style.theme_names():
style.theme_use("clam")
def _create_top_widgets():
# Creates the controls above the Kconfig tree in the main window
global _show_all_var
global _show_name_var
global _single_menu_var
global _menupath
global _backbutton
topframe = ttk.Frame(_root)
topframe.grid(column=0, row=0, sticky="ew")
ttk.Button(topframe, text="Save", command=_save) \
.grid(column=0, row=0, sticky="ew", padx=".05c", pady=".05c")
ttk.Button(topframe, text="Save as...", command=_save_as) \
.grid(column=1, row=0, sticky="ew")
ttk.Button(topframe, text="Save minimal (advanced)...",
command=_save_minimal) \
.grid(column=2, row=0, sticky="ew", padx=".05c")
ttk.Button(topframe, text="Open...", command=_open) \
.grid(column=3, row=0)
ttk.Button(topframe, text="Jump to...", command=_jump_to_dialog) \
.grid(column=4, row=0, padx=".05c")
_show_name_var = BooleanVar()
ttk.Checkbutton(topframe, text="Show name", command=_do_showname,
variable=_show_name_var) \
.grid(column=0, row=1, sticky="nsew", padx=".05c", pady="0 .05c",
ipady=".2c")
_show_all_var = BooleanVar()
ttk.Checkbutton(topframe, text="Show all", command=_do_showall,
variable=_show_all_var) \
.grid(column=1, row=1, sticky="nsew", pady="0 .05c")
# Allow the show-all and single-menu status to be queried via plain global
# Python variables, which is faster and simpler
def show_all_updated(*_):
global _show_all
_show_all = _show_all_var.get()
_trace_write(_show_all_var, show_all_updated)
_show_all_var.set(False)
_single_menu_var = BooleanVar()
ttk.Checkbutton(topframe, text="Single-menu mode", command=_do_tree_mode,
variable=_single_menu_var) \
.grid(column=2, row=1, sticky="nsew", padx=".05c", pady="0 .05c")
_backbutton = ttk.Button(topframe, text="<--", command=_leave_menu,
state="disabled")
_backbutton.grid(column=0, row=4, sticky="nsew", padx=".05c", pady="0 .05c")
def tree_mode_updated(*_):
global _single_menu
_single_menu = _single_menu_var.get()
if _single_menu:
_backbutton.grid()
else:
_backbutton.grid_remove()
_trace_write(_single_menu_var, tree_mode_updated)
_single_menu_var.set(False)
# Column to the right of the buttons that the menu path extends into, so
# that it can grow wider than the buttons
topframe.columnconfigure(5, weight=1)
_menupath = ttk.Label(topframe)
_menupath.grid(column=0, row=3, columnspan=6, sticky="w", padx="0.05c",
pady="0 .05c")
def _create_kconfig_tree_and_desc(parent):
# Creates a Panedwindow with a Treeview that shows Kconfig nodes and a Text
# that shows a description of the selected node. Returns a tuple with the
# Panedwindow and the Treeview. This code is shared between the main window
# and the jump-to dialog.
panedwindow = ttk.Panedwindow(parent, orient=VERTICAL)
tree_frame, tree = _create_kconfig_tree(panedwindow)
desc_frame, desc = _create_kconfig_desc(panedwindow)
panedwindow.add(tree_frame, weight=1)
panedwindow.add(desc_frame)
def tree_select(_):
# The Text widget does not allow editing the text in its disabled
# state. We need to temporarily enable it.
desc["state"] = "normal"
sel = tree.selection()
if not sel:
desc.delete("1.0", "end")
desc["state"] = "disabled"
return
# Text.replace() is not available in Python 2's Tkinter
desc.delete("1.0", "end")
desc.insert("end", _info_str(_id_to_node[sel[0]]))
desc["state"] = "disabled"
tree.bind("<<TreeviewSelect>>", tree_select)
tree.bind("<1>", _tree_click)
tree.bind("<Double-1>", _tree_double_click)
tree.bind("<Return>", _tree_enter)
tree.bind("<KP_Enter>", _tree_enter)
tree.bind("<space>", _tree_toggle)
tree.bind("n", _tree_set_val(0))
tree.bind("m", _tree_set_val(1))
tree.bind("y", _tree_set_val(2))
return panedwindow, tree
def _create_kconfig_tree(parent):
# Creates a Treeview for showing Kconfig nodes
frame = ttk.Frame(parent)
tree = ttk.Treeview(frame, selectmode="browse", height=20,
columns=("name",))
tree.heading("#0", text="Option", anchor="w")
tree.heading("name", text="Name", anchor="w")
tree.tag_configure("n-bool", image=_n_bool_img)
tree.tag_configure("y-bool", image=_y_bool_img)
tree.tag_configure("m-tri", image=_m_tri_img)
tree.tag_configure("n-tri", image=_n_tri_img)
tree.tag_configure("m-tri", image=_m_tri_img)
tree.tag_configure("y-tri", image=_y_tri_img)
tree.tag_configure("m-my", image=_m_my_img)
tree.tag_configure("y-my", image=_y_my_img)
tree.tag_configure("n-locked", image=_n_locked_img)
tree.tag_configure("m-locked", image=_m_locked_img)
tree.tag_configure("y-locked", image=_y_locked_img)
tree.tag_configure("not-selected", image=_not_selected_img)
tree.tag_configure("selected", image=_selected_img)
tree.tag_configure("edit", image=_edit_img)
tree.tag_configure("invisible", foreground="red")
tree.grid(column=0, row=0, sticky="nsew")
_add_vscrollbar(frame, tree)
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
# Create items for all menu nodes. These can be detached/moved later.
# Micro-optimize this a bit.
insert = tree.insert
id_ = id
Symbol_ = Symbol
for node in _kconf.node_iter():
item = node.item
insert("", "end", iid=id_(node),
values=item.name if item.__class__ is Symbol_ else "")
return frame, tree
def _create_kconfig_desc(parent):
# Creates a Text for showing the description of the selected Kconfig node
frame = ttk.Frame(parent)
desc = Text(frame, height=12, wrap="none", borderwidth=0,
state="disabled")
desc.grid(column=0, row=0, sticky="nsew")
# Work around not being to Ctrl-C/V text from a disabled Text widget, with a
# tip found in https://stackoverflow.com/questions/3842155/is-there-a-way-to-make-the-tkinter-text-widget-read-only
desc.bind("<1>", lambda _: desc.focus_set())
_add_vscrollbar(frame, desc)
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
return frame, desc
def _add_vscrollbar(parent, widget):
# Adds a vertical scrollbar to 'widget' that's only shown as needed
vscrollbar = ttk.Scrollbar(parent, orient="vertical",
command=widget.yview)
vscrollbar.grid(column=1, row=0, sticky="ns")
def yscrollcommand(first, last):
# Only show the scrollbar when needed. 'first' and 'last' are
# strings.
if float(first) <= 0.0 and float(last) >= 1.0:
vscrollbar.grid_remove()
else:
vscrollbar.grid()
vscrollbar.set(first, last)
widget["yscrollcommand"] = yscrollcommand
def _create_status_bar():
# Creates the status bar at the bottom of the main window
global _status_label
_status_label = ttk.Label(_root, anchor="e", padding="0 0 0.4c 0")
_status_label.grid(column=0, row=3, sticky="ew")
def _set_status(s):
# Sets the text in the status bar to 's'
_status_label["text"] = s
def _set_conf_changed(changed):
# Updates the status re. whether there are unsaved changes
global _conf_changed
_conf_changed = changed
if changed:
_set_status("Modified")
def _update_tree():
# Updates the Kconfig tree in the main window by first detaching all nodes
# and then updating and reattaching them. The tree structure might have
# changed.
# If a selected/focused item is detached and later reattached, it stays
# selected/focused. That can give multiple selections even though
# selectmode=browse. Save and later restore the selection and focus as a
# workaround.
old_selection = _tree.selection()
old_focus = _tree.focus()
# Detach all tree items before re-stringing them. This is relatively fast,
# luckily.
_tree.detach(*_id_to_node.keys())
if _single_menu:
_build_menu_tree()
else:
_build_full_tree(_kconf.top_node)
_tree.selection_set(old_selection)
_tree.focus(old_focus)
def _build_full_tree(menu):
# Updates the tree starting from menu.list, in full-tree mode. To speed
# things up, only open menus are updated. The menu-at-a-time logic here is
# to deal with invisible items that can show up outside show-all mode (see
# _shown_full_nodes()).
for node in _shown_full_nodes(menu):
_add_to_tree(node, _kconf.top_node)
# _shown_full_nodes() includes nodes from menus rooted at symbols, so
# we only need to check "real" menus/choices here
if node.list and not isinstance(node.item, Symbol):
if _tree.item(id(node), "open"):
_build_full_tree(node)
else:
# We're just probing here, so _shown_menu_nodes() will work
# fine, and might be a bit faster
shown = _shown_menu_nodes(node)
if shown:
# Dummy element to make the open/closed toggle appear
_tree.move(id(shown[0]), id(shown[0].parent), "end")
def _shown_full_nodes(menu):
# Returns the list of menu nodes shown in 'menu' (a menu node for a menu)
# for full-tree mode. A tricky detail is that invisible items need to be
# shown if they have visible children.
def rec(node):
res = []
while node:
if _visible(node) or _show_all:
res.append(node)
if node.list and isinstance(node.item, Symbol):
# Nodes from menu created from dependencies
res += rec(node.list)
elif node.list and isinstance(node.item, Symbol):
# Show invisible symbols (defined with either 'config' and
# 'menuconfig') if they have visible children. This can happen
# for an m/y-valued symbol with an optional prompt
# ('prompt "foo" is COND') that is currently disabled.
shown_children = rec(node.list)
if shown_children:
res.append(node)
res += shown_children
node = node.next
return res
return rec(menu.list)
def _build_menu_tree():
# Updates the tree in single-menu mode. See _build_full_tree() as well.
for node in _shown_menu_nodes(_cur_menu):
_add_to_tree(node, _cur_menu)
def _shown_menu_nodes(menu):
# Used for single-menu mode. Similar to _shown_full_nodes(), but doesn't
# include children of symbols defined with 'menuconfig'.
def rec(node):
res = []
while node:
if _visible(node) or _show_all:
res.append(node)
if node.list and not node.is_menuconfig:
res += rec(node.list)
elif node.list and isinstance(node.item, Symbol):
shown_children = rec(node.list)
if shown_children:
# Invisible item with visible children
res.append(node)
if not node.is_menuconfig:
res += shown_children
node = node.next
return res
return rec(menu.list)
def _visible(node):
# Returns True if the node should appear in the menu (outside show-all
# mode)
return node.prompt and expr_value(node.prompt[1]) and not \
(node.item == MENU and not expr_value(node.visibility))
def _add_to_tree(node, top):
# Adds 'node' to the tree, at the end of its menu. We rely on going through
# the nodes linearly to get the correct order. 'top' holds the menu that
# corresponds to the top-level menu, and can vary in single-menu mode.
parent = node.parent
_tree.move(id(node), "" if parent is top else id(parent), "end")
_tree.item(
id(node),
text=_node_str(node),
# The _show_all test avoids showing invisible items in red outside
# show-all mode, which could look confusing/broken. Invisible symbols
# are shown outside show-all mode if an invisible symbol has visible
# children in an implicit menu.
tags=_img_tag(node) if _visible(node) or not _show_all else
_img_tag(node) + " invisible")
def _node_str(node):
# Returns the string shown to the right of the image (if any) for the node
if node.prompt:
if node.item == COMMENT:
s = "*** {} ***".format(node.prompt[0])
else:
s = node.prompt[0]
if isinstance(node.item, Symbol):
sym = node.item
# Print "(NEW)" next to symbols without a user value (from e.g. a
# .config), but skip it for choice symbols in choices in y mode,
# and for symbols of UNKNOWN type (which generate a warning though)
if sym.user_value is None and sym.type and not \
(sym.choice and sym.choice.tri_value == 2):
s += " (NEW)"
elif isinstance(node.item, Symbol):
# Symbol without prompt (can show up in show-all)
s = "<{}>".format(node.item.name)
else:
# Choice without prompt. Use standard_sc_expr_str() so that it shows up
# as '<choice (name if any)>'.
s = standard_sc_expr_str(node.item)
if isinstance(node.item, Symbol):
sym = node.item
if sym.orig_type == STRING:
s += ": " + sym.str_value
elif sym.orig_type in (INT, HEX):
s = "({}) {}".format(sym.str_value, s)
elif isinstance(node.item, Choice) and node.item.tri_value == 2:
# Print the prompt of the selected symbol after the choice for
# choices in y mode
sym = node.item.selection
if sym:
for sym_node in sym.nodes:
# Use the prompt used at this choice location, in case the
# choice symbol is defined in multiple locations
if sym_node.parent is node and sym_node.prompt:
s += " ({})".format(sym_node.prompt[0])
break
else:
# If the symbol isn't defined at this choice location, then
# just use whatever prompt we can find for it
for sym_node in sym.nodes:
if sym_node.prompt:
s += " ({})".format(sym_node.prompt[0])
break
# In single-menu mode, print "--->" next to nodes that have menus that can
# potentially be entered. Print "----" if the menu is empty. We don't allow
# those to be entered.
if _single_menu and node.is_menuconfig:
s += " --->" if _shown_menu_nodes(node) else " ----"
return s
def _img_tag(node):
# Returns the tag for the image that should be shown next to 'node', or the
# empty string if it shouldn't have an image
item = node.item
if item in (MENU, COMMENT) or not item.orig_type:
return ""
if item.orig_type in (STRING, INT, HEX):
return "edit"
# BOOL or TRISTATE
if _is_y_mode_choice_sym(item):
# Choice symbol in y-mode choice
return "selected" if item.choice.selection is item else "not-selected"
if len(item.assignable) <= 1:
# Pinned to a single value
return "" if isinstance(item, Choice) else item.str_value + "-locked"
if item.type == BOOL:
return item.str_value + "-bool"
# item.type == TRISTATE
if item.assignable == (1, 2):
return item.str_value + "-my"
return item.str_value + "-tri"
def _is_y_mode_choice_sym(item):
# The choice mode is an upper bound on the visibility of choice symbols, so
# we can check the choice symbols' own visibility to see if the choice is
# in y mode
return isinstance(item, Symbol) and item.choice and item.visibility == 2
def _tree_click(event):
# Click on the Kconfig Treeview
tree = event.widget
if tree.identify_element(event.x, event.y) == "image":
item = tree.identify_row(event.y)
# Select the item before possibly popping up a dialog for
# string/int/hex items, so that its help is visible
_select(tree, item)
_change_node(_id_to_node[item], tree.winfo_toplevel())
return "break"
def _tree_double_click(event):
# Double-click on the Kconfig treeview
# Do an extra check to avoid weirdness when double-clicking in the tree
# heading area
if not _in_heading(event):
return _tree_enter(event)
def _in_heading(event):
# Returns True if 'event' took place in the tree heading
tree = event.widget
return hasattr(tree, "identify_region") and \
tree.identify_region(event.x, event.y) in ("heading", "separator")
def _tree_enter(event):
# Enter press or double-click within the Kconfig treeview. Prefer to
# open/close/enter menus, but toggle the value if that's not possible.
tree = event.widget
sel = tree.focus()
if sel:
node = _id_to_node[sel]
if tree.get_children(sel):
_tree_toggle_open(sel)
elif _single_menu_mode_menu(node, tree):
_enter_menu_and_select_first(node)
else:
_change_node(node, tree.winfo_toplevel())
return "break"
def _tree_toggle(event):
# Space press within the Kconfig treeview. Prefer to toggle the value, but
# open/close/enter the menu if that's not possible.
tree = event.widget
sel = tree.focus()
if sel:
node = _id_to_node[sel]
if _changeable(node):
_change_node(node, tree.winfo_toplevel())
elif _single_menu_mode_menu(node, tree):
_enter_menu_and_select_first(node)
elif tree.get_children(sel):
_tree_toggle_open(sel)
return "break"
def _tree_left_key(_):
# Left arrow key press within the Kconfig treeview
if _single_menu:
# Leave the current menu in single-menu mode
_leave_menu()
return "break"
# Otherwise, default action
def _tree_right_key(_):
# Right arrow key press within the Kconfig treeview
sel = _tree.focus()
if sel:
node = _id_to_node[sel]
# If the node can be entered in single-menu mode, do it
if _single_menu_mode_menu(node, _tree):
_enter_menu_and_select_first(node)
return "break"
# Otherwise, default action
def _single_menu_mode_menu(node, tree):
# Returns True if single-menu mode is on and 'node' is an (interface)
# menu that can be entered
return _single_menu and tree is _tree and node.is_menuconfig and \
_shown_menu_nodes(node)
def _changeable(node):
# Returns True if 'node' is a Symbol/Choice whose value can be changed
sc = node.item
if not isinstance(sc, (Symbol, Choice)):
return False
# This will hit for invisible symbols, which appear in show-all mode and