-
Notifications
You must be signed in to change notification settings - Fork 1
/
trowser.py
executable file
·8855 lines (7291 loc) · 332 KB
/
trowser.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# ------------------------------------------------------------------------ #
# Copyright (C) 2007-2010,2019-2020,2023 T. Zoerner
# ------------------------------------------------------------------------ #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# ------------------------------------------------------------------------ #
#
# DESCRIPTION: Browser for line-oriented text files, e.g. debug traces.
#
# ------------------------------------------------------------------------ #
import sys
import os
import errno
import bisect
import threading
from datetime import datetime
from datetime import timedelta
import time
import tempfile
import json
import re
import traceback
import tkinter.font as tkf
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
from tkinter import colorchooser
# Module "appdirs" is required on Windows to learn the directory where to store
# application configuration files. Install the module via "pip3 install appdirs"
# if the import fails. (Alternatively, you could replace the one function call
# into the module with a hard-coded path.)
if sys.platform == "win32":
import appdirs
#
# This function is used during start-up to define fonts, colors and
# global event binding tags.
#
def InitResources():
global font_normal, font_bold, font_hlink, img_marker
# override default font for the Tk message box
tk.eval("option add *Dialog.msg.font {helvetica 9 bold} userDefault")
# place the "Help" menu button on the far right of the menu bar
tk.eval("option add *Menu.useMotifHelp true")
# fonts for text and label widgets
font_normal = tkf.nametofont("TkDefaultFont")
font_bold = DeriveFont(font_normal, 0, "bold")
font_hlink = DeriveFont(font_normal, -2, "underline")
# bindings to allow scrolling a text widget with the mouse wheel
tk.bind_class("TextWheel", "<Button-4>", lambda e: e.widget.yview_scroll(-3, "units"))
tk.bind_class("TextWheel", "<Button-5>", lambda e: e.widget.yview_scroll(3, "units"))
tk.bind_class("TextWheel", "<MouseWheel>", lambda e: e.widget.yview_scroll(int(-(e.delta / 120) * 3), "units"))
text_modifier_events = (
"<<Clear>>", "<<Cut>>", "<<Paste>>", "<<PasteSelection>>",
"<<Redo>>", "<<Undo>>", "<<TkAccentBackspace>>", "<Key-BackSpace>",
"<Key>", "<Key-Delete>", "<Key-Insert>", "<Key-Return>",
# Not modifiers, but events are overridden below
"<Key-Up>", "<Key-Down>", "<Key-Left>", "<Key-Right>",
"<Key-Tab>", "<Control-Key-c>")
for event in set(tk.bind_class("Text")) - set(text_modifier_events):
tk.bind_class("TextReadOnly", event, tk.bind_class("Text", event))
# since Tk 8.6 there are no event handlers for <Key-Up> in tag Text anymore
tk.bind_class("TextReadOnly", "<Key-Up>", lambda e: CursorMoveUpDown(wt.f1_t, -1))
tk.bind_class("TextReadOnly", "<Key-Down>", lambda e: CursorMoveUpDown(wt.f1_t, 1))
tk.bind_class("TextReadOnly", "<Key-Left>", lambda e: CursorMoveLeftRight(wt.f1_t, -1))
tk.bind_class("TextReadOnly", "<Key-Right>", lambda e: CursorMoveLeftRight(wt.f1_t, 1))
# bindings for a selection text widget (listbox emulation)
# (uses non-standard cursor movement event bindings, hence not added here)
for event in ( "<Button-2>", "<B2-Motion>", "<Key-Prior>", "<Key-Next>",
"<Shift-Key-Tab>", "<Control-Key-Tab>", "<Control-Shift-Key-Tab>" ):
tk.bind_class("TextSel", event, tk.bind_class("Text", event))
for event in ( "<Button-4>", "<Button-5>", "<MouseWheel>" ):
tk.bind_class("TextReadOnly", event, tk.bind_class("TextWheel", event))
tk.bind_class("TextSel", event, tk.bind_class("TextWheel", event))
tk.bind_class("TextReadOnly", "<Control-Key-c>", tk.bind_class("Text", "<<Copy>>"))
tk.bind_class("TextReadOnly", "<Key-Tab>", tk.bind_class("Text", "<Control-Key-Tab>"))
tk.bind_class("TextSel", "<Key-Tab>", tk.bind_class("Text", "<Control-Key-Tab>"))
# bookmark image which is inserted into the text widget
img_marker = tk.eval("image create photo -data "
"R0lGODlhBwAHAMIAAAAAuPj8+Hh8+JiYmDAw+AAAAAAAAAAAACH"
"5BAEAAAEALAAAAAAHAAcAAAMUGDGsSwSMJ0RkpEIG4F2d5DBTkAAAOw==")
#
# This function creates the main window of the trace browser, including the
# menu at the top, the text area and a vertical scrollbar in the middle, and
# the search control dialog at the bottom.
#
def CreateMainWindow():
# menubar at the top of the main window
wt.menubar = Menu(tk)
wt.menubar_ctrl = Menu(wt.menubar, tearoff=0, postcommand=MenuPosted)
wt.menubar_ctrl.add_command(label="Open file...", command=MenuCmd_OpenFile)
wt.menubar_ctrl.add_command(label="Reload current file", state=DISABLED, command=MenuCmd_Reload)
wt.menubar_ctrl.add_separator()
wt.menubar_ctrl.add_command(label="Discard above cursor...", command=lambda:MenuCmd_Discard(False))
wt.menubar_ctrl.add_command(label="Discard below cursor...", command=lambda:MenuCmd_Discard(True))
wt.menubar_ctrl.add_separator()
wt.menubar_ctrl.add_command(label="Font selection...", command=FontList_OpenDialog)
wt.menubar_ctrl.add_command(label="Toggle line-wrap", command=ToggleLineWrap, accelerator="ALT-w")
wt.menubar_ctrl.add_separator()
wt.menubar_ctrl.add_command(label="Quit", command=UserQuit)
wt.menubar_search = Menu(wt.menubar, tearoff=0, postcommand=MenuPosted)
wt.menubar_search.add_command(label="Search history...", command=SearchHistory_Open)
wt.menubar_search.add_command(label="Edit highlight patterns...", command=TagList_OpenDialog)
wt.menubar_search.add_separator()
wt.menubar_search.add_command(label="List all search matches...", command=lambda:SearchAll(True, 0), accelerator="ALT-a")
wt.menubar_search.add_command(label="List all matches above...", command=lambda:SearchAll(True, 1), accelerator="ALT-P")
wt.menubar_search.add_command(label="List all matches below...", command=lambda:SearchAll(True, 1), accelerator="ALT-N")
wt.menubar_search.add_separator()
wt.menubar_search.add_command(label="Clear search highlight", command=SearchHighlightClear, accelerator="&")
wt.menubar_search.add_separator()
wt.menubar_search.add_command(label="Goto line number...", command=lambda:KeyCmd_OpenDialog("goto"))
wt.menubar_mark = Menu(wt.menubar, tearoff=0, postcommand=MenuPosted)
wt.menubar_mark.add_command(label="Toggle bookmark", accelerator="m", command=Mark_ToggleAtInsert)
wt.menubar_mark.add_command(label="List bookmarks", command=MarkList_OpenDialog)
wt.menubar_mark.add_command(label="Delete all bookmarks", command=Mark_DeleteAll)
wt.menubar_mark.add_separator()
wt.menubar_mark.add_command(label="Jump to prev. bookmark", command=lambda:Mark_JumpNext(False), accelerator="'-")
wt.menubar_mark.add_command(label="Jump to next bookmark", command=lambda:Mark_JumpNext(True), accelerator="'+")
wt.menubar_mark.add_separator()
wt.menubar_mark.add_command(label="Read bookmarks from file...", command=Mark_ReadFileFrom)
wt.menubar_mark.add_command(label="Save bookmarks to file...", command=Mark_SaveFileAs)
wt.menubar_help = Menu(wt.menubar, name="help", tearoff=0, postcommand=MenuPosted)
dlg_help_add_menu_commands(wt.menubar_help)
wt.menubar_help.add_separator()
wt.menubar_help.add_command(label="About", command=OpenAboutDialog)
wt.menubar.add_cascade(label="Control", menu=wt.menubar_ctrl, underline=0)
wt.menubar.add_cascade(label="Search", menu=wt.menubar_search, underline=0)
wt.menubar.add_cascade(label="Bookmarks", menu=wt.menubar_mark, underline=0)
wt.menubar.add_cascade(label="Help", menu=wt.menubar_help)
tk.config(menu=wt.menubar)
# frame #1: text widget and scrollbar
wt.f1 = Frame(tk)
wt.f1_t = Text(wt.f1, width=1, height=1, wrap=NONE,
font=font_content, background=col_bg_content, foreground=col_fg_content,
cursor="top_left_arrow", relief=FLAT, exportselection=1)
wt.f1_t.pack(side=LEFT, fill=BOTH, expand=1)
wt.f1_sb = Scrollbar(wt.f1, orient=VERTICAL, command=wt.f1_t.yview, takefocus=0)
wt.f1_sb.pack(side=LEFT, fill=Y)
wt.f1_t.configure(yscrollcommand=wt.f1_sb.set)
wt.f1.pack(side=TOP, fill=BOTH, expand=1)
wt.f1_t.focus_set()
# note: order is important: "find" must be lower than highlighting tags
HighlightConfigure(wt.f1_t, "find", fmt_find)
HighlightConfigure(wt.f1_t, "findinc", fmt_findinc)
wt.f1_t.tag_config("margin", lmargin1=17)
wt.f1_t.tag_config("bookmark", lmargin1=0)
HighlightConfigure(wt.f1_t, "sel", fmt_selection)
wt.f1_t.tag_lower("sel")
wt.f1_t.bindtags([wt.f1_t, "TextReadOnly", tk, "all"])
# commands to scroll the X/Y view
KeyBinding_UpDown(wt.f1_t)
KeyBinding_LeftRight(wt.f1_t)
# commands to move the cursor
# Note: values e.state MS-Windows: 1=SHIFT, 2=CAPS-Lock, 4=CTRL, 0x60000=ALT, 0x60004=Alt-GR, 0x40000=always set!
wt.f1_t.bind("<Key-Home>", lambda e: BindCallAndBreak(lambda: KeyHomeEnd(wt.f1_t, "left") if ((e.state & 0xFF) == 0) else CursorGotoLine(wt.f1_t, "start")))
wt.f1_t.bind("<Key-End>", lambda e: BindCallAndBreak(lambda: KeyHomeEnd(wt.f1_t, "right") if ((e.state & 0xFF) == 0) else CursorGotoLine(wt.f1_t, "end")))
wt.f1_t.bind("<Key-space>", lambda e:BindCallKeyClrBreak(lambda: CursorMoveLeftRight(wt.f1_t, 1)))
wt.f1_t.bind("<Key-BackSpace>", lambda e:BindCallKeyClrBreak(lambda: CursorMoveLeftRight(wt.f1_t, -1)))
KeyCmdBind(wt.f1_t, "h", lambda: wt.f1_t.event_generate("<Left>"))
KeyCmdBind(wt.f1_t, "l", lambda: wt.f1_t.event_generate("<Right>"))
KeyCmdBind(wt.f1_t, "Return", lambda: CursorMoveLine(wt.f1_t, 1))
KeyCmdBind(wt.f1_t, "w", lambda: CursorMoveWord(1, 0, 0))
KeyCmdBind(wt.f1_t, "e", lambda: CursorMoveWord(1, 0, 1))
KeyCmdBind(wt.f1_t, "b", lambda: CursorMoveWord(0, 0, 0))
KeyCmdBind(wt.f1_t, "W", lambda: CursorMoveWord(1, 1, 0))
KeyCmdBind(wt.f1_t, "E", lambda: CursorMoveWord(1, 1, 1))
KeyCmdBind(wt.f1_t, "B", lambda: CursorMoveWord(0, 1, 0))
KeyCmdBind(wt.f1_t, "ge", lambda: CursorMoveWord(0, 0, 1))
KeyCmdBind(wt.f1_t, "gE", lambda: CursorMoveWord(0, 1, 1))
KeyCmdBind(wt.f1_t, ";", lambda: SearchCharInLine("", 1))
KeyCmdBind(wt.f1_t, ",", lambda: SearchCharInLine("", -1))
# commands for searching & repeating
KeyCmdBind(wt.f1_t, "/", lambda: SearchEnter(1))
KeyCmdBind(wt.f1_t, "?", lambda: SearchEnter(0))
KeyCmdBind(wt.f1_t, "n", lambda: SearchNext(1))
KeyCmdBind(wt.f1_t, "N", lambda: SearchNext(0))
KeyCmdBind(wt.f1_t, "*", lambda: SearchWord(1))
KeyCmdBind(wt.f1_t, "#", lambda: SearchWord(0))
KeyCmdBind(wt.f1_t, "&", lambda: SearchHighlightClear())
wt.f1_t.bind("<Alt-Key-f>", lambda e: BindCallKeyClrBreak(lambda:wt.f2_e.focus_set()))
wt.f1_t.bind("<Alt-Key-n>", lambda e: BindCallKeyClrBreak(lambda:SearchNext(1)))
wt.f1_t.bind("<Alt-Key-p>", lambda e: BindCallKeyClrBreak(lambda:SearchNext(0)))
wt.f1_t.bind("<Alt-Key-h>", lambda e: BindCallKeyClrBreak(lambda:SearchHighlightOnOff()))
wt.f1_t.bind("<Alt-Key-a>", lambda e: BindCallKeyClrBreak(lambda:SearchAll(False, 0)))
wt.f1_t.bind("<Alt-Key-N>", lambda e: BindCallKeyClrBreak(lambda:SearchAll(False, 1)))
wt.f1_t.bind("<Alt-Key-P>", lambda e: BindCallKeyClrBreak(lambda:SearchAll(False, -1)))
# misc
KeyCmdBind(wt.f1_t, "i", lambda: SearchList_CopyCurrentLine())
KeyCmdBind(wt.f1_t, "u", lambda: SearchList_Undo())
wt.f1_t.bind("<Control-Key-r>", lambda e: SearchList_Redo())
wt.f1_t.bind("<Control-Key-g>", lambda e: BindCallKeyClrBreak(DisplayLineNumber))
wt.f1_t.bind("<Control-Key-o>", lambda e: BindCallKeyClrBreak(lambda:CursorJumpHistory(wt.f1_t, -1)))
wt.f1_t.bind("<Control-Key-i>", lambda e: BindCallKeyClrBreak(lambda:CursorJumpHistory(wt.f1_t, 1)))
wt.f1_t.bind("<Double-Button-1>", lambda e: BindCallKeyClrBreak(Mark_ToggleAtInsert) if (e.state == 0) else None)
KeyCmdBind(wt.f1_t, "m", Mark_ToggleAtInsert)
wt.f1_t.bind("<Alt-Key-w>", lambda e: BindCallAndBreak(ToggleLineWrap))
wt.f1_t.bind("<Control-plus>", lambda e: BindCallKeyClr(lambda:ChangeFontSize(1)))
wt.f1_t.bind("<Control-minus>", lambda e: BindCallKeyClr(lambda:ChangeFontSize(-1)))
wt.f1_t.bind("<Control-Alt-Delete>", lambda e: DebugDumpAllState())
# catch-all (processes "KeyCmdBind" from above)
wt.f1_t.bind("<FocusIn>", lambda e: KeyClr())
wt.f1_t.bind("<Return>", lambda e: "break" if KeyCmd(wt.f1_t, "Return") else None)
wt.f1_t.bind("<KeyPress>", lambda e: "break" if KeyCmd(wt.f1_t, e.char) else None)
# frame #2: search controls
wt.f2 = Frame(borderwidth=2, relief=RAISED)
wt.f2_l = Label(text="Find:", underline=0)
wt.f2_e = Entry(width=20, textvariable=tlb_find, exportselection=0)
wt.fs_mh = Menu(tearoff=0)
wt.f2_bn = Button(text="Next", command=lambda:SearchNext(1), underline=0, pady=2)
wt.f2_bp = Button(text="Prev.", command=lambda:SearchNext(0), underline=0, pady=2)
wt.f2_bl = Button(text="All", command=lambda:SearchAll(True, 0), underline=0, pady=2)
wt.f2_bh = Checkbutton(text="Highlight all", variable=tlb_hall, command=lambda:SearchHighlightSettingChange, underline=0)
wt.f2_cb = Checkbutton(text="Match case", variable=tlb_case, command=lambda:SearchHighlightSettingChange, underline=6)
wt.f2_re = Checkbutton(text="Reg.Exp.", variable=tlb_regexp, command=lambda:SearchHighlightSettingChange, underline=4)
for wid in (wt.f2_l, wt.f2_e, wt.f2_bn, wt.f2_bp, wt.f2_bl, wt.f2_bh, wt.f2_cb, wt.f2_re):
wid.pack(side=LEFT, anchor=W, padx=1)
wt.f2_e.pack_configure(fill=X, expand=1)
wt.f2.pack(side=TOP, fill=X)
wt.f2_e.bind("<Escape>", lambda e: BindCallAndBreak(SearchAbort))
wt.f2_e.bind("<Return>", lambda e: BindCallAndBreak(SearchReturn))
wt.f2_e.bind("<FocusIn>", lambda e: SearchInit())
wt.f2_e.bind("<FocusOut>", lambda e: SearchLeave())
wt.f2_e.bind("<Control-n>", lambda e: BindCallAndBreak(lambda: SearchIncrement(1, False)))
wt.f2_e.bind("<Control-N>", lambda e: BindCallAndBreak(lambda: SearchIncrement(0, False)))
wt.f2_e.bind("<Key-Up>", lambda e: BindCallAndBreak(lambda: Search_BrowseHistory(True)))
wt.f2_e.bind("<Key-Down>", lambda e: BindCallAndBreak(lambda: Search_BrowseHistory(False)))
wt.f2_e.bind("<Control-d>", lambda e: BindCallAndBreak(Search_Complete))
wt.f2_e.bind("<Control-D>", lambda e: BindCallAndBreak(Search_CompleteLeft))
wt.f2_e.bind("<Control-x>", lambda e: BindCallAndBreak(Search_RemoveFromHistory))
wt.f2_e.bind("<Control-c>", lambda e: BindCallAndBreak(SearchAbort))
# disabled in v1.2 because of possible conflict with misconfigured backspace key
#wt.f2_e.bind("<Control-h>", lambda e: BindCallAndBreak(lambda: TagList_AddSearch(tk)))
#wt.f2_e.bind("<Control-H>", lambda e: BindCallAndBreak(SearchHistory_Open))
wt.f2_e.bind("<Alt-Key-n>", lambda e: BindCallAndBreak(lambda: SearchNext(1)))
wt.f2_e.bind("<Alt-Key-p>", lambda e: BindCallAndBreak(lambda: SearchNext(0)))
wt.f2_e.bind("<Alt-Key-a>", lambda e: BindCallAndBreak(lambda: SearchAll(False, 0)))
wt.f2_e.bind("<Alt-Key-N>", lambda e: BindCallAndBreak(lambda: SearchAll(False, 1)))
wt.f2_e.bind("<Alt-Key-P>", lambda e: BindCallAndBreak(lambda: SearchAll(False, -1)))
wt.f2_e.bind("<Alt-Key-c>", lambda e: BindCallAndBreak(lambda: SearchHighlightToggleVar(tlb_case)))
wt.f2_e.bind("<Alt-Key-e>", lambda e: BindCallAndBreak(lambda: SearchHighlightToggleVar(tlb_regexp)))
tlb_find.trace("w", SearchVarTrace) # add variable tlb_find write SearchVarTrace
tk.protocol(name="WM_DELETE_WINDOW", func=UserQuit)
tk.geometry(win_geom["main_win"])
tk.positionfrom(who="user")
wt.f1_t.bind("<Configure>", lambda e: ToplevelResized(e.widget, tk, wt.f1_t, "main_win"))
# dummy widget for xselection handling
wt.xselection = Label()
wt.xselection.selection_handle(TextSel_XselectionHandler)
#
# This wrapper is used for event bindings to first call a function and then
# return "break" to the window manager, so that the event is not further
# processed.
#
def BindCallAndBreak(func):
func()
return "break"
def BindCallKeyClrBreak(func):
func()
KeyClr()
return "break"
def BindCallKeyClr(func):
func()
KeyClr()
#
# This function creates the requested bitmaps if they don't exist yet
#
def CreateButtonBitmap(*args):
for img in args:
try:
tk.eval("image height %s" % img)
except:
if img == "img_dropdown":
# image for drop-down menu copied from combobox.tcl by Bryan Oakley
tk.eval("image create bitmap img_dropdown -data \"" \
"#define down_arrow_width 15\\n" \
"#define down_arrow_height 15\\n" \
"static char down_arrow_bits[] = {\\n" \
"0x00,0x80,0x00,0x80,0x00,0x80,0x00,0x80,\\n" \
"0x00,0x80,0xf8,0x8f,0xf0,0x87,0xe0,0x83,\\n" \
"0xc0,0x81,0x80,0x80,0x00,0x80,0x00,0x80,\\n" \
"0x00,0x80,0x00,0x80,0x00,0x80};\"")
if img == "img_down":
tk.eval("image create bitmap img_down -data \"" \
"#define ptr_down_width 16\\n" \
"#define ptr_down_height 14\\n" \
"static unsigned char ptr_down_bits[] = {\\n" \
"0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,\\n" \
"0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,\\n" \
"0xc0,0x01,0xf8,0x0f,0xf0,0x07,0xe0,0x03,\\n" \
"0xc0,0x01,0x80,0x00};\"")
if img == "img_up":
tk.eval("image create bitmap img_up -data \"" \
"#define ptr_up_width 16\\n" \
"#define ptr_up_height 14\\n" \
"static unsigned char ptr_up_bits[] = {\\n" \
"0x80,0x00,0xc0,0x01,0xe0,0x03,0xf0,0x07,\\n" \
"0xf8,0x0f,0xc0,0x01,0xc0,0x01,0xc0,0x01,\\n" \
"0xc0,0x01,0xc0,0x01,0xc0,0x01,0xc0,0x01,\\n" \
"0xc0,0x01,0xc0,0x01};\"")
# ----------------------------------------------------------------------------
#
# This function is called during start-up to create tags for all color
# highlights.
#
def HighlightCreateTags():
for w in patlist:
tagnam = w[4]
HighlightConfigure(wt.f1_t, tagnam, w)
wt.f1_t.tag_lower(tagnam, "find")
#
# This function is called after loading a new text to apply the color
# highlighting to the complete text. This means all matches on all
# highlight patterns has to be searched for. Since this can take some
# time, the operation done in the background to avoid blocking the user.
# The CPU is given up voluntarily after each pattern and after max. 100ms
#
def HighlightInit():
global tid_high_init
if wt_exists(wt.hipro):
wt.hipro.destroy()
wt.hipro = None
if len(patlist) > 0:
# create a progress bar as overlay to the main window
wt.hipro = Frame(wt.f1_t, takefocus=0, relief=SUNKEN, borderwidth=2)
wt.hipro_c = Canvas(wt.hipro, width=100, height=10, highlightthickness=0, takefocus=0)
wt.hipro_c.pack()
cid = wt.hipro_c.create_rectangle(0, 0, 0, 12, fill="#0b1ff7", outline="")
wt.hipro.place(anchor=NW, x=0, y=0) #in=wt.f1_t
wt.f1_t.tag_add("margin", "1.0", "end")
wt.f1_t.configure(cursor="watch")
# trigger highlighting for the 1st pattern in the background
tid_high_init = tk.after(50, lambda: HighlightInitBg(0, cid, 0, 0))
# apply highlighting on the text in the visible area (this is quick)
# use the yview callback to redo highlighting in case the user scrolls
Highlight_YviewRedirect()
#
# This function is a slave-function of HighlightInit. The function
# loops across all members in the global pattern list to apply color
# the respective highlighting. The loop is broken up by installing each
# new iteration as an idle event (and limiting each step to 100ms)
#
def HighlightInitBg(pat_idx, cid, line, loop_cnt):
global tid_high_init
if block_bg_tasks or (tid_search_inc is not None) or (tid_search_hall is not None) or (tid_search_list is not None):
# background tasks are suspended - re-schedule with timer
tid_high_init = tk.after(100, lambda:HighlightInitBg(pat_idx, cid, line, 0))
elif loop_cnt > 10:
# insert a small timer delay to allow for idle-driven interactive tasks (e.g. selections)
tid_high_init = tk.after(10, lambda:HighlightInitBg(pat_idx, cid, line, 0))
elif pat_idx < len(patlist):
w = patlist[pat_idx]
tagnam = w[4]
opt = Search_GetOptions(w[0], w[1], w[2])
loop_cnt += 1
# here we do the actual work:
# apply the tag to all matching lines of text
line = HighlightLines(w[0], tagnam, opt, line)
if line >= 0:
# not done yet - reschedule
tid_high_init = tk.after_idle(lambda:HighlightInitBg(pat_idx, cid, line, loop_cnt))
else:
# trigger next tag
pat_idx += 1
tid_high_init = tk.after_idle(lambda:HighlightInitBg(pat_idx, cid, 1, loop_cnt))
# update the progress bar
wt.hipro_c.coords(cid, 0, 0, 100*pat_idx//len(patlist), 12)
else:
if wt_exists(wt.hipro):
wt.hipro.destroy()
wt.hipro = None
wt.f1_t.configure(cursor="top_left_arrow")
tid_high_init = None
#
# This function searches for all lines in the main text widget which match the
# given pattern and adds the given tag to them. If the loop doesn't complete
# within 100ms, the search is paused and the function returns the number of the
# last searched line. In this case the caller must invoke the funtion again
# (as an idle event, to allow user-interaction in-between.)
#
def HighlightLines(pat, tagnam, opt, line):
max_line = int(wt.f1_t.index("end").split(".", maxsplit=1)[0])
start_t = datetime.now()
max_delta = timedelta(microseconds=100000)
while line < max_line:
pos = wt.f1_t.search(pat, "%d.0" % line, "end", **opt)
if pos == "":
break
# match found, highlight this line
line = int(pos.split(".", maxsplit=1)[0])
wt.f1_t.tag_add(tagnam, "%d.0" % line, "%d.0" % (line + 1))
# trigger the search result list dialog in case the line is included there too
SearchList_HighlightLine(tagnam, line)
line += 1
# limit the runtime of the loop - return start line number for the next invocation
if (datetime.now() - start_t > max_delta) and (line < max_line):
return line
# all done for this pattern
return -1
#
# This helper function schedules the line highlight function until highlighting
# is complete for the given pattern. This function is used to add highlighting
# for single tags (e.g. modified highlight patterns or colors; currently not used
# for search highlighting because a separate "cancel ID" is required.)
#
def HighlightAll(pat, tagnam, opt, line=1, loop_cnt=0):
global tid_high_init
if block_bg_tasks:
# background tasks are suspended - re-schedule with timer
tid_high_init = tk.after(100, lambda: HighlightAll(pat, tagnam, opt, line, 0))
elif loop_cnt > 10:
# insert a small timer delay to allow for idle-driven interactive tasks (e.g. selections)
tid_high_init = tk.after(10, lambda: HighlightAll(pat, tagnam, opt, line, 0))
else:
line = HighlightLines(pat, tagnam, opt, line)
if line >= 0:
loop_cnt += 1
tid_high_init = tk.after_idle(lambda: HighlightAll(pat, tagnam, opt, line, loop_cnt))
else:
wt.f1_t.configure(cursor="top_left_arrow")
tid_high_init = None
#
# This function searches the currently visible text content for all lines
# which contain the given sub-string and marks these lines with the given tag.
#
def HighlightVisible(pat, tagnam, opt):
start_pos = wt.f1_t.index("@1,1")
end_pos = wt.f1_t.index("@%d,%d" % (wt.f1_t.winfo_width() - 1, wt.f1_t.winfo_height() - 1))
line = int(start_pos.split(".", maxsplit=1)[0])
max_line = int(end_pos.split(".", maxsplit=1)[0])
#puts "visible $start_pos...$end_pos: $pat $opt"
while line < max_line:
pos = wt.f1_t.search(pat, "%d.0" % line, "end", **opt)
if pos == "":
break
line = int(pos.split(".", maxsplit=1)[0])
wt.f1_t.tag_add(tagnam, "%d.0" % line, "%d.0" % (line + 1))
line += 1
#
# This callback is installed to the main text widget's yview. It is used
# to detect changes in the view to update highlighting if the highlighting
# task is not complete yet. The event is forwarded to the vertical scrollbar.
#
def Highlight_YviewCallback(frac1, frac2):
if tid_high_init is not None:
for w in patlist:
opt = Search_GetOptions(w[0], w[1], w[2])
HighlightVisible(w[0], w[4], opt)
if tid_search_hall is not None:
HighlightVisible(tlb_cur_hall_opt[0], "find", tlb_cur_hall_opt[1])
# automatically remove the redirect if no longer needed
if (tid_high_init is None) and (tid_search_hall is None):
wt.f1_t.configure(yscrollcommand=wt.f1_sb.set)
wt.f1_sb.set(frac1, frac2)
#
# This function redirect the yview callback from the scrollbar into the above
# function. This is used to install a redirection for the duration of the
# initial or search highlighting task.
#
def Highlight_YviewRedirect():
wt.f1_t.configure(yscrollcommand=Highlight_YviewCallback)
#
# This function creates or updates a text widget tag with the options of
# a color highlight entry. The function is called during start-up for all
# highlight patterns, and by the highlight edit dialog (also used for the
# sample text widget.)
#
def HighlightConfigure(wid, tagname, w):
cfg = {}
if w[8]:
cfg["font"] = DeriveFont(font_content, 0, "bold")
else:
cfg["font"] = ""
if w[9]:
cfg["underline"] = w[9]
else:
cfg["underline"] = ""
if w[10]:
cfg["overstrike"] = w[10]
else:
cfg["overstrike"] = ""
if w[13] != "":
cfg["relief"] = w[13]
cfg["borderwidth"] = w[14]
else:
cfg["relief"] = ""
cfg["borderwidth"] = ""
if w[15] > 0:
cfg["spacing1"] = w[15]
cfg["spacing3"] = w[15]
else:
cfg["spacing1"] = ""
cfg["spacing3"] = ""
cfg["background"] = w[6]
cfg["foreground"] = w[7]
cfg["bgstipple"] = w[11]
cfg["fgstipple"] = w[12]
wid.tag_config(tagname, **cfg)
#
# This function clears the current search color highlighting without
# resetting the search string. It's bound to the "&" key, but also used
# during regular search reset.
#
def SearchHighlightClear():
global tlb_cur_hall_opt, tid_search_hall
if tid_search_hall is not None: tk.after_cancel(tid_search_hall)
tid_search_hall = None
wt.f1_t.configure(cursor="top_left_arrow")
wt.f1_t.tag_remove("find", "1.0", "end")
wt.f1_t.tag_remove("findinc", "1.0", "end")
tlb_cur_hall_opt = ["", []]
SearchList_HighlightClear()
#
# This function triggers color highlighting of all lines of text which match
# the current search string. The function is called when global highlighting
# is en-/disabled, when the search string is modified or when search options
# are changed.
#
def SearchHighlightUpdate(pat, opt):
global tlb_cur_hall_opt, tid_search_hall
if pat != "":
if tlb_hall.get():
if opt.get("forwards"): del opt["forwards"]
if opt.get("backwards"): del opt["backwards"]
if tk.focus_get() != wt.f2_e:
if ((tlb_cur_hall_opt[0] != pat) or
(tlb_cur_hall_opt[1] != opt)):
# display "busy" cursor until highlighting is finished
wt.f1_t.configure(cursor="watch")
# kill background highlight process for obsolete pattern
if tid_search_hall is not None: tk.after_cancel(tid_search_hall)
# start highlighting in the background
tlb_cur_hall_opt = [pat, opt]
tid_search_hall = tk.after(100, lambda: SearchHighlightAll(pat, "find", opt))
# apply highlighting on the text in the visible area (this is quick)
# (note this is required in addition to the redirect below)
HighlightVisible(pat, "find", opt)
# use the yview callback to redo highlighting in case the user scrolls
Highlight_YviewRedirect()
else:
HighlightVisible(pat, "find", opt)
else:
SearchHighlightClear()
#
# This is a wrapper for the above function which works on the current
# pattern in the search entry field.
#
def SearchHighlightUpdateCurrent():
if tlb_hall.get():
pat = tlb_find.get()
if pat != "":
if SearchExprCheck(pat, tlb_regexp.get(), True):
opt = Search_GetOptions(pat, tlb_regexp.get(), tlb_case.get())
SearchHighlightUpdate(pat, opt)
#
# This helper function calls the global search highlight function until
# highlighting is complete.
#
def SearchHighlightAll(pat, tagnam, opt, line=1, loop_cnt=0):
global tid_search_hall
if block_bg_tasks:
# background tasks are suspended - re-schedule with timer
tid_search_hall = tk.after(100, lambda: SearchHighlightAll(pat, tagnam, opt, line, 0))
elif loop_cnt > 10:
# insert a small timer delay to allow for idle-driven interactive tasks (e.g. selections)
tid_search_hall = tk.after(10, lambda: SearchHighlightAll(pat, tagnam, opt, line, 0))
else:
line = HighlightLines(pat, tagnam, opt, line)
if line >= 0:
loop_cnt += 1
tid_search_hall = tk.after_idle(lambda: SearchHighlightAll(pat, tagnam, opt, line, loop_cnt))
else:
tid_search_hall = None
wt.f1_t.configure(cursor="top_left_arrow")
#
# This function is bound to the "Highlight all" checkbutton to en- or disable
# global highlighting.
#
def SearchHighlightOnOff():
tlb_hall.set(not tlb_hall.get())
UpdateRcAfterIdle()
SearchHighlightUpdateCurrent()
#
# This function is invoked after a change in search settings (i.e. case
# match, reg.exp. or global highlighting.) The changed settings are
# stored in the RC file and a possible search highlighting is removed
# or updated (the latter only if global highlighting is enabled)
#
def SearchHighlightSettingChange():
UpdateRcAfterIdle()
SearchHighlightClear()
if tlb_hall.get():
SearchHighlightUpdateCurrent()
def SearchHighlightToggleVar(obj):
obj.set(obj.get() ^ 1)
SearchHighlightSettingChange()
#
# This function is invoked when the user enters text in the "find" entry field.
# In contrary to the "atomic" search, this function only searches a small chunk
# of text, then re-schedules itself as an "idle" task. The search can be aborted
# at any time by canceling the task.
#
def Search_Background(pat, is_fwd, opt, start, is_changed, callback):
global tid_search_inc
if block_bg_tasks:
# background tasks are suspended - re-schedule with timer
tid_search_inc = tk.after(100, lambda: Search_Background(pat, is_fwd, opt, start, is_changed, callback))
return
if is_fwd:
end = wt.f1_t.index("end")
else:
end = "1.0"
if start != end:
if is_fwd:
next_line = wt.f1_t.index(start + " + 5000 lines lineend")
else:
next_line = wt.f1_t.index(start + " - 5000 lines linestart")
# invoke the actual search in the text widget content
match_len = IntVar(tk, 0)
pos = wt.f1_t.search(pat, start, next_line, count=match_len, **opt)
if pos == "":
tid_search_inc = tk.after_idle(lambda: Search_Background(pat, is_fwd, opt, next_line, is_changed, callback))
else:
tid_search_inc = None
Search_HandleMatch(pos, match_len.get(), pat, opt, is_changed)
callback(pos, pat, is_fwd, is_changed)
else:
tid_search_inc = None
Search_HandleMatch("", 0, pat, opt, is_changed)
callback("", pat, is_fwd, is_changed)
#
# This function searches the main text content for the expression in the
# search entry field, starting at the current cursor position. When a match
# is found, the cursor is moved there and the line is highlighed.
#
def Search_Atomic(pat, is_re, use_case, is_fwd, is_changed):
global tlb_last_dir
pos = ""
if (pat != "") and SearchExprCheck(pat, is_re, True):
tlb_last_dir = is_fwd
search_opt = Search_GetOptions(pat, is_re, use_case, tlb_last_dir)
start_pos = Search_GetBase(is_fwd, False)
CursorJumpPushPos(wt.f1_t)
if is_fwd:
search_range = [start_pos, wt.f1_t.index("end")]
else:
search_range = [start_pos, "1.0"]
match_len = IntVar(tk, 0)
if start_pos != search_range[1]:
# invoke the actual search in the text widget content
while True:
pos = wt.f1_t.search(pat, search_range[0], search_range[1], count=match_len, **search_opt)
# work-around for backwards search:
# make sure the matching text is entirely to the left side of the cursor
if (pos != "") and SearchOverlapCheck(is_fwd, start_pos, pos, match_len.get()):
# match overlaps: search further backwards
search_range[0] = pos
continue
break
else:
pos = ""
# update cursor position and highlight
Search_HandleMatch(pos, match_len.get(), pat, search_opt, is_changed)
else:
# empty or invalid expression: just remove old highlights
SearchReset()
return pos
#
# This helper function checks if the match returned for a backwards search
# overlaps the search start position (e.g. the match is 1 char left of the
# start pos, but 2 chars long)
#
def SearchOverlapCheck(is_fwd, start_pos, pos, match_len):
if not is_fwd:
# convert start position into numerical (e.g. may be "insert")
try:
(line1, char1) = map(int, start_pos.split("."))
except:
try:
start_pos = wt.f1_t.index(start_pos)
(line1, char1) = map(int, start_pos.split("."))
except:
return False
try:
(line2, char2) = map(int, wt.f1_t.index(pos).split("."))
if (line1 == line2) and (char2 + match_len > char1):
return True
except:
return False
return False
#
# This function handles the result of a text search in the main window. If
# a match was found, the cursor is moved to the start of the match and the
# matching section and complete line are highlighted. Optionally, a background
# process to highlight all matches is started. If no match is found, any
# previously applied search highlighting is removed.
#
def Search_HandleMatch(pos, match_len, pat, opt, is_changed):
global tlb_find_line
if (pos != "") or is_changed:
if not tlb_hall.get() or (tlb_cur_hall_opt[0] != pat):
SearchHighlightClear()
else:
wt.f1_t.tag_remove("findinc", "1.0", "end")
if pos != "":
tlb_find_line = int(pos.split(".")[0])
wt.f1_t.see(pos)
wt.f1_t.mark_set("insert", pos)
wt.f1_t.tag_add("find", "%d.0" % tlb_find_line, "%d.0" % (tlb_find_line + 1))
if match_len > 0:
wt.f1_t.tag_add("findinc", pos, "%s + %d chars" % (pos, match_len))
SearchList_HighlightLine("find", tlb_find_line)
SearchList_MatchView(tlb_find_line)
if tlb_hall.get():
SearchHighlightUpdate(pat, opt)
#
# This function displays a message if no match was found for a search
# pattern. This is split off from the search function so that some
# callers can override the message.
#
def Search_HandleNoMatch(pat, is_fwd):
if pat != "":
pat = ": " + pat
if is_fwd:
DisplayStatusLine("search", "warn", "No match until end of file" + pat)
else:
DisplayStatusLine("search", "warn", "No match until start of file" + pat)
#
# This function is bound to all changes of the search text in the
# "find" entry field. It's called when the user enters new text and
# triggers an incremental search.
#
def SearchVarTrace(name1, name2, op):
# pylint: disable=unused-argument # signature cannot be changed
global tid_search_inc
if tid_search_inc is not None: tk.after_cancel(tid_search_inc)
tid_search_inc = tk.after(50, lambda: SearchIncrement(tlb_last_dir, True))
#
# This function performs a so-called "incremental" search after the user
# has modified the search text. This means searches are started already
# while the user is typing.
#
def SearchIncrement(is_fwd, is_changed):
global tlb_inc_base, tlb_inc_view
global tid_search_inc
tid_search_inc = None
if tk.focus_get() == wt.f2_e:
pat = tlb_find.get()
if (pat != "") and SearchExprCheck(pat, tlb_regexp.get(), False):
if tlb_inc_base is None:
tlb_inc_base = Search_GetBase(is_fwd, True)
tlb_inc_view = [wt.f1_t.xview()[0], wt.f1_t.yview()[0]]
CursorJumpPushPos(wt.f1_t)
if is_changed:
wt.f1_t.tag_remove("findinc", "1.0", "end")
wt.f1_t.tag_remove("find", "1.0", "end")
start_pos = tlb_inc_base
#wt.f1_t.xview_moveto(tlb_inc_view[0])
#wt.f1_t.yview_moveto(tlb_inc_view[1])
#wt.f1_t.mark_set("insert", tlb_inc_base)
#wt.f1_t.see("insert")
else:
start_pos = Search_GetBase(is_fwd, False)
opt = Search_GetOptions(pat, tlb_regexp.get(), tlb_case.get(), is_fwd)
Search_Background(pat, is_fwd, opt, start_pos, is_changed, Search_IncMatch)
else:
SearchReset()
if pat != "":
DisplayStatusLine("search", "error", "Incomplete or invalid reg.exp.")
else:
ClearStatusLine("search")
#
# This function is invoked as callback after a background search for the
# incremental search in the entry field is completed. (Before this call,
# cursor position and search highlights are already updated.)
#
def Search_IncMatch(pos, pat, is_fwd, is_changed):
global tlb_hist_pos, tlb_hist_prefix
if (pos == "") and (tlb_inc_base is not None):
if is_changed:
wt.f1_t.xview_moveto(tlb_inc_view[0])
wt.f1_t.yview_moveto(tlb_inc_view[1])
wt.f1_t.mark_set("insert", tlb_inc_base)
wt.f1_t.see("insert")
if is_fwd:
DisplayStatusLine("search", "warn", "No match until end of file")
else:
DisplayStatusLine("search", "warn", "No match until start of file")
else:
ClearStatusLine("search")
if tlb_hist_pos is not None:
hl = tlb_history[tlb_hist_pos]
if pat != hl[0]:
tlb_hist_pos = None
tlb_hist_prefix = None
#
# This function checks if the search pattern syntax is valid
#
def SearchExprCheck(pat, is_re, display):
if is_re:
try:
# Text widget uses Tcl "re_syntax" which slightly differs from Python "re"
#re.compile(pat)
dummy_wid = Text(tk)
dummy_wid.search(pat, 1.0, regexp=True)
return True
#except re.error as e:
except Exception as e:
if display:
DisplayStatusLine("search", "error", "Syntax error in search expression: " + str(e))
return False
else:
return True
#
# This function returns the start position for a search. The first search
# starts at the insertion cursor. If the cursor is not visible, the search
# starts at the top or bottom of the visible text. When a search is repeated,
# the search must start behind the previous match (for a forward search) to
# prevent finding the same word again, or finding an overlapping match. (For
# backwards searches overlaps cannot be handled via search arguments; such
# results are filtered out when a match is found.)
#
def Search_GetBase(is_fwd, is_init):
if wt.f1_t.bbox("insert") is None:
if is_fwd:
wt.f1_t.mark_set("insert", "@1,1")
else: