-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathguiconfig.py
More file actions
executable file
·2899 lines (2206 loc) · 87.2 KB
/
guiconfig.py
File metadata and controls
executable file
·2899 lines (2206 loc) · 87.2 KB
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'). Requires Python 3.6+.
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.
A dark/light theme system provides a modern, professional appearance with a blue
color scheme. The interface automatically adapts to window resizing with a
responsive layout.
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-T : Toggle dark/light theme
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 re
from tkinter import *
from tkinter import ttk
from tkinter import 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,
_needs_save as _kconf_needs_save,
_extract_controlling_symbols,
)
# If True, use GIF image data embedded in this file instead of separate GIF
# files. See _load_images().
_USE_EMBEDDED_IMAGES = True
# Blue Theme Colors - Light Mode
CUSTOMTKINTER_LIGHT = {
"bg_primary": "#F9F9FA",
"bg_secondary": "#EBEBEC",
"bg_input": "#FFFFFF",
"fg_primary": "#1A1A1A",
"fg_secondary": "#4A4A4A",
"accent_primary": "#3B8ED0",
"accent_hover": "#36719F",
"accent_active": "#1F6AA5",
"button_bg": "#E0E0E0",
"button_fg": "#1A1A1A",
"button_active_bg": "#C0C0C0",
"tree_bg": "#FFFFFF",
"tree_select": "#3B8ED0",
"tree_select_fg": "#FFFFFF",
"tree_oddrow": "#F9F9FA",
"tree_evenrow": "#FFFFFF",
}
# Blue Theme Colors - Dark Mode
CUSTOMTKINTER_DARK = {
"bg_primary": "#2B2B2B",
"bg_secondary": "#1D1E1E",
"bg_input": "#343638",
"fg_primary": "#DCE4EE",
"fg_secondary": "#B0B0B0",
"accent_primary": "#1F6AA5",
"accent_hover": "#144870",
"accent_active": "#0C3150",
"button_bg": "#404040",
"button_fg": "#FFFFFF",
"button_active_bg": "#505050",
"tree_bg": "#2B2B2B",
"tree_select": "#1F6AA5",
"tree_select_fg": "#FFFFFF",
"tree_oddrow": "#2B2B2B",
"tree_evenrow": "#323232",
}
# Help text for the jump-to dialog
_JUMP_TO_HELP = """\
Type to search - results update as you type. Supports multiple strings/regexes
(space-separated) that must all match. Python's regex flavor is used (see 're'
module). Double-click an item to jump to it. Values can be toggled within the dialog.\
"""
class ThemeManager:
"""
Manages dark/light theme switching for guiconfig.
Uses hybrid approach: tk.Label for text (full color control) + ttk widgets for native look.
Compatible with macOS aqua theme.
"""
def __init__(self, root):
self.root = root
self.current_theme = "light"
self.colors = CUSTOMTKINTER_LIGHT
# Force use of 'clam' theme for consistent color control across platforms
# clam theme properly supports ttk widget styling unlike aqua theme
style = ttk.Style()
if "clam" in style.theme_names():
style.theme_use("clam")
def toggle(self):
"""Toggle between light and dark themes"""
self.set_theme("dark" if self.current_theme == "light" else "light")
def set_theme(self, theme_name):
"""Set specific theme: 'light' or 'dark'"""
self.current_theme = theme_name
self.colors = (
CUSTOMTKINTER_DARK if theme_name == "dark" else CUSTOMTKINTER_LIGHT
)
self.apply()
def apply(self):
"""Apply current theme to all widgets recursively"""
c = self.colors
# Update root window
self.root.configure(bg=c["bg_primary"])
# Use Tk option database to set default colors (works better than ttk styles on macOS)
self.root.option_add("*background", c["bg_primary"])
self.root.option_add("*foreground", c["fg_primary"])
self.root.option_add("*Frame.background", c["bg_primary"])
self.root.option_add("*Labelframe.background", c["bg_primary"])
self.root.option_add("*Label.background", c["bg_primary"])
self.root.option_add("*Label.foreground", c["fg_primary"])
# Update ttk styles first
style = ttk.Style()
# Standard ttk styles
style.configure("TFrame", background=c["bg_primary"])
style.configure(
"TLabelframe",
background=c["bg_primary"],
bordercolor=c["bg_primary"],
darkcolor=c["bg_primary"],
lightcolor=c["bg_primary"],
)
style.configure(
"TLabelframe.Label", background=c["bg_primary"], foreground=c["fg_primary"]
)
style.configure(
"TButton",
background=c["button_bg"],
foreground=c["button_fg"],
bordercolor=c["bg_primary"],
darkcolor=c["button_bg"],
lightcolor=c["button_bg"],
borderwidth=1,
focuscolor=c["button_bg"],
)
style.map(
"TButton",
background=[
("active", c["button_active_bg"]),
("pressed", c["button_active_bg"]),
],
foreground=[("active", c["button_fg"]), ("pressed", c["button_fg"])],
bordercolor=[("active", c["bg_primary"]), ("pressed", c["bg_primary"])],
darkcolor=[
("active", c["button_active_bg"]),
("pressed", c["button_active_bg"]),
],
lightcolor=[
("active", c["button_active_bg"]),
("pressed", c["button_active_bg"]),
],
)
style.configure(
"TLabel", background=c["bg_primary"], foreground=c["fg_primary"]
)
style.configure(
"TCheckbutton", background=c["bg_primary"], foreground=c["fg_primary"]
)
# Custom styles for widgets that don't respond to standard styles in aqua theme
style.configure("Custom.TFrame", background=c["bg_primary"])
style.configure(
"Custom.TLabel", background=c["bg_primary"], foreground=c["fg_primary"]
)
# Treeview styling (works well even in aqua)
style.configure(
"Treeview",
background=c["tree_bg"],
foreground=c["fg_primary"],
fieldbackground=c["tree_bg"],
)
style.map(
"Treeview",
background=[("selected", c["tree_select"])],
foreground=[("selected", c["tree_select_fg"])],
)
# Entry styling
style.configure(
"TEntry", fieldbackground=c["bg_input"], foreground=c["fg_primary"]
)
# Panedwindow styling
style.configure("TPanedwindow", background=c["bg_primary"])
# Update tree row colors
global _tree
if _tree:
_tree.tag_configure("oddrow", background=c["tree_oddrow"])
_tree.tag_configure("evenrow", background=c["tree_evenrow"])
# Update all tracked description Text widgets (main window + any
# open dialogs). Prune destroyed widgets while iterating.
live = set()
for w in _desc_texts:
if w.winfo_exists():
w.configure(bg=c["tree_bg"], fg=c["fg_primary"])
live.add(w)
_desc_texts.clear()
_desc_texts.update(live)
def _main():
menuconfig(standard_kconfig(__doc__))
# Global variables used below:
#
# _root:
# The Toplevel instance for the main window
#
# _theme_manager:
# ThemeManager instance for handling dark/light theme switching
#
# _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
#
# _theme_button:
# Button for toggling between light and dark themes
#
# _status_label:
# Label with status text shown at the bottom of the main window
# ("Modified", "Saved to ...", etc.)
#
# _stats_label:
# Label showing statistics (symbol count, changed count) in the status bar
#
# _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.
#
# _desc_texts:
# Set of description Text widgets (main window + open dialogs).
# Pruned of destroyed widgets during theme apply().
#
# _*_img:
# PhotoImage instances for images
# Initialized here because ThemeManager.apply() may be called before any
# tree/desc widgets exist.
_desc_texts = set()
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
global _tree_row_index
global _search_after_id
global _theme_manager
_kconf = kconf
# Clear cached node lists so they rebuild for the new Kconfig instance
_cached_sc_nodes.clear()
_cached_menu_comment_nodes.clear()
_jump_to_tree = None
_tree_row_index = 0
_search_after_id = None
_desc_texts.clear()
_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
children = _tree.get_children()
if children:
_select(_tree, 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(
f"+{(_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 prompt for saving the
# configuration if there are actual changes or if no .config file exists
# (so user can save the default configuration).
print(_kconf.load_config())
if not os.path.exists(_conf_filename):
# No .config exists - treat as changed so user can save defaults
return True
return _needs_save()
def _needs_save():
return _kconf_needs_save(_kconf)
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
global _theme_manager
# Create the root window. This initializes Tkinter and makes e.g.
# PhotoImage available, so do it early.
_root = Tk()
# Initialize theme manager early
_theme_manager = ThemeManager(_root)
_load_images()
_init_misc_ui()
_fix_treeview_issues()
_create_top_widgets()
_create_menubar()
# 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("<Control-t>", _toggle_theme)
_root.bind("/", _jump_to_dialog)
_root.bind("<Escape>", _on_quit)
# Apply initial theme (light mode by default) after all widgets are created
_theme_manager.apply()
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 = f"_{name}_img"
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",
"R0lGODlhMAAwAIEAAAAAADuO0AAAAAAAACH5BAkAAAAALAAAAAAwADAAQAjfAAEIHEiwYICCCBEeTMiwIYAAECNKnEhRokOBFTNCvIhRY0WCHjk2DDnQ40eOJimiTJlS5EqWKl0qhEkz4kWTMkGSNLgzJ06HNYPm5Bl041CgRm8mPZqwqE2mJZ1q9MmyaVWGV2VmjZoR6sOpM7tC7dnxp9aWWLdyNStSKlivbr1aXaiUrlydZ++GtTuX7924er8Chut2ItPCb18iTly2Zl2ajdk+lizZZWXBJw8zjmx47GbMMTWLJZr5KFnOnYdShnm2qtPJalEvtmh5dmqqs/8WDgzaMW/Mj393zCsyIAA7",
)
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)
_root.iconphoto(True, _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)
def _create_menubar():
# Creates the menu bar at the top of the window
# Note: This is called after _create_top_widgets() initializes the variables
menubar = Menu(_root)
_root.config(menu=menubar)
# File menu
file_menu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="Save", command=_save)
file_menu.add_command(label="Save As...", command=_save_as)
file_menu.add_command(label="Save Minimal...", command=_save_minimal)
file_menu.add_separator()
file_menu.add_command(label="Open...", command=_open)
file_menu.add_separator()
file_menu.add_command(label="Quit", command=_on_quit)
# Options menu
options_menu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Options", menu=options_menu)
options_menu.add_checkbutton(
label="Show Name",
variable=_show_name_var,
command=_do_showname,
)
options_menu.add_checkbutton(
label="Show All",
variable=_show_all_var,
command=_do_showall,
)
options_menu.add_checkbutton(
label="Single-Menu Mode",
variable=_single_menu_var,
command=_do_tree_mode,
)
# Theme menu
theme_menu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Theme", menu=theme_menu)
theme_menu.add_command(
label="Light Mode",
command=lambda: (_theme_manager.set_theme("light"), _update_tree()),
)
theme_menu.add_command(
label="Dark Mode",
command=lambda: (_theme_manager.set_theme("dark"), _update_tree()),
)
theme_menu.add_separator()
theme_menu.add_command(
label="Toggle (Ctrl+T)",
command=lambda: (_theme_manager.toggle(), _update_tree()),
)
def _create_top_widgets():
# Creates the controls above the Kconfig tree in the main window
# Also initializes the option variables used by the menu bar
global _show_all_var
global _show_name_var
global _single_menu_var
global _menupath
global _backbutton
# Initialize option variables first (needed by menubar)
_show_name_var = BooleanVar()
_show_all_var = BooleanVar()
_single_menu_var = BooleanVar()
# Use tk.Frame instead of ttk.Frame for better color control on macOS
topframe = Frame(_root, bg=_theme_manager.colors["bg_primary"])
topframe.grid(column=0, row=0, sticky="ew", padx=".1c", pady=".1c")
# Configure topframe columns to expand properly
topframe.columnconfigure(0, weight=1)
topframe.columnconfigure(1, weight=0)
topframe.columnconfigure(2, weight=0)
# Create button groups with separators
# File operations group
file_group = ttk.LabelFrame(topframe, text="File Operations")
file_group.grid(column=0, row=0, sticky="ew", padx="0 .1c")
# Create inner frame for consistent background
file_inner = ttk.Frame(file_group)
file_inner.pack(fill="both", expand=True, padx=5, pady=5)
# Configure column weights for responsive layout
for col in range(4):
file_inner.columnconfigure(col, weight=1)
ttk.Button(file_inner, text="Save", command=_save).grid(
column=0, row=0, sticky="ew", padx="2", pady="2"
)
ttk.Button(file_inner, text="Save as...", command=_save_as).grid(
column=1, row=0, sticky="ew", padx="2", pady="2"
)
ttk.Button(file_inner, text="Save minimal...", command=_save_minimal).grid(
column=2, row=0, sticky="ew", padx="2", pady="2"
)
ttk.Button(file_inner, text="Open...", command=_open).grid(
column=3, row=0, sticky="ew", padx="2", pady="2"
)
# Navigation group
nav_group = ttk.LabelFrame(topframe, text="Navigation")
nav_group.grid(column=1, row=0, sticky="ew", padx="0 .1c")
# Create inner frame for consistent background
nav_inner = ttk.Frame(nav_group)
nav_inner.pack(fill="both", expand=True, padx=5, pady=5)
ttk.Button(nav_inner, text="Jump to...", command=_jump_to_dialog, width=12).grid(
column=0, row=0, sticky="ew", padx="2", pady="2"
)
# View options group (includes theme toggle)
options_group = ttk.LabelFrame(topframe, text="View Options")
options_group.grid(column=0, row=1, columnspan=3, sticky="ew", pady=".1c 0")
# Create inner frame for consistent background
options_inner = ttk.Frame(options_group)
options_inner.pack(fill="both", expand=True, padx=5, pady=5)
# Configure column weights to ensure proper expansion
for col in range(3):
options_inner.columnconfigure(col, weight=1)
options_inner.columnconfigure(3, weight=0) # Theme button: fixed width
ttk.Checkbutton(
options_inner, text="Show name", command=_do_showname, variable=_show_name_var
).grid(column=0, row=0, sticky="w", padx="5", pady="2")
ttk.Checkbutton(
options_inner, text="Show all", command=_do_showall, variable=_show_all_var
).grid(column=1, row=0, sticky="w", padx="5", pady="2")
ttk.Checkbutton(
options_inner,
text="Single-menu mode",
command=_do_tree_mode,
variable=_single_menu_var,
).grid(column=2, row=0, sticky="w", padx="5", pady="2")
# Theme toggle button
global _theme_button
_theme_button = ttk.Button(
options_inner, text="☀ Light", command=lambda: _toggle_theme(None), width=12
)
_theme_button.grid(column=3, row=0, sticky="e", padx="5", pady="2")
# 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)
# Create integrated menu path bar with back button - use ttk.Frame for consistent theming
path_frame = ttk.Frame(topframe, relief="groove", borderwidth=1)
path_frame.grid(column=0, row=2, columnspan=3, sticky="ew", pady=".1c 0")
_backbutton = ttk.Button(
path_frame, text="\u25c0 Back", command=_leave_menu, state="disabled", width=8
)
_backbutton.pack(side="left", padx=2, pady=2)
_backbutton.pack_forget() # Initially hidden
def tree_mode_updated(*_):
global _single_menu
_single_menu = _single_menu_var.get()
if _single_menu:
_backbutton.pack(
side="left", padx=2, pady=2, before=path_frame.winfo_children()[1]
)
else:
_backbutton.pack_forget()
_trace_write(_single_menu_var, tree_mode_updated)
_single_menu_var.set(False)
# Use ttk.Label for consistent theming
path_label = ttk.Label(path_frame, text="Path:", font=("TkDefaultFont", 9, "bold"))
path_label.pack(side="left", padx=(10, 2))
_menupath = ttk.Label(path_frame, anchor="w", relief="flat")
_menupath.pack(side="left", fill="x", expand=True, padx=2, pady=2)
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)
# Register desc widget for theme updates (pruned automatically in apply())
_desc_texts.add(desc)
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
desc.replace("1.0", "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",))
# Configure column widths and headers
tree.column("#0", width=400, minwidth=200, stretch=True)
tree.column("name", width=200, minwidth=100, stretch=True)
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("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)
# Enhanced semantic color tags
tree.tag_configure("invisible", foreground="#cc0000") # Red for invisible items
tree.tag_configure("new-item", foreground="#0066cc") # Blue for NEW items
tree.tag_configure(
"menu-item", foreground="#006600"
) # Dark green for menu/choice items
# Alternating row colors (zebra striping) for better readability
# Colors will be set by ThemeManager.apply()
tree.tag_configure("oddrow")
tree.tag_configure("evenrow")
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",
bg=_theme_manager.colors["tree_bg"],
fg=_theme_manager.colors["fg_primary"],
)
desc.grid(column=0, row=0, sticky="nsew")
# Work around not being able 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.