-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathbindings.py
2269 lines (1955 loc) · 90 KB
/
bindings.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
"""
The core Python bindings to Tkhtml3
Copyright (c) 2025 Andereoo
"""
from re import IGNORECASE, MULTILINE, split, sub, finditer
from urllib.parse import urlencode, urljoin, urlparse
import tkinter as tk
from tkinter import ttk
from imageutils import text_to_image, data_to_image, blank_image
from utilities import *
class Combobox(tk.Widget):
"Bindings for Bryan Oakley's combobox widget."
def __init__(self, master):
try:
load_combobox(master)
tk.Widget.__init__(self, master, "::combobox::combobox")
except tk.TclError:
load_combobox(master, force=True)
tk.Widget.__init__(self, master, "::combobox::combobox")
self.configure(
highlightthickness=0,
borderwidth=0,
editable=False,
takefocus=0,
selectbackground="#6eb9ff",
relief="flat",
elementborderwidth=0,
buttonbackground="white",
)
self.data = [""]
self.values = [""]
self.default = 0
def insert(self, data, values, selected):
for elem in reversed(data):
self.tk.call(self._w, "list", "insert", 0, elem)
self.data = data
self.values = values
if selected:
self.default = self.values.index(selected)
self.reset()
def set(self, value):
if value in self.values:
self.tk.call(self._w, "select", self.values.index(value))
def reset(self):
self.tk.call(self._w, "select", self.default)
def get(self):
val = self.tk.call(self._w, "curselection")[0]
return self.values[val]
class TkinterWeb(tk.Widget):
"Bindings for the Tkhtml3 HTML widget."
def __init__(self, master, tkinterweb_options=None, **kwargs):
self.master = master
self._setup_settings()
self._setup_status_variables()
# inherited settings
waiting_options = {}
if tkinterweb_options:
for item, value in tkinterweb_options.items():
try:
setattr(self, item, value)
except AttributeError:
waiting_options[item] = value
# provide OS information for troubleshooting
self.post_message(f"Starting TkinterWeb for {PLATFORM.processor} {PLATFORM.system} with Python {'.'.join(PYTHON_VERSION)}")
if self.use_prebuilt_tkhtml:
# get Tkhtml folder and register crash handling
folder = get_tkhtml_folder()
if "drawcleanupcrashcmd" not in kwargs:
kwargs["drawcleanupcrashcmd"] = master.register(self._on_draw_cleanup_crash_cmd)
else:
folder = None
# register image loading infrastructure
if "imagecmd" not in kwargs:
kwargs["imagecmd"] = master.register(self._on_image_cmd)
# if "logcmd" not in kwargs:
# kwargs["logcmd"] = tkhtml_notifier
# load the Tkhtml3 widget
try:
load_tkhtml(master, folder, )
tk.Widget.__init__(self, master, "html", kwargs)
except tk.TclError:
load_tkhtml(master, folder, True)
tk.Widget.__init__(self, master, "html", kwargs)
# create a tiny, blank frame for cursor updating
self.motion_frame = tk.Frame(self, bg=self.motion_frame_bg, width=1, height=1)
self.motion_frame.place(x=0, y=0)
# If a setting required the widget to be initialized and couldn't be changed, change it now
if waiting_options:
for item, value in waiting_options.items():
setattr(self, item, value)
self._setup_bindings()
self._setup_handlers()
self.update_default_style()
self.post_message(f"Tkhtml3 successfully loaded from {folder}")
def _setup_settings(self):
"Widget settings."
self.allow_threading = self.master.tk.eval('set tcl_platform(threaded)')
self._caches_enabled = True
self._dark_theme_enabled = False
self._image_inversion_enabled = False
self._crash_prevention_enabled = True
self._javascript_enabled = False
self.messages_enabled = True
self.events_enabled = True
self.selection_enabled = True
self.stylesheets_enabled = True
self.images_enabled = True
self.forms_enabled = True
self.objects_enabled = True
self.ignore_invalid_images = True
self.image_alternate_text_enabled = True
self.overflow_scroll_frame = None
self.default_style = None
self.dark_style = None
self.use_prebuilt_tkhtml = True
self.experimental = False
self.find_match_highlight_color = "#ef0fff"
self.find_match_text_color = "#fff"
self.find_current_highlight_color = "#38d878"
self.find_current_text_color = "#fff"
self.selected_text_highlight_color = "#3584e4"
self.selected_text_color = "#fff"
self.visited_links = []
self.image_alternate_text_font = get_alt_font()
self.image_alternate_text_size = 14
self.image_alternate_text_threshold = 10
self.embed_obj = None
self.manage_vsb_func = placeholder
self.manage_hsb_func = placeholder
self.on_link_click = placeholder
self.on_form_submit = placeholder
self.message_func = placeholder
self.on_script = placeholder
self.on_element_script = placeholder
self.on_resource_setup = placeholder
self.maximum_thread_count = 20
self.insecure_https = False
self.headers = {}
self.dark_theme_limit = 160
self.style_dark_theme_regex = r"([^:;\s{]+)\s?:\s?([^;{!]+)(?=!|;|})"
self.general_dark_theme_regexes = [r'(<[^>]+bgcolor=")([^"]*)',r'(<[^>]+text=")([^"]*)',r'(<[^>]+link=")([^"]*)']
self.inline_dark_theme_regexes = [r'(<[^>]+style=")([^"]*)', r'([a-zA-Z-]+:)([^;]*)']
self.radiobutton_token = "TKWtsvLKac1"
self.node_tag = f"tkinterweb.{id(self)}.nodes"
self.scrollable_node_tag = f"tkinterweb.{id(self)}.scrollablenodes"
self.widget_container_attr = "-tkinterweb-widget-container"
def _setup_status_variables(self):
"Widget status variables."
self.base_url = ""
self.title = ""
self.icon = ""
self.style_count = 0
self.active_threads = []
self.loaded_images = set()
self.image_directory = {}
self.image_name_prefix = f"_tkinterweb_img_{id(self)}_"
self.is_selecting = False
self.downloads_have_occured = False
self.pending_scripts = []
self.unstoppable = True
self.on_embedded_node = None
self.selection_start_node = None
self.selection_start_offset = None
self.selection_end_node = None
self.selection_end_offset = None
self.prev_active_node = None
self.current_node = None
self.hovered_nodes = []
self.loaded_elements = []
self.current_cursor = ""
self.vsb_type = 2
self.selection_type = 0
self.motion_frame_bg = "white"
self.form_widgets = {}
self.form_nodes = {}
self.loaded_forms = {}
self.radio_buttons = {}
self.waiting_forms = 0
self.loaded_iframes = {}
def _setup_bindings(self):
"Widget bindtags and bindings."
self._add_bindtags(self, False)
self.bind("<<Copy>>", self.copy_selection, True)
self.bind("<B1-Motion>", self._extend_selection, True)
self.bind("<Button-1>", self._on_click, True)
self.bind("<Button-2>", self._on_middle_click, True)
self.bind("<Button-3>", self._on_right_click, True)
self.bind("<Double-Button-1>", self._on_double_click, True)
self.bind("<ButtonRelease-1>", self._on_click_release, True)
self.bind_class(self.node_tag, "<Motion>", self._on_mouse_motion, True)
def _setup_handlers(self):
"Register node handlers."
self.register_handler("script", "script", self._on_script)
self.register_handler("script", "style", self._on_style)
self.register_handler("node", "link", self._on_link)
self.register_handler("node", "title", self._on_title)
self.register_handler("node", "a", self._on_a)
self.register_handler("node", "base", self._on_base)
self.register_handler("node", "input", self._on_input)
self.register_handler("node", "textarea", self._on_textarea)
self.register_handler("node", "select", self._on_select)
self.register_handler("node", "form", self._on_form)
self.register_handler("node", "object", self._on_object)
self.register_handler("node", "iframe", self._on_iframe)
self.register_handler("node", "table", self._on_table)
self.register_handler("node", "img", self._on_image)
# Node handlers don't work on body and html elements.
# These elements also cannot be removed without causing a segfault.
# Wierd.
self.register_handler("parse", "body", self._on_body)
self.register_handler("parse", "html", self._on_body)
self.register_handler("attribute", "input", self._on_input_value_change)
self.register_handler("attribute", "select", self._on_input_value_change)
self.register_handler("attribute", "a", self._on_a_value_change)
self.register_handler("attribute", "object", self._on_object_value_change)
self.register_handler("attribute", "iframe", self._on_iframe_value_change)
self.register_handler("attribute", "img", self._on_image_value_change)
@property
def caches_enabled(self):
return self._caches_enabled
@caches_enabled.setter
def caches_enabled(self, enabled):
"Disable the Tkhtml image cache when disabling caches."
if self._caches_enabled != enabled:
self._caches_enabled = enabled
self.enable_imagecache(enabled)
@property
def javascript_enabled(self):
return self._javascript_enabled
@javascript_enabled.setter
def javascript_enabled(self, enabled):
"Warn the user when enabling JavaScript."
if self._javascript_enabled != enabled:
self._javascript_enabled = enabled
if enabled:
self.post_message("WARNING: JavaScript support was enabled. This feature is a work in progress. Only enable JavaScript support on documents you know and trust.")
@property
def crash_prevention_enabled(self):
return self._crash_prevention_enabled
@crash_prevention_enabled.setter
def crash_prevention_enabled(self, enabled):
"Warn the user when disabling crash prevention."
if self._crash_prevention_enabled != enabled:
self._crash_prevention_enabled = enabled
if not enabled:
self.post_message("WARNING: Crash prevention was disabled. You may encounter segmentation faults on some pages.")
@property
def dark_theme_enabled(self):
return self._dark_theme_enabled
@dark_theme_enabled.setter
def dark_theme_enabled(self, enabled):
"Warn the user when enabling dark mode."
if self._dark_theme_enabled != enabled:
self._dark_theme_enabled = enabled
if enabled:
self.post_message("Dark theme was enabled. This feature may cause hangs or crashes on some pages.")
self.update_default_style()
@property
def image_inversion_enabled(self):
return self._image_inversion_enabled
@image_inversion_enabled.setter
def image_inversion_enabled(self, enabled):
"Warn the user when enabling image inversion."
if self._image_inversion_enabled != enabled:
self._image_inversion_enabled = enabled
if enabled:
self.post_message("Image inversion was enabled. This feature may cause hangs or crashes on some pages.")
@property
def threading_enabled(self):
return bool(self._maximum_thread_count)
@threading_enabled.setter
def threading_enabled(self, enabled):
"Convenience setting to enable/disable threading by changing the maximum thread count. Not a real setting."
if enabled:
self.maximum_thread_count = self.default_maximum_thread_count
else:
self.maximum_thread_count = 0
@property
def maximum_thread_count(self):
return self._maximum_thread_count
@maximum_thread_count.setter
def maximum_thread_count(self, count):
"Ensure that maximum_thread_count is always zero if Tcl/Tk is not built with thread support."
count = int(count)
if self.allow_threading:
self._maximum_thread_count = count
if count:
self.default_maximum_thread_count = count
else:
self.post_message("WARNING: threading is disabled because your Tcl/Tk library does not support threading")
self.default_maximum_thread_count = self._maximum_thread_count = 0
def post_event(self, event):
"Generate a virtual event."
if self.events_enabled:
# thread safety
self.after(0, lambda event=event: self._finish_posting_event(event))
def post_message(self, message):
"Post a message."
if self.overflow_scroll_frame:
message = "[EMBEDDED DOCUMENT] " + message
if self.messages_enabled:
self.message_func(message)
def parse(self, html):
"Parse HTML code."
self.downloads_have_occured = False
self.unstoppable = True
html = self._crash_prevention(html)
html = self._dark_mode(html)
self.tk.call(self._w, "parse", html)
# we assume that if no downloads have been made by now the document has finished loading, so we send the done loading signal
if not self.downloads_have_occured:
self.post_event(DONE_LOADING_EVENT)
self._submit_deferred_scripts()
self.send_onload()
def send_onload(self, root=None, children=None):
"""Send the onload signal for nodes that aren't handled at runtime.
We keep this a seperate command so that it can be run after inserting elements or changing the innerHTML"""
if not self._javascript_enabled:
return
if children:
for node in children:
if self.get_node_tag(node) not in {"img", "object", "link"}:
self._submit_element_js(node, "onload")
else:
for node in self.search("[onload]", root=root):
if self.get_node_tag(node) not in {"img", "object", "link"}:
self._submit_element_js(node, "onload")
def update_default_style(self):
"Update the default stylesheet based on color theme."
if self._dark_theme_enabled and self.dark_style:
self.config(defaultstyle=self.dark_style)
elif self.default_style:
self.config(defaultstyle=self.default_style)
def parse_css(self, sheetid=None, data="", url=None, override=False):
"Parse CSS code."
if not url:
url = self.base_url
data = self._crash_prevention(data)
if self._dark_theme_enabled:
data = sub(self.style_dark_theme_regex, lambda match, matchtype=0: self._generate_altered_colour(match, matchtype), data)
try:
#urlcmd = self.register(self.resolve_url)
importcmd = self.register(
lambda new_url, parent_url=url: self._on_atimport(
parent_url, new_url
)
)
if override:
self.style_count += 1
self.tk.call(
self._w, "style", "-id", "author" + str(self.style_count).zfill(4), "-importcmd", importcmd, data
)
elif sheetid:
self.tk.call(
self._w, "style", "-id", sheetid, "-importcmd", importcmd, data
)
else:
self.tk.call(self._w, "style", "-importcmd", importcmd, data)
except tk.TclError:
# the widget doesn't exist anymore
pass
def reset(self):
"Reset the widget."
self.stop()
self.loaded_images = set()
self.image_directory = {}
self.form_get_commands = {}
self.form_nodes = {}
self.form_widgets = {}
self.loaded_forms = {}
self.waiting_forms = 0
self.radio_buttons = {}
self.loaded_iframes = {}
self.hovered_nodes = []
self.loaded_elements = []
self.current_node = None
self.on_embedded_node = None
self.selection_start_node = None
self.selection_end_node = None
self.title = ""
self.icon = ""
self.vsb_type = self.manage_vsb_func()
self.manage_hsb_func()
self._set_cursor("default")
self.tk.call(self._w, "reset")
def stop(self):
"Stop loading resources."
self.unstoppable = False
for thread in self.active_threads:
thread.stop()
def node(self, *args):
"Retrieve one or more document node handles from the current document."
nodes = self.tk.call(self._w, "node", *args)
if nodes:
return nodes
else:
return None, None
def text(self, *args):
"Enable interaction with the text of the HTML document."
return self.tk.call(self._w, "text", *args)
def tag(self, subcommand, tag_name, *args):
"Return the name of the Html tag that generated this document node, or an empty string if the node is a text node."
return self.tk.call(self._w, "tag", subcommand, tag_name, *args)
def search(self, selector, cnf={}, **kwargs):
"""Search the document for the specified CSS selector; return a Tkhtml3 node if found."""
return self.tk.call((self._w, "search", selector)+self._options(cnf, kwargs))
def xview(self, *args):
"Used to control horizontal scrolling."
if args:
return self.tk.call(self._w, "xview", *args)
coords = map(float, self.tk.call(self._w, "xview").split())
return tuple(coords)
def xview_scroll(self, number, what):
"""Shifts the view in the window left or right, according to number and what.
"number" is an integer, and "what" is either "units" or "pages"."""
return self.xview("scroll", number, what)
def xview_moveto(self, number):
"Shifts the view horizontally to the specified position"
return self.xview("moveto", number)
def yview(self, *args):
"""Used to control vertical scrolling."""
return self.tk.call(self._w, "yview", *args)
def yview_scroll(self, number, what):
"""Shifts the view in the window left or right, according to number and what.
"number" is an integer, and "what" is either "units" or "pages"."""
return self.yview("scroll", number, what)
def yview_moveto(self, number):
"Moves the view vertically to the specified position."
return self.yview("moveto", number)
def bbox(self, node=None):
"Get the bounding box of the viewport or a specified node."
return self.tk.call(self._w, "bbox", node)
def parse_fragment(self, html):
"""Parse a document fragment.
A document fragment isn't part of the active document but is comprised of nodes like the active document.
Changes made to the fragment don't affect the document.
Returns a root node."""
self.downloads_have_occured = False
self.unstoppable = True
html = self._crash_prevention(html)
html = self._dark_mode(html)
fragment = self.tk.call(self._w, "fragment", html)
# We assume that if no downloads have been made by now the document has finished loading, so we send the done loading signal
if not self.downloads_have_occured:
self.post_event(DONE_LOADING_EVENT)
self._submit_deferred_scripts()
return fragment
def enable_imagecache(self, enabled):
"Enable or disable the Tkhtml imagecache."
self.tk.call(self._w, "configure", "-imagecache", enabled)
def get_node_text(self, node_handle, *args):
"Get the text content of the given node."
return self.tk.call(node_handle, "text", *args)
def set_node_text(self, node_handle, new):
"Set the text content of the given node."
return self.tk.call(node_handle, "text", "set", new)
def get_node_tag(self, node_handle):
"Get the HTML tag of the given node."
return self.tk.call(node_handle, "tag")
def get_node_parent(self, node_handle):
"Get the parent of the given node."
return self.tk.call(node_handle, "parent")
def get_node_children(self, node_handle):
"Get the children of the given node."
return self.tk.call(node_handle, "children")
def get_node_attribute(self, node_handle, attribute, default="", value=None):
"Get the specified attribute of the given node."
if value: # backwards compatability
return self.tk.call(node_handle, "attribute", attribute, value)
else:
return self.tk.call(
node_handle, "attribute", "-default", default, attribute
)
def set_node_attribute(self, node_handle, attribute, value):
"Set the specified attribute of the given node."
return self.tk.call(node_handle, "attribute", attribute, value)
def get_node_attributes(self, node_handle):
"Get the attributes of the given node."
attr = self.tk.call(node_handle, "attribute")
return dict(zip(attr[0::2], attr[1::2]))
def get_node_property(self, node_handle, node_property, *args):
"Get the specified CSS property of the given node."
return self.tk.call(node_handle, "property", *args, node_property)
def get_node_properties(self, node_handle, *args):
"Get the CSS properties of the given node."
prop = self.tk.call(node_handle, "property", *args)
return dict(zip(prop[0::2], prop[1::2]))
def override_node_properties(self, node_handle, *props):
"Get/set the CSS property override list."
if props: return self.tk.call(node_handle, "override", " ".join(props))
return self.tk.call(node_handle, "override")
def insert_node(self, node_handle, child_nodes):
"Experimental, insert the specified nodes into the parent node."
return self.tk.call(node_handle, "insert", child_nodes)
def insert_node_before(self, node_handle, child_nodes, before):
"Experimental, place the specified nodes is before another node."
return self.tk.call(node_handle, "insert", "-before", before, child_nodes)
def replace_node_contents(self, node_handle, contents, *args):
"Fill a node with either a Tk widget or with Tkhtml nodes."
if not contents:
# calling replace on an empty node causes Tkhtml to segfault
contents = self.tk.call(self._w, "fragment", " ")
return self.tk.call(node_handle, "replace", contents, *args)
def delete_node(self, node_handle):
"Delete the given node."
node_parent = self.get_node_parent(node_handle)
node_tag = self.get_node_tag(node_handle)
# removing the body element causes a segfault
if node_parent and node_tag != "body":
self.tk.call(node_parent, "remove", node_handle)
else:
raise tk.TclError(f"{node_tag} elements cannot be removed")
def destroy_node(self, node_handle):
"Destroy a node. May cause crashes so avoid it whenever possible."
self.tk.call(node_handle, "destroy")
def set_node_flags(self, node, name):
"Set dynamic flags on the given node."
self.tk.call(node, "dynamic", "set", name)
def remove_node_flags(self, node, name):
"Set dynamic flags on the given node."
self.tk.call(node, "dynamic", "clear", name)
def get_node_tkhtml(self, node_handle):
"Get pathName of node (I think)."
return self.tk.call(node_handle, "html")
def get_current_node(self, event):
"Get current node."
return self.tk.eval(
f"""set node [lindex [lindex [{self} node {event.x} {event.y}] end] end]"""
)
def get_current_node_parent(self, node):
"Get the parent of the given node."
return self.tk.eval(f"""set node [lindex [lindex [{node} parent] end] end]""")
def register_handler(self, handler_type, node_tag, callback):
"Register a node handler"
self.tk.call(self._w, "handler", handler_type, node_tag, self.register(callback))
def image(self, full=False):
"""Return the name of a new Tk image containing the rendered document.
The returned image should be deleted when the script has finished with it.
Note that this command is mainly intended for automated testing.
Be wary of running this command on large documents.
Does not work on Windows unless experimental Tkhtml is used."""
full = "-full" if full else ""
name = self.tk.call(self._w, "image", full)
return name, self.tk.call(name, "data")
def postscript(self, cnf={}, **kwargs):
"""Print the contents of the canvas to a postscript file.
Valid options: colormap, colormode, file, fontmap, height,
pageanchor, pageheight, pagesize, pagewidth, pagex, pagey,
nobg, noimages, rotate, width, x, and y.
Does not work unless experimental Tkhtml is used."""
return self.tk.call((self._w, "postscript")+self._options(cnf, kwargs))
def preload_image(self, url):
"""Preload an image for use later.
Only useful if caches are enabled and reset() is not called after preloading."""
return self.tk.call(self._w, "preload", url)
def get_computed_styles(self):
"Get a tuple containing the computed CSS rules for each CSS selector"
return self.tk.call(self._w, "_styleconfig")
def fetch_scripts(self, attributes, url=None, data=None):
"Fetch and run scripts"
thread = self._begin_download()
if url and self.unstoppable:
self.post_message(f"Fetching script from {shorten(url)}")
try:
data = self._download_url(url)[0]
except Exception as error:
self.post_message(f"ERROR: could not load script {url}: {error}")
self.on_resource_setup(url, "script", False)
if data and self.unstoppable:
if "defer" in attributes:
self.pending_scripts.append((attributes, data))
else:
self.after(0, self.on_script, attributes, data) # thread safety
if url:
self.post_message(f"Successfully loaded {shorten(url)}")
self.on_resource_setup(url, "script", True)
self._finish_download(thread)
def fetch_styles(self, node=None, url=None, data=None):
"Fetch stylesheets and parse the CSS code they contain"
thread = self._begin_download()
if url and self.unstoppable:
self.post_message(f"Fetching stylesheet from {shorten(url)}")
try:
data = sub(r"url\((.*?)\)",
lambda match, url=url: self._fix_css_urls(match, url),
self._download_url(url)[0]
)
except Exception as error:
self.post_message(f"ERROR: could not load stylesheet {url}: {error}")
self.on_resource_setup(url, "stylesheet", False)
if data and self.unstoppable:
self.style_count += 1
sheetid = "user." + str(self.style_count).zfill(4)
self.parse_css(f"{sheetid}.9999", data, url)
if node:
# thread safety
self.after(0, self._submit_element_js, node, "onload")
if url:
self.post_message(f"Successfully loaded {shorten(url)}")
self.on_resource_setup(url, "stylesheet", True)
self._finish_download(thread)
def fetch_objects(self, node, url):
thread = self._begin_download()
try:
data, newurl, filetype, code = self._download_url(url)
if data and filetype.startswith("image"):
name = self.image_name_prefix + str(len(self.loaded_images))
image = data_to_image(data, name, filetype, self._image_inversion_enabled, self.dark_theme_limit)
self.loaded_images.add(image)
self.override_node_properties(node, "-tkhtml-replacement-image", f"url(replace:{image})")
elif data and filetype == "text/html":
self.after(0, self._create_iframe, node, newurl, data)
self.after(0, self._submit_element_js, node, "onload")
except Exception as error:
self.post_message(f"ERROR: could not load object element: {error}")
self._finish_download(thread)
def load_alt_text(self, url, name):
if (url in self.image_directory):
node = self.image_directory[url]
if not self.ignore_invalid_images:
image = data_to_image(BROKEN_IMAGE, name, "image/png", self._image_inversion_enabled, self.dark_theme_limit)
self.loaded_images.add(image)
elif self.image_alternate_text_enabled:
alt = self.get_node_attribute(node, "alt")
if alt and self.experimental:
self.insert_node(node, self.parse_fragment(alt))
elif alt:
image = text_to_image(
name, alt, self.bbox(node),
self.image_alternate_text_font,
self.image_alternate_text_size,
self.image_alternate_text_threshold,
)
self.loaded_images.add(image)
elif not self.ignore_invalid_images:
image = data_to_image(BROKEN_IMAGE, name, "image/png", self._image_inversion_enabled, self.dark_theme_limit)
self.loaded_images.add(image)
def fetch_images(self, node, url, name):
"Fetch images and display them in the document."
thread = self._begin_download()
self.post_message(f"Fetching image from {shorten(url)}")
if url == self.base_url:
self.load_alt_text(url, name)
self.post_message(f"ERROR: image url not specified")
else:
try:
data, newurl, filetype, code = self._download_url(url)
if self.unstoppable and data:
# thread safety
self.after(0, self.finish_fetching_images, node, data, name, filetype, url)
except Exception as error:
self.load_alt_text(url, name)
self.post_message(f"ERROR: could not load image {url}: {error}")
self.on_resource_setup(url, "image", False)
self._finish_download(thread)
def finish_fetching_images(self, node, data, name, filetype, url):
try:
image = data_to_image(data, name, filetype, self._image_inversion_enabled, self.dark_theme_limit)
if image:
self.loaded_images.add(image)
self.post_message(f"Successfully loaded {shorten(url)}")
self.on_resource_setup(url, "image", True)
if node:
# thread safety
self.after(0, self._submit_element_js, node, "onload")
if self.experimental:
node = self.search(f'img[src="{url}"]')
if node:
if self.get_node_children(node): self.delete_node(self.get_node_children(node))
else:
self.load_alt_text(url, name)
self.post_message(f"ERROR: the image {url} could not be shown: either PyGObject, CairoSVG, or both PyCairo and Rsvg must be installed to parse .svg files")
self.on_resource_setup(url, "image", False)
except Exception as error:
self.load_alt_text(url, name)
self.post_message(f"ERROR: could not load image {url}: {error}")
self.on_resource_setup(url, "image", False)
def handle_node_replacement(self, node, widgetid, deletecmd, stylecmd=None, allowscrolling=True, handledelete=True):
"Replace a Tkhtml3 node with a Tkinter widget."
if stylecmd:
if handledelete:
self.replace_node_contents(
node, widgetid,
"-deletecmd", self.register(deletecmd),
"-stylecmd", self.register(stylecmd),
)
else:
self.replace_node_contents(
node, widgetid, "-stylecmd", self.register(stylecmd)
)
else:
if handledelete:
self.replace_node_contents(
node, widgetid, "-deletecmd", self.register(deletecmd)
)
else:
self.replace_node_contents(node, widgetid)
self._add_bindtags(widgetid, allowscrolling)
widgetid.bind(
"<Enter>",
lambda event, node_handle=node: self._on_embedded_mouse_motion(
event, node_handle=node_handle
),
)
widgetid.bind(
"<Leave>",
lambda event, node_handle=None: self._on_embedded_mouse_motion(
event, node_handle=node_handle
),
)
def handle_node_removal(self, widgetid):
widgetid.destroy()
def handle_node_style(self, node, widgetid, widgettype="button"):
if widgettype == "button":
bg = "transparent"
while bg == "transparent" and node != "":
bg = self.get_node_property(node, "background-color")
node = self.get_node_parent(node)
if bg == "transparent":
bg = "white"
widgetid.configure(
background=bg,
highlightbackground=bg,
highlightcolor=bg,
activebackground=bg,
)
elif widgettype == "range":
bg = "transparent"
while bg == "transparent" and node != "":
bg = self.get_node_property(node, "background-color")
node = self.get_node_parent(node)
if bg == "transparent":
bg = "white"
style = ttk.Style()
stylename = f"Scale{widgetid}.Horizontal.TScale"
style.configure(stylename, background=bg)
widgetid.configure(style=stylename)
elif widgettype == "text":
bg = self.get_node_property(node, "background-color")
fg = self.get_node_property(node, "color")
font = self.get_node_property(node, "font")
if bg == "transparent":
bg = "white"
if fg == "transparent":
fg = "white"
widgetid.configure(background=bg, foreground=fg, font=font)
def map_node(self, node, force=False):
"Redraw a node if it currently containing a Tk widget."
if force or (self.get_node_attribute(node, self.widget_container_attr) != ""):
self.set_node_attribute(node, self.widget_container_attr, "")
self.replace_node_contents(node, node)
def replace_node_with_widget(self, node, widgetid):
"Replace a node with a Tk widget."
if not widgetid:
# reset the node if a widget is not supplied
self.map_node(node)
return
manager = widgetid.winfo_manager()
if manager == "Tkhtml": # Don't display the same widget twice
for old_node in self.search(f"[{self.widget_container_attr}]"):
if self.get_node_attribute(old_node, self.widget_container_attr) == str(widgetid):
# If we know where the widget is,
# Replace the old node with its original contents so we can redraw the widget here
self.map_node(old_node)
break
else:
raise tk.TclError(f"cannot embed widget already managed by {manager}")
# Tkhtml seems to remove the widget from the previous geometry manager if it is not Tkhtml so I think we are fine
allowscrolling = self.get_node_attribute(node, "allowscrolling", "false") != "false"
allowstyling = self.get_node_attribute(node, "allowstyling", "false") != "false"
handleremoval = self.get_node_attribute(node, "handleremoval", "false") != "false"
if allowstyling:
allowstyling = lambda node=node, widgetid=widgetid, widgettype="text": self.handle_node_style(node, widgetid, widgettype)
else:
allowstyling = None
if handleremoval:
# Tkhtml's -deletecmd handler is fairly broken
# I would instead give the widget an extra class and bind to <Unmap>
# But apparently that doesn't fire at all. Oh well.
handleremoval = lambda widgetid=widgetid: self.handle_node_removal(widgetid)
else:
handleremoval = None
# We used to add the node to a dict but we need to be able to delete it when destroy is called o any of its parents
# By setting an attribute we can use Tkhtml's search function
self.set_node_attribute(node, self.widget_container_attr, widgetid)
self.handle_node_replacement(
node,
widgetid,
handleremoval,
allowstyling,
allowscrolling,
False,
)
self._submit_element_js(node, "onload")
def find_text(self, searchtext, select, ignore_case, highlight_all):
"Search for and highlight specific text in the document."
self.clear_selection()
nmatches = 0
matches = []
selected = []
match_indexes = []
self.tag("delete", "findtext")
self.tag("delete", "findtextselected")
if len(searchtext) == 0 or select <= 0:
return nmatches, selected, matches
doctext = self.text("text")
try:
# find matches
if ignore_case:
rmatches = finditer(
searchtext, doctext, flags=IGNORECASE | MULTILINE
)
else:
rmatches = finditer(searchtext, doctext, flags=MULTILINE)
for match in rmatches:
match_indexes.append(
(
match.start(0),
match.end(0),
)
)
nmatches += 1
if len(match_indexes) > 0:
# highlight matches
self.post_message(f"{nmatches} results for the search key '{searchtext}' have been found")
if highlight_all:
for num, match in enumerate(match_indexes):
match = self.text("index", match_indexes[num][0])
match += self.text("index", match_indexes[num][1])
matches.append(match)
selected = self.text("index", match_indexes[select - 1][0])
selected += self.text("index", match_indexes[select - 1][1])
for match in matches:
node1, index1, node2, index2 = match
self.tag("add", "findtext", node1, index1, node2, index2)
self.tag(
"configure",
"findtext",
"-bg",
self.find_match_highlight_color,
"-fg",
self.find_match_text_color,
)
node1, index1, node2, index2 = selected
self.tag("add", "findtextselected", node1, index1, node2, index2)
self.tag(
"configure",
"findtextselected",
"-bg",
self.find_current_highlight_color,
"-fg",
self.find_current_text_color,
)