forked from thonny/thonny
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui_utils.py
More file actions
2794 lines (2216 loc) · 88.8 KB
/
Copy pathui_utils.py
File metadata and controls
2794 lines (2216 loc) · 88.8 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
# -*- coding: utf-8 -*-
import os
import platform
import re
import subprocess
import sys
import textwrap
import threading
import time
import tkinter as tk
import tkinter.font
import traceback
from dataclasses import dataclass
from logging import getLogger
from tkinter import filedialog, messagebox, ttk
from typing import Any, Callable, Dict, List, Literal, Optional, Tuple, Union # @UnusedImport
from _tkinter import TclError
from pystart import get_workbench, misc_utils, tktextext
from pystart.common import TextRange, normpath_with_actual_case
from pystart.custom_notebook import CustomNotebook, CustomNotebookPage
from pystart.languages import get_button_padding, tr
from pystart.misc_utils import running_on_linux, running_on_mac_os, running_on_windows
from pystart.tktextext import TweakableText
PARENS_REGEX = re.compile(r"[\(\)\{\}\[\]]")
logger = getLogger(__name__)
# Using tk.Frame instead of ttk.Frame, because Aqua theme doesn't allow changing Frame background
class CustomToolbutton(tk.Frame):
def __init__(
self,
master,
command: Callable = None,
style: Optional[str] = None,
image=None,
state="normal",
text=None,
compound=None,
width=None,
pad=None,
font=None,
background=None,
foreground=None,
borderwidth=0,
):
if isinstance(image, (list, tuple)):
self.normal_image = image[0]
self.disabled_image = image[-1]
else:
self.normal_image = image
self.disabled_image = image
self.state = state
self.style = style
self.background = background
self.foreground = foreground
self.prepare_style_options()
if state == "disabled":
self.current_image = self.disabled_image
else:
self.current_image = self.normal_image
super().__init__(
master, background=self.normal_background, borderwidth=borderwidth, relief="solid"
)
kw = {}
if font is not None:
kw["font"] = font
self.label = tk.Label(
self,
image=self.current_image,
text=text,
compound=compound,
width=None if width is None else ems_to_pixels(width - 1),
background=self.normal_background,
foreground=self.normal_foreground,
**kw,
)
# TODO: introduce padx and pady arguments
if isinstance(pad, int):
padx = pad
pady = pad
elif isinstance(pad, (tuple, list)):
assert len(pad) == 2
# TODO: how to use it?
padx = pad
pady = 0
else:
padx = None
pady = None
if text and not image:
# text only button content needs adjustment
pady = pady or 0
pady = (pady, pady + ems_to_pixels(0.23))
self.label.grid(row=0, column=0, padx=padx, pady=pady, sticky="nsew")
self.command = command
self.bind("<1>", self.on_click, True)
self.label.bind("<1>", self.on_click, True)
self.bind("<Enter>", self.on_enter, True)
self.label.bind("<Enter>", self.on_enter, True)
self.bind("<Leave>", self.on_leave, True)
self.label.bind("<Leave>", self.on_leave, True)
# 确保整个按钮区域都能触发事件
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
# 设置默认光标为手型
self.configure(cursor="hand2")
self.label.configure(cursor="hand2")
self._on_theme_changed_binding = self.bind("<<ThemeChanged>>", self.on_theme_changed, True)
def cget(self, key: str) -> Any:
if key in ["text", "image"]:
return self.label.cget(key)
else:
return super().cget(key)
def on_click(self, event):
if self.state == "normal":
self.command()
def on_enter(self, event):
if self.state == "normal":
super().configure(background=self.hover_background)
self.label.configure(background=self.hover_background)
# 调试信息
# print(f"Mouse entered button: {event.widget}")
def on_leave(self, event):
super().configure(background=self.normal_background)
self.label.configure(background=self.normal_background)
def configure(self, cnf={}, state=None, image=None, command=None, background=None, **kw):
if command:
self.command = command
if "state" in cnf and not state:
state = cnf.get("state")
elif not state:
state = "normal"
self.state = state
if image:
self.current_image = image
elif self.state == "disabled":
self.current_image = self.disabled_image
else:
self.current_image = self.normal_image
super().configure(background=background)
# tkinter.Frame should be always state=normal as it won't display the image if "disabled"
# at least on mac with Tk 8.6.13
self.label.configure(
cnf, image=self.current_image, state="normal", background=background, **kw
)
def on_theme_changed(self, event):
self.prepare_style_options()
self.configure(background=self.normal_background, foreground=self.normal_foreground)
def prepare_style_options(self):
style_conf = get_style_configuration("CustomToolbutton")
if self.style:
style_conf |= get_style_configuration(self.style)
self.normal_background = self.background or style_conf["background"]
self.normal_foreground = self.foreground or style_conf["foreground"]
self.hover_background = style_conf["activebackground"]
def destroy(self):
if not get_workbench().is_closing():
try:
self.unbind("<<ThemeChanged>>", self._on_theme_changed_binding)
except Exception:
pass
super().destroy()
class CommonDialog(tk.Toplevel):
def __init__(self, master=None, skip_tk_dialog_attributes=False, **kw):
assert master
super().__init__(master=master, class_="PyStart", **kw)
self.withdraw() # remain invisible until size calculations are done
# Opening a dialog and minimizing everything with Win-D in Windows makes the main
# window and dialog stuck. This is a work-around.
self.bind("<FocusIn>", self._unlock_on_focus_in, True)
if not skip_tk_dialog_attributes:
# https://bugs.python.org/issue43655
if self._windowingsystem == "aqua":
self.tk.call(
"::tk::unsupported::MacWindowStyle", "style", self, "moveableModal", "closeBox"
)
elif self._windowingsystem == "x11":
self.wm_attributes("-type", "dialog")
self.resizable(True, True)
self.parent = master
def _unlock_on_focus_in(self, event):
if not self.winfo_ismapped():
focussed_widget = self.focus_get()
self.deiconify()
if focussed_widget:
focussed_widget.focus_set()
def get_large_padding(self):
return ems_to_pixels(1.5)
def get_medium_padding(self):
return ems_to_pixels(1)
def get_small_padding(self):
return ems_to_pixels(0.6)
def set_initial_focus(self, node=None) -> bool:
if node is None:
node = self
if isinstance(
node,
(
ttk.Entry,
ttk.Combobox,
ttk.Treeview,
tk.Text,
ttk.Notebook,
CustomNotebook,
ttk.Button,
tk.Listbox,
),
):
node.focus_set()
return True
else:
for child in node.winfo_children():
if self.set_initial_focus(child):
return True
return False
class CommonDialogEx(CommonDialog):
def __init__(self, master=None, **kw):
super().__init__(master=master, **kw)
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
# Need to fill the dialog with a frame to gain theme support
self.main_frame = ttk.Frame(self)
# ipady doesn't work right, at least on Linux (it only applies to the first gridded child)
# therefore only providing common padding for left and right edges
self.main_frame.grid(row=0, column=0, sticky="nsew", ipadx=self.get_large_padding())
self.main_frame.rowconfigure(0, weight=1)
self.main_frame.columnconfigure(0, weight=1)
self.bind("<Escape>", self.on_close, True)
self.protocol("WM_DELETE_WINDOW", self.on_close)
def on_close(self, event=None):
self.destroy()
class QueryDialog(CommonDialogEx):
def __init__(
self,
master,
title: str,
prompt: str,
initial_value: str = "",
options: List[str] = [],
entry_width: Optional[int] = None,
):
super().__init__(master)
self.var = tk.StringVar(value=initial_value)
self.result = None
margin = self.get_large_padding()
spacing = margin // 2
self.title(title)
self.prompt_label = ttk.Label(self.main_frame, text=prompt)
self.prompt_label.grid(row=1, column=1, columnspan=2, padx=margin, pady=(margin, spacing))
if options:
self.entry_widget = ttk.Combobox(
self.main_frame, textvariable=self.var, values=options, height=15, width=entry_width
)
else:
self.entry_widget = ttk.Entry(self.main_frame, textvariable=self.var, width=entry_width)
self.entry_widget.bind("<Return>", self.on_ok, True)
self.entry_widget.bind("<KP_Enter>", self.on_ok, True)
self.entry_widget.grid(
row=3, column=1, columnspan=2, sticky="we", padx=margin, pady=(0, margin)
)
self.ok_button = ttk.Button(
self.main_frame, text=tr("OK"), command=self.on_ok, default="active"
)
self.ok_button.grid(row=5, column=1, padx=(margin, spacing), pady=(0, margin), sticky="e")
self.cancel_button = ttk.Button(self.main_frame, text=tr("Cancel"), command=self.on_cancel)
self.cancel_button.grid(row=5, column=2, padx=(0, margin), pady=(0, margin), sticky="e")
self.main_frame.columnconfigure(1, weight=1)
self.entry_widget.focus_set()
def on_ok(self, event=None):
self.result = self.var.get()
self.destroy()
def on_cancel(self, event=None):
self.result = None
self.destroy()
def get_result(self) -> Optional[str]:
return self.result
def ask_string(
title: str,
prompt: str,
initial_value: str = "",
options: List[str] = [],
entry_width: Optional[int] = None,
master=None,
):
dlg = QueryDialog(
master, title, prompt, initial_value=initial_value, options=options, entry_width=entry_width
)
show_dialog(dlg, master)
return dlg.get_result()
class CustomMenubar(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master, style="CustomMenubar.TFrame")
self._menus = []
self._opened_menu = None
ttk.Style().map(
"CustomMenubarLabel.TLabel",
background=[
("!active", lookup_style_option("Menubar", "background", "gray")),
("active", lookup_style_option("Menubar", "activebackground", "LightYellow")),
],
foreground=[
("!active", lookup_style_option("Menubar", "foreground", "black")),
("active", lookup_style_option("Menubar", "activeforeground", "black")),
],
)
def add_cascade(self, label, menu):
label_widget = ttk.Label(
self,
style="CustomMenubarLabel.TLabel",
text=label,
padding=[6, 3, 6, 2],
font="TkDefaultFont",
)
if len(self._menus) == 0:
padx = (6, 0)
else:
padx = 0
label_widget.grid(row=0, column=len(self._menus), padx=padx)
def enter(event):
label_widget.state(("active",))
# Don't know how to open this menu when another menu is open
# another tk_popup just doesn't work unless old menu is closed by click or Esc
# https://stackoverflow.com/questions/38081470/is-there-a-way-to-know-if-tkinter-optionmenu-dropdown-is-active
# unpost doesn't work in Win and Mac: https://www.tcl.tk/man/tcl8.5/TkCmd/menu.htm#M62
# print("ENTER", menu, self._opened_menu)
if self._opened_menu is not None:
self._opened_menu.unpost()
click(event)
def leave(event):
label_widget.state(("!active",))
def click(event):
try:
# print("Before")
self._opened_menu = menu
menu.tk_popup(
label_widget.winfo_rootx(),
label_widget.winfo_rooty() + label_widget.winfo_height(),
)
finally:
# print("After")
self._opened_menu = None
label_widget.bind("<Enter>", enter, True)
label_widget.bind("<Leave>", leave, True)
label_widget.bind("<1>", click, True)
self._menus.append(menu)
class WorkbenchPanedWindow(tk.PanedWindow):
def __init__(
self,
master: tk.Widget,
orient: Literal["horizontal", "vertical"],
size_config_key: Optional[str] = None,
):
self.size_config_key = size_config_key
super().__init__(master, orient=orient)
self._update_appearance_binding = self.bind(
"<<ThemeChanged>>", self._update_appearance, True
)
self._update_appearance()
def all_children_hidden(self):
for child in self.panes():
if not self.panecget(child, "hide"):
return False
return True
def update_visibility(self):
if isinstance(self.master, tk.PanedWindow):
should_be_hidden = self.all_children_hidden()
if self.winfo_ismapped() and should_be_hidden and self.size_config_key is not None:
if self.cget("orient") == "vertical":
value = self.winfo_width()
else:
value = self.winfo_height()
get_workbench().set_option(self.size_config_key, value)
self.master.paneconfig(self, hide=should_be_hidden)
def _update_appearance(self, event=None):
self.configure(sashwidth=lookup_style_option("Sash", "sashthickness", ems_to_pixels(0.6)))
self.configure(background=lookup_style_option(".", "background"))
def destroy(self):
self.unbind("<<ThemeChanged>>", self._update_appearance_binding)
super().destroy()
def has_several_visible_panes(self):
count = 0
for child in self.winfo_children():
if child.winfo_ismapped():
count += 1
return count > 1
class ViewNotebook(CustomNotebook):
"""
Enables inserting views according to their position keys.
Remember its own position key. Automatically updates its visibility.
"""
def __init__(self, master, location_in_workbench, position_key):
self.location_in_workbench = location_in_workbench
if get_workbench().in_simple_mode():
closable = False
else:
closable = True
super().__init__(master, closable=closable)
self.position_key = position_key
def forget(self, child: tk.Widget) -> None:
if (
isinstance(self.master, WorkbenchPanedWindow)
and self.master.has_several_visible_panes()
):
close_height = self.winfo_height()
get_workbench().set_option(
f"layout.{self.location_in_workbench}_nb_height", close_height
)
super().forget(child)
def after_insert(
self,
pos: Union[int, Literal["end"]],
page: CustomNotebookPage,
old_notebook: Optional[CustomNotebook],
) -> None:
super().after_insert(pos, page, old_notebook)
self._update_visibility()
if old_notebook is None:
get_workbench().event_generate("NotebookPageOpened", page=page)
else:
get_workbench().event_generate(
"NotebookPageMoved", page=page, new_notebook=self, old_notebook=old_notebook
)
def after_forget(
self, pos: int, page: CustomNotebookPage, new_notebook: Optional[CustomNotebook]
):
# see the comment at after_add_or_insert
super().after_forget(pos, page, new_notebook)
self._update_visibility()
if new_notebook is None:
get_workbench().event_generate("NotebookPageClosed", page=page)
# if there is new_notebook, then Workbench gets its Moved event from it
def _is_visible(self):
return self.winfo_ismapped()
def _update_visibility(self):
if isinstance(self.master, WorkbenchPanedWindow):
if len(self.tabs()) == 0 and self._is_visible():
self.master.paneconfig(self, hide=True)
if len(self.tabs()) > 0 and not self._is_visible():
self.master.paneconfig(self, hide=False)
self.master.update_visibility()
def allows_dragging_to_another_notebook(self) -> bool:
return True
class TreeFrame(ttk.Frame):
def __init__(
self,
master,
columns,
displaycolumns="#all",
show_scrollbar=True,
show_statusbar=False,
borderwidth=0,
relief="flat",
consider_heading_stripe=True,
**tree_kw,
):
ttk.Frame.__init__(self, master, borderwidth=borderwidth, relief=relief)
self.vert_scrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL)
if show_scrollbar:
self.vert_scrollbar.grid(
row=0, column=1, sticky=tk.NSEW, rowspan=2 if show_statusbar else 1
)
scrollbar_stripe = check_create_aqua_scrollbar_stripe(self)
if scrollbar_stripe is not None:
scrollbar_stripe.grid(
row=0, column=1, sticky="nse", rowspan=2 if show_statusbar else 1
)
scrollbar_stripe.tkraise()
self.tree = ttk.Treeview(
self,
columns=columns,
displaycolumns=displaycolumns,
yscrollcommand=self.vert_scrollbar.set,
**tree_kw,
)
self.tree["show"] = "headings"
self.tree.grid(row=0, column=0, sticky=tk.NSEW)
if consider_heading_stripe:
heading_stripe = check_create_heading_stripe(self)
if heading_stripe is not None:
heading_stripe.grid(row=0, column=0, sticky="new")
heading_stripe.tkraise()
self.vert_scrollbar["command"] = self.tree.yview
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.tree.bind("<<TreeviewSelect>>", self.on_select, "+")
self.tree.bind("<Double-Button-1>", self.on_double_click, "+")
self.tree.bind("<Button-3>", self.on_secondary_click, True)
if misc_utils.running_on_mac_os():
self.tree.bind("<2>", self.on_secondary_click, True)
self.tree.bind("<Control-1>", self.on_secondary_click, True)
self.context_menu = tk.Menu(self.tree, tearoff=0)
self.context_menu.add_command(command=self.on_copy, label="Copy")
self.error_label = ttk.Label(self.tree)
if show_statusbar:
self.statusbar = ttk.Frame(self)
self.statusbar.grid(row=1, column=0, sticky="nswe")
else:
self.statusbar = None
def _clear_tree(self):
for child_id in self.tree.get_children():
self.tree.delete(child_id)
def clear(self):
self._clear_tree()
def on_secondary_click(self, event):
self.tree.identify_row(event.y)
self.context_menu.post(event.x_root, event.y_root)
def on_copy(self):
texts = []
for item in self.tree.selection():
text = self.tree.item(item, option="text")
values = map(str, self.tree.item(item, option="values"))
combined = text + "\t" + "\t".join(values)
texts.append(combined.strip("\t"))
self.clipboard_clear()
self.clipboard_append(os.linesep.join(texts))
def on_select(self, event):
pass
def on_double_click(self, event):
pass
def show_error(self, error_text):
self.error_label.configure(text=error_text)
self.error_label.grid()
def clear_error(self):
self.error_label.grid_remove()
def sequence_to_accelerator(sequence):
"""Translates Tk event sequence to customary shortcut string
for showing in the menu"""
if not sequence:
return ""
if not sequence.startswith("<"):
return sequence
accelerator = (
sequence.strip("<>").replace("Key-", "").replace("KeyPress-", "").replace("Control", "Ctrl")
)
# Tweaking individual parts
parts = accelerator.split("-")
# tkinter shows shift with capital letter, but in shortcuts it's customary to include it explicitly
if len(parts[-1]) == 1 and parts[-1].isupper() and not "Shift" in parts:
parts.insert(-1, "Shift")
# even when shift is not required, it's customary to show shortcut with capital letter
if len(parts[-1]) == 1:
parts[-1] = parts[-1].upper()
accelerator = "+".join(parts)
# Post processing
accelerator = (
accelerator.replace("Minus", "-")
.replace("minus", "-")
.replace("Plus", "+")
.replace("plus", "+")
.replace("space", "Space")
)
return accelerator
def get_zoomed(toplevel):
if "-zoomed" in toplevel.wm_attributes(): # Linux
return bool(toplevel.wm_attributes("-zoomed"))
else: # Win/Mac
return toplevel.wm_state() == "zoomed"
def set_zoomed(toplevel, value):
if "-zoomed" in toplevel.wm_attributes(): # Linux
toplevel.wm_attributes("-zoomed", str(int(value)))
else: # Win/Mac
if value:
toplevel.wm_state("zoomed")
else:
toplevel.wm_state("normal")
class EnhancedTextWithLogging(tktextext.EnhancedText):
def __init__(
self,
master,
indent_width: int,
tab_width: int,
style="Text",
tag_current_line=False,
cnf={},
**kw,
):
super().__init__(
master=master,
indent_width=indent_width,
tab_width=tab_width,
style=style,
tag_current_line=tag_current_line,
cnf=cnf,
**kw,
)
self._last_event_changed_line_count = False
def direct_insert(self, index, chars, tags=None, **kw):
# try removing line numbers
# TODO: shouldn't it take place only on paste?
# TODO: does it occur when opening a file with line numbers in it?
# if self._propose_remove_line_numbers and isinstance(chars, str):
# chars = try_remove_linenumbers(chars, self)
concrete_index = self.index(index)
line_before = self.get(concrete_index + " linestart", concrete_index + " lineend")
self._last_event_changed_line_count = "\n" in chars
result = tktextext.EnhancedText.direct_insert(self, index, chars, tags=tags, **kw)
line_after = self.get(concrete_index + " linestart", concrete_index + " lineend")
trivial_for_coloring, trivial_for_parens = self._is_trivial_edit(
chars, line_before, line_after
)
if not self._suppress_events:
get_workbench().event_generate(
"TextInsert",
index=concrete_index,
text=chars,
tags=tags,
text_widget=self,
trivial_for_coloring=trivial_for_coloring,
trivial_for_parens=trivial_for_parens,
)
return result
def direct_delete(self, index1, index2=None, **kw):
try:
# index1 may be eg "sel.first" and it doesn't make sense *after* deletion
concrete_index1 = self.index(index1)
if index2 is not None:
concrete_index2 = self.index(index2)
else:
concrete_index2 = self.index(index1 + " +1c")
chars = self.get(index1, index2)
self._last_event_changed_line_count = "\n" in chars
line_before = self.get(
concrete_index1 + " linestart",
(concrete_index1 if concrete_index2 is None else concrete_index2) + " lineend",
)
return tktextext.EnhancedText.direct_delete(self, index1, index2=index2, **kw)
finally:
line_after = self.get(
concrete_index1 + " linestart",
(concrete_index1 if concrete_index2 is None else concrete_index2) + " lineend",
)
trivial_for_coloring, trivial_for_parens = self._is_trivial_edit(
chars, line_before, line_after
)
if not self._suppress_events:
get_workbench().event_generate(
"TextDelete",
index1=concrete_index1,
index2=concrete_index2,
text_widget=self,
trivial_for_coloring=trivial_for_coloring,
trivial_for_parens=trivial_for_parens,
)
def _is_trivial_edit(self, chars, line_before, line_after):
# line is taken after edit for insertion and before edit for deletion
if not chars.strip():
# linebreaks, including with automatic indent
# check it doesn't break a triple-quote
trivial_for_coloring = line_before.count("'''") == line_after.count(
"'''"
) and line_before.count('"""') == line_after.count('"""')
trivial_for_parens = trivial_for_coloring
elif len(chars) > 1:
# paste, cut, load or something like this
trivial_for_coloring = False
trivial_for_parens = False
elif chars == "#":
trivial_for_coloring = "''''" not in line_before and '"""' not in line_before
trivial_for_parens = trivial_for_coloring and not re.search(PARENS_REGEX, line_before)
elif chars in "()[]{}":
trivial_for_coloring = line_before.count("'''") == line_after.count(
"'''"
) and line_before.count('"""') == line_after.count('"""')
trivial_for_parens = False
elif chars == "'":
trivial_for_coloring = "'''" not in line_before and "'''" not in line_after
trivial_for_parens = False # can put parens into open string
elif chars == '"':
trivial_for_coloring = '"""' not in line_before and '"""' not in line_after
trivial_for_parens = False # can put parens into open string
elif chars == "\\":
# can shorten closing quote
trivial_for_coloring = '"""' not in line_before and '"""' not in line_after
trivial_for_parens = False
else:
trivial_for_coloring = line_before.count("'''") == line_after.count(
"'''"
) and line_before.count('"""') == line_after.count('"""')
trivial_for_parens = trivial_for_coloring
return trivial_for_coloring, trivial_for_parens
class SafeScrollbar(ttk.Scrollbar):
def __init__(self, master=None, **kw):
super().__init__(master=master, **kw)
def set(self, first, last):
try:
ttk.Scrollbar.set(self, first, last)
except Exception:
traceback.print_exc()
class AutoScrollbar(SafeScrollbar):
# http://effbot.org/zone/tkinter-autoscrollbar.htm
# a vert_scrollbar that hides itself if it's not needed. only
# works if you use the grid geometry manager.
def __init__(self, master=None, **kw):
self.hide_count = 0
self.gridded = False
super().__init__(master=master, **kw)
def set(self, first, last):
if float(first) <= 0.0 and float(last) >= 1.0:
# Need to accept 1 automatic hide, otherwise even narrow files
# get horizontal scrollbar
if self.gridded and self.hide_count < 2:
self.grid_remove()
elif float(first) > 0.001 or float(last) < 0.999:
# with >0 and <1 it occasionally made scrollbar wobble back and forth
if not self.gridded:
self.grid()
ttk.Scrollbar.set(self, first, last)
def grid(self, *args, **kwargs):
super().grid(*args, **kwargs)
self.gridded = True
def grid_configure(self, *args, **kwargs):
super().grid_configure(*args, **kwargs)
self.gridded = True
def grid_remove(self):
super().grid_remove()
self.gridded = False
self.hide_count += 1
def grid_forget(self):
super().grid_forget()
self.gridded = False
self.hide_count += 1
def pack(self, **kw):
raise tk.TclError("cannot use pack with this widget")
def place(self, **kw):
raise tk.TclError("cannot use place with this widget")
def update_entry_text(entry, text):
original_state = entry.cget("state")
entry.config(state="normal")
entry.delete(0, "end")
entry.insert(0, text)
entry.config(state=original_state)
class VerticallyScrollableFrame(ttk.Frame):
# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame
def __init__(self, master):
ttk.Frame.__init__(self, master)
# set up scrolling with canvas
vscrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL)
self.canvas = tk.Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set)
vscrollbar.config(command=self.canvas.yview)
self.canvas.xview_moveto(0)
self.canvas.yview_moveto(0)
self.canvas.grid(row=0, column=0, sticky=tk.NSEW)
vscrollbar.grid(row=0, column=1, sticky=tk.NSEW)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.interior = ttk.Frame(self.canvas)
self.interior_id = self.canvas.create_window(0, 0, window=self.interior, anchor=tk.NW)
self.bind("<Configure>", self._configure_interior, "+")
self.bind("<Expose>", self._expose, "+")
def _expose(self, event):
self.update_idletasks()
self.update_scrollbars()
def _configure_interior(self, event):
self.update_scrollbars()
def update_scrollbars(self):
# update the scrollbars to match the size of the inner frame
size = (self.canvas.winfo_width(), self.interior.winfo_reqheight())
self.canvas.config(scrollregion="0 0 %s %s" % size)
if (
self.interior.winfo_reqwidth() != self.canvas.winfo_width()
and self.canvas.winfo_width() > 10
):
# update the interior's width to fit canvas
# print("CAWI", self.canvas.winfo_width())
self.canvas.itemconfigure(self.interior_id, width=self.canvas.winfo_width())
class ScrollableFrame(ttk.Frame):
# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame
def __init__(self, master):
ttk.Frame.__init__(self, master)
# set up scrolling with canvas
vscrollbar = ttk.Scrollbar(self, orient=tk.VERTICAL)
hscrollbar = ttk.Scrollbar(self, orient=tk.HORIZONTAL)
self.canvas = tk.Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set)
vscrollbar.config(command=self.canvas.yview)
hscrollbar.config(command=self.canvas.xview)
self.canvas.xview_moveto(0)
self.canvas.yview_moveto(0)
self.canvas.grid(row=0, column=0, sticky=tk.NSEW)
vscrollbar.grid(row=0, column=1, sticky=tk.NSEW)
hscrollbar.grid(row=1, column=0, sticky=tk.NSEW)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.interior = ttk.Frame(self.canvas)
self.interior.columnconfigure(0, weight=1)
self.interior.rowconfigure(0, weight=1)
self.interior_id = self.canvas.create_window(0, 0, window=self.interior, anchor=tk.NW)
self.bind("<Configure>", self._configure_interior, "+")
self.bind("<Expose>", self._expose, "+")
def _expose(self, event):
self.update_idletasks()
self._configure_interior(event)
def _configure_interior(self, event):
# update the scrollbars to match the size of the inner frame
size = (self.canvas.winfo_reqwidth(), self.interior.winfo_reqheight())
self.canvas.config(scrollregion="0 0 %s %s" % size)
class ThemedListbox(tk.Listbox):
def __init__(self, master=None, cnf={}, **kw):
super().__init__(master=master, cnf=cnf, **kw)
self._ui_theme_change_binding = self.bind(
"<<ThemeChanged>>", self._reload_theme_options, True
)
self._reload_theme_options()
def _reload_theme_options(self, event=None):
style = ttk.Style()
states = []
if self["state"] == "disabled":
states.append("disabled")
# Following crashes when a combobox is focused
# if self.focus_get() == self:
# states.append("focus")
opts = {}
for key in [
"background",
"foreground",
"highlightthickness",
"highlightcolor",
"highlightbackground",
]:
value = style.lookup(self.get_style_name(), key, states)
if value:
opts[key] = value
self.configure(opts)
def get_style_name(self):
return "Listbox"
def destroy(self):
self.unbind("<<ThemeChanged>>", self._ui_theme_change_binding)
super().destroy()