-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDebugConsole.py
executable file
·4405 lines (4017 loc) · 177 KB
/
DebugConsole.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
#!/bin/env -S python3 -B
# -*- coding: utf-8 -*-
#
# DebugConsole.py
# pythonDebugConsole
#
# Created by Jens Ayton on 2007-11-29.
# Copyright (c) 2007 Jens Ayton. All rights reserved.
#
# GUI I/O stuff (c) 2008-2012 Kaks. CC-by-NC-SA 3
#
# GUI stuff (c) 2019 cag CC-by-NC-SA 4
#
# CLI arg and several other fixes (c) 2024 MrFlibble CC-by-NC-SA 4
#
"""
A gui implementation of the Oolite JavaScript debug console interface.
"""
__author__ = "Jens Ayton <[email protected]>, Kaks, cag"
#__version__ = "2.08" #From this version on, will be pulling version from _version file.
from _version import __version__
import os, sys #Flibble moved this up near the top in case debug on windows without con.
FROZEN=hasattr(sys, 'frozen')
if sys.platform == 'win32' and FROZEN:
#This is the only "dump it where we are" Flibble investigates: Just keep the exe in a dir :-|
sys.stderr = open(os.path.join(os.getcwd(), os.path.basename(sys.argv[0]))+"-stderr.txt", "w")
# Send all stdout to stderr needs stderr to exist first.
# When frozen with noconsole on 'doze, there's no stdout to begin with!
sys.stdout = sys.stderr
import cliArgs as dca #Flibble
#####################################
if dca.g['debug']:
import pdb
from traceback import print_exc
#####################################
try:
from sys import _MEIPASS
HAVE_MEIPASS = True
except:
HAVE_MEIPASS = False
from collections import OrderedDict, namedtuple
from ooliteConsoleServer import *
from twisted.internet.protocol import Factory
from twisted.internet import stdio, reactor, tksupport
from OoliteDebugCLIProtocol import OoliteDebugCLIProtocol
from pickle import load as pickle_load
from pickle import dump as pickle_dump
from re import compile
from logging import StreamHandler, basicConfig, Formatter, getLogger, shutdown, DEBUG, WARNING
from traceback import format_tb
from errno import ENOENT, ENOSPC
from platform import system as platform_system
platformIsLinux = platform_system() == 'Linux'
platformIsWindows = platform_system() == 'Windows'
#As we have parsed the command line, and dragged in constants, we know the OS
# and if not frozen, knowing the path will allow us to find our icons.
if not FROZEN:
#Get script path (dereferenced in case symlink).
SCRIPTPATH = os.path.dirname(os.path.realpath(__file__))
Python2 = sys.version_info[0] == 2
if Python2:
import ConfigParser as configparser
from Tkinter import *
import tkFont
import tkColorChooser as tkColor
from time import clock, asctime
from string import maketrans
else:
import configparser
from tkinter import *
import tkinter.font as tkFont
import tkinter.colorchooser as tkColor
from time import perf_counter, asctime
# constants
MINIMUM_WIDTH = 600
MINIMUM_HEIGHT = 480
SCROLLER_WIDTH = 20
DEFAULT_GEOMETRY = '{}x{}+0+0'.format(MINIMUM_WIDTH, MINIMUM_HEIGHT)
DEFAULT_ALIAS_POSN = '[{}, {}]'.format(int(MINIMUM_WIDTH/8), int(MINIMUM_HEIGHT)/3) # 440 120 @ Arial 10
DEBUGGER_TITLE = 'Oolite - Javascript Debug Console ({})'.format('executable' if FROZEN else 'Python2' if Python2 else 'Python3')
GEOMETRY_RE = compile(r'(\d+)x(\d+)\+(\d+)\+(\d+)')
TRIMSECT_RE = compile(r"\[ *(?P<header>[^]]+?) *\]") # trim section names
CONNECTMSG = "Please (re)start Oolite in order to connect."
#Flibble : Adding cli args stuff with sane default paths.
BASE_FNAME = dca.g['base']
CFG_EXT = '.' + dca.g['cext']
HIST_EXT = '.' + dca.g['hext']
LOG_EXT = '.' + dca.g['lext']
LOG_PATH = dca.g['lpath']
CFG_PATH = dca.g['cpath']
CFG_BASE = os.path.join ( CFG_PATH, BASE_FNAME )
HIST_BASE = os.path.join ( LOG_PATH, BASE_FNAME )
LOG_BASE = os.path.join ( LOG_PATH, BASE_FNAME )
CFGFILE = CFG_BASE + CFG_EXT
HISTFILE = HIST_BASE + HIST_EXT
LOGFILE = LOG_BASE + LOG_EXT
MAX_HIST_CMDS = 200
MAX_HIST_SIZE = MAX_HIST_CMDS * 1000
MAX_HIST_VERSION = 3
MAX_CFG_VERSION = 3
MAX_LOG_VERSION = 5
# in seconds
CMD_TIMEOUT = 2 # elapsed time before sending next in queue (current goes in timedOutCmds)
CMD_TIMEOUT_LONG = 4 # " except for a couple long running cmds
CMD_TIMEOUT_ABORT = 15 # " when cmd is abandonded (deleted from timedOutCmds) as data considered stale
TKCOLORS = {
'black': '#000000',
'red': '#ff0000',
'green': '#00ff00',
'blue': '#0000ff',
'cyan': '#00ffff',
'yellow': '#ffff00',
'magenta': '#ff00ff',
'white': '#ffffff',
}
OOCOLORS = {
'blackColor': '#000000',
'darkGrayColor': '#555555',
'lightGrayColor': '#2a2a2a',
'whiteColor': '#ffffff',
'grayColor': '#808080',
'redColor': '#ff0000',
'greenColor': '#00ff00',
'blueColor': '#0000ff',
'cyanColor': '#00ffff',
'yellowColor': '#ffff00',
'magentaColor': '#ff00ff',
'orangeColor': '#ff8000',
'purpleColor': '#800080',
'brownColor': '#996633',
}
debugFlags = OrderedDict((
('DEBUG_LINKED_LISTS', 0x00000001),
# ('UNUSED', 0x00000002),
('DEBUG_COLLISIONS', 0x00000004),
('DEBUG_DOCKING', 0x00000008),
('DEBUG_OCTREE_LOGGING', 0x00000010),
# ('UNUSED', 0x00000020),
('DEBUG_BOUNDING_BOXES', 0x00000040),
('DEBUG_OCTREE_DRAW', 0x00000080),
('DEBUG_DRAW_NORMALS', 0x00000100),
('DEBUG_NO_DUST', 0x00000200),
('DEBUG_NO_SHADER_FALLBACK',0x00000400),
('DEBUG_SHADER_VALIDATION', 0x00000800),
# Flag for temporary use, always last in list.
# ('DEBUG_MISC', 0x10000000),
))
allDebugFlags = sum(flag for flag in debugFlags.values())
logMessageClasses = OrderedDict((
('General Errors', 'general.error'),
('Script Errors', '$scriptError'),
('Script Debug', '$scriptDebugOn'),
('Shader Debug', '$shaderDebugOn'),
('Troubleshooting Dumps', '$troubleShootingDump'),
('Entity State', '$entityState'),
('Data Cache Debug', '$dataCacheDebug'),
('Texture Debug', '$textureDebug'),
('Sound Debug', '$soundDebug'),
))
detailLevels = OrderedDict((
('Minimum', 'DETAIL_LEVEL_MINIMUM'),
('Normal', 'DETAIL_LEVEL_NORMAL'),
('Shaders', 'DETAIL_LEVEL_SHADERS'),
('Extras', 'DETAIL_LEVEL_EXTRAS'),
))
showConsoleForDebug = {
'Show Console for Log Messages': 'show-console-on-log',
'Show Console for Warnings': 'show-console-on-warning',
'Show Console for Errors': 'show-console-on-error',
}
# these are console properties, with setter & getter fns; cannot use setConfigurationValue, as (3 of 4) values
# actually stored in private properties (eg. __dumpStackForErrors) and we'll get out of sync otherwise
persistenceMap = {
'dump-stack-for-errors': 'dumpStackForErrors',
'dump-stack-for-warnings': 'dumpStackForWarnings',
'show-error-locations': 'showErrorLocations',
'show-error-locations-during-console-eval': 'showErrorLocationsDuringConsoleEval',
}
# default configuration
defaultConfig = OrderedDict((
('Settings', OrderedDict((
('SaveConfigOnExit', 'Yes'),
('MsWheelHistory', 'No'),
('MaxHistoryCmds', str(MAX_HIST_CMDS)),
('SaveHistoryOnExit', 'Yes'),
('Geometry', DEFAULT_GEOMETRY),
('AliasWindow', DEFAULT_ALIAS_POSN),
('ConsolePort', 8563),
('EnableShowConsole', 'Yes'),
('MacroExpansion', 'Yes'),
('TruncateCmdEcho', 'No'),
('ResetCmdSizeOnRun', 'Yes'),
('_PlistOverrides_', 'if Yes, colors and fonts are replaced with those received from Oolite'),
('PlistOverrides', 'No'),
('MaxBufferSize', '200000'),
('DebugToggle', 'No'),
))
),
('Font', OrderedDict((
('Family', 'Arial'),
('Size', 10),
('Weight', 'normal'),
('Slant', 'roman'),
))
),
('Colors', OrderedDict((
('Foreground', 'yellow'),
('Background', 'black'),
('Command', 'cyan'),
('Selectfg', 'black'),
('Selectbg', 'white'),
))
),
('Aliases', OrderedDict()
),
))
# globals
TCP_Port = None
app = None
debugLogger = None
cmdLineHandler = None
openMessages = []
SilentMsg = namedtuple('SilentMsg', 'cmd, label, tkVar, discard, timeSent')
class SimpleConsoleDelegate:
__active = Active = False
def __init__(self, protocol):
self.protocol = protocol
self.identityString = "DebugConsole"
def __del__(self):
if self.__active: self.protocol.factory.activeCount -= 1
if cmdLineHandler.inputReceiver is self: cmdLineHandler.inputReceiver = None
def acceptConnection(self):
return self.protocol.factory.activeCount < 1
def connectionOpened(self, ooliteVersionString):
app.colorPrint("Opened connection with Oolite version {}".format(ooliteVersionString))
app.colorPrint('')
app.bodyText.update_idletasks()
app.bodyText.edit_modified(False)
self.protocol.factory.activeCount += 1
self.__active = self.Active = True
cmdLineHandler.inputReceiver = self
app.client = self.protocol
def loadConfig(self, config): # settings received from client; config is a dict of debugger settings
if not app.connectedToOolite:
app.initClientSettings(config)
else:
app.noteConfig(config)
def connectionClosed(self, message):
if message is None or isinstance(message, str):
if message is not None and len(message) > 0:
app.colorPrint('Connection closed: "{}"'.format(message))
else:
app.colorPrint("Connection closed with no message at {}.".format(asctime))
if self.__active:
self.protocol.factory.activeCount -= 1
self.__active = self.Active = False
app.tried=0
app.client = None
app.disableClientSettings()
def writeToConsole(self, message, colorKey, emphasisRanges):
app.handleMessage(message, colorKey, emphasisRanges)
def clearConsole(self):
app.bodyClear()
def showConsole(self):
if app.localOptions['EnableShowConsole']:
if app.top.state() != 'zoomed' and app.top.state() != 'normal':
app.top.state('normal')
app.top.wm_attributes("-topmost", 1)
app.top.wm_attributes("-topmost", 0)
app.top.lift()
app.cmdLine.focus_set()
def send(string):
receiveUserInput(string)
def receiveUserInput(self, string):
self.protocol.sendCommand(string)
def closeConnection(self, message):
self.protocol.closeConnection(message)
# end class SimpleConsoleDelegate
class TopWindow(Toplevel):
def __init__(self, parent, name=True, enduring=False, showNow=True):
Toplevel.__init__(self, parent)
self.transient(parent)
self.parent = parent
self.setTitle(name)
self.enduring = enduring
if enduring: # override the 'X' from destroying window
self.protocol('WM_DELETE_WINDOW', self.closeTop)
self.twFrame = Frame(self)
self.resizable(width=False, height=False)
self.twFrame.grid()
if showNow:
self.focus_set()
else:
self.withdraw()
def savePosition(self):
Xoff, Yoff = self.getGeometry(self, coords=True)
if Xoff == 0 and Yoff == 0: # newly minted widget, ie. never mapped
return # don't clobber any existing saved values
self.mouseXY = [Xoff, Yoff]
@classmethod
def getGeometry(cls, widget, coords=False):
widget.update_idletasks()
info = widget.winfo_geometry()
widgetSize, Xoff, Yoff = info.split('+')
width, depth = widgetSize.split('x')
if coords:
return [int(Xoff), int(Yoff)]
else:
return [int(width), int(depth), int(Xoff), int(Yoff)]
def center(self):
width, depth, Xoff, Yoff = self.getGeometry(self.parent.winfo_toplevel())
winWidth, winDepth, _, _ = self.getGeometry(self)
winXoff = Xoff + (width>>1) - (winWidth>>1)
winYoff = Yoff + (depth>>1) - (winDepth>>1)
self.geometry('{}x{}+{}+{}'.format(winWidth, winDepth, winXoff, winYoff))
self.mouseXY = [winXoff, winYoff]
self.restoreTop()
def showAtMouse(self, coords=None, offsetX=0, offsetY=0):
if not hasattr(self, 'mouseXY') and coords is None:
self.mouseXY = self.winfo_pointerxy()
x, y = self.mouseXY if coords is None else coords
self.mouseXY = [x + offsetX, y + offsetY]
self.restoreTop()
def setTitle(self, name):
self.name = name
if name and len(name) > 0:
self.title(name)
def openTop(self):
if not hasattr(self, 'mouseXY'):
self.showAtMouse()
else:
self.restoreTop()
def restoreTop(self):
if hasattr(self, 'mouseXY'):
self.geometry('+{}+{}'.format(*self.mouseXY))
self.deiconify()
self.lift() # required in pyinstaller version else fontSelectTop won't show (anywhere!)
self.focus_set()
def closeTop(self, event=None):
if self.enduring:
if hasattr(self, 'mouseXY'):# creation delayed until opened (closeTop may precede; see closeAnyOpenFrames)
self.savePosition() # preserve user's positioning of window
self.withdraw()
else:
self.destroy()
return 'break'
# end class TopWindow
class OoInfoBox(TopWindow):
_count = 0
def __init__(self, master, msg, font=None, destruct=None, error=False):
OoInfoBox._count += 1
TopWindow.__init__(self, master, name='Error' if error else 'Message', enduring=False, showNow=False)
self.bind('<Escape>', self.closeMessageBox)
infoBoxFrame = self.twFrame
length = len(msg)
if '\n' not in msg and length < 40:
padding = ' '*((40 - length)>>1)
msg = '{}{}{}'.format(padding, msg, padding)
msg = '\n{}\n'.format(msg)
self.msgBoxStr = StringVar(value=msg, name='ooInfoBox_'+str(OoInfoBox._count)+'_msgBoxStr')
self.msgBoxLabel = Label(infoBoxFrame, textvariable=self.msgBoxStr,
font=font, anchor=CENTER, justify=CENTER)
self.msgBoxOK = Button(infoBoxFrame, text='OK', font=font,
padx=10, command=self.closeMessageBox)
self.msgBoxOK.bind('<Return>', self.closeMessageBox)
self.msgBoxLabel.grid( row=0, column=0, sticky=N, columnspan=2, padx=8)
if destruct is not None:
self.msgBoxSpinFrame = Frame(infoBoxFrame)
self.msgBoxSpinVar = StringVar(value=str(destruct), name='ooInfoBox_'+str(OoInfoBox._count)+'_msgBoxSpinVar')
self.msgBoxSpinLabel = Label(self.msgBoxSpinFrame, text='closing in:',
padx=10, font=font, anchor=W)
self.msgBoxSpinbox = Spinbox(self.msgBoxSpinFrame, exportselection=0,
from_=0, to=10, increment=1, font=font,
state='readonly', width=2, textvariable=self.msgBoxSpinVar)
self.msgBoxSpinbox.bind('<Enter>', self.haltDestruct)
self.msgBoxSpinLabel.grid( row=0, column=0, sticky=E) # in msgBoxSpinFrame
self.msgBoxSpinbox.grid( row=0, column=1, sticky=W) # "
self.msgBoxSpinFrame.grid( row=1, column=0, sticky=W)
self.destructID = self.after(1000, self.destructMessage)
infoBoxFrame.columnconfigure(0, weight=1) # to center OK button (almost)
infoBoxFrame.columnconfigure(1, weight=3)
self.msgBoxOK.grid( row=1, column=1, sticky=SW, padx=2, pady=2)
else:
self.msgBoxOK.grid( row=1, column=0, sticky=S, columnspan=2, padx=2, pady=2)
self.center()
self.msgBoxOK.focus_set()
destructID = None
def destructMessage(self):
self.destructID = None
self.msgBoxSpinbox.invoke('buttondown')
count = int(self.msgBoxSpinVar.get())
if count > 0:
self.destructID = self.after(1000, self.destructMessage)
else:
self.closeMessageBox()
def haltDestruct(self, event=None):
if self.destructID is not None:
self.after_cancel(self.destructID)
self.destructID = None
def closeMessageBox(self, event=None):
if self.destructID is not None:
self.after_cancel(self.destructID)
self.destructID = None
if self in openMessages:
openMessages.remove(self)
del self.msgBoxStr
# self.msgBoxStr.unset()
if hasattr(self, 'msgBoxSpinVar'):
del self.msgBoxSpinVar
# self.msgBoxSpinVar.unset()
self.closeTop()
return 'break'
# end class OoInfoBox
class OoBarMenu(Menu): # for menubar pulldown menus that support fonts!
menus = []
def __init__(self, master, label, font, **kwargs):
self.master = master
self.label = label
self.font = font
self.menuButton = Button(master, text=self.label, font=font, name='{}Menu'.format(label.lower()),
command=self.toggleMenu)
if platformIsWindows:
self.menuButton.bind('<Leave>', self.closeMenu)
# only the OS can close a menu (?), so this at least keeps their 'open' flags in sync
Menu.__init__(self, master, tearoff=0, font=font, **kwargs)
self._index = len(OoBarMenu.menus)
OoBarMenu.menus.append(self)
self.menuButton.grid(row=0, column=self._index, sticky=W)
self.menuItems = {}
self.statesVary = {}
self.isOpen = False
def closeMenu(self, event=None):
if self.isOpen and platformIsLinux:
self.unpost()
# This subcommand does not work on Windows and the Macintosh, as
# those platforms have their own way of unposting menus. (tcl8.5)
self.isOpen = False
def toggleMenu(self): # storing open state in 'underline' (not used) to enable toggling
if not self.isOpen:
openXY = [self.master.winfo_rootx() + self.menuButton.winfo_x(),
self.master.winfo_rooty() + self.menuButton.winfo_y() + self.menuButton.winfo_height()]
for menu in OoBarMenu.menus:
if menu != self:# prevent flashing on Linux??
menu.closeMenu()
self.isOpen = True
self.post(*openXY) # we wait for the menu to close
else:
self.closeMenu()
def _add(self, kind, **kwargs):
if 'label' not in kwargs: return
label = kwargs['label']
if 'stateChange' in kwargs:
self.statesVary[label] = kwargs['stateChange']
del kwargs['stateChange']
self.add(kind, **kwargs)
self.menuItems[label] = self.index(END)
def add_cascade(self, **kwargs):
self._add('cascade', **kwargs)
def add_checkbutton(self, **kwargs):
self._add('checkbutton', **kwargs)
def add_command(self, **kwargs):
self._add('command', **kwargs)
def add_radiobutton(self, **kwargs):
self._add('radiobutton', **kwargs)
def add_separator(self, **kwargs):
self.add('separator', **kwargs) # bypass _add as never change state, color
def configLabel(self, label, **kwargs):
if label in self.menuItems:
self.entryconfigure(self.menuItems[label], **kwargs)
else:
errmsg = 'Error: label "{}" not in menuItems'.format(label)
if dca.g['debug']:
print(errmsg)
print_exc()
pdb.set_trace()
else:
debugLogger.error(errmsg)
def changeAllStates(self, newState):
statesVary = self.statesVary
for label in statesVary:
if statesVary[label]:
self.configLabel(label, state=newState)
def removeOnesSelf(self):
self.menuButton.destroy()
self.destroy()
# end class OoBarMenu
class TextPopup(Menu):
_count = 0
def __init__(self, master, histCmd=None):
self.master = master
TextPopup._count += 1
Menu.__init__(self, master, tearoff=0)
self.histCmd = histCmd
self.add_command(label='Select all', command=self.selectAll)
self.add_command(label='Begin Select', command=self.beginSelect)
self.add_command(label='End Select', command=self.endSelect)
self.add_separator()
self.add_command(label='Search ...', command=self.openSearchBox)
self.add_separator()
self.add_command(label='Copy', command=self.copyText)
self.add_command(label='Copy All', command=self.copyAllText)
self.add_command(label='Paste', command=self.pasteText)
self.add_separator()
self.add_command(label='Delete', command=self.deleteText)
self.add_command(label='Delete All', command=self.deleteAllText)
self.add_separator()
self.add_command(label='Undo delete', command=self.deleteUndo)
self.searchStrings = [] # prev. search strings for history
self.createSearchBox()
if histCmd:
self.add_separator()
self.add_command(label='Remove command', command=histCmd)
self.master.bind('<Button-1>', self.recordTextPosn)
self.master.bind('<Button-3>', self.openPopUpMenu)
self.master.bind('<<Clear>>', self.deleteText)
self.master.bind('<BackSpace>', self.deleteText)
self.master.bind('<Delete>', self.deleteText)
self.master.bind('<Alt-BackSpace>', self.deleteUndo)
self.master.bind('<<Cut>>', self.cutText)
self.master.bind('<Control-X>', self.cutText)
self.master.bind('<<Copy>>', self.copyText)
self.master.bind('<Control-C>', self.copyText)
self.master.bind('<<Paste>>', self.pasteText)
self.master.bind('<Control-V>', self.pasteText)
self.master.bind('<<Undo>>', self.deleteUndo)
self.master.bind('<Control-Z>', self.deleteUndo)
def selectAll(self):
txt = self.master
txt.tag_remove(SEL, '1.0', END)
txt.tag_add(SEL, '1.0', END)
txt.tag_raise(SEL)
self.selStart = '1.0'
self.selEnd = END
txt.focus_set()
def beginSelect(self):
txt = self.master
txt.tag_remove(SEL, '1.0', END)
selStart = self.formatMouseIndex()
txt.tag_add(SEL, selStart) # this sets selection range of 1 char
self.selStart = selStart
self.selEnd = None
txt.focus_set() # often focus is in cmdLine, so this saves a click
def formatMouseIndex(self, xOffset=None):
txt = self.master
[x, y] = self.rightMouseXY
if xOffset is not None:
x += xOffset
return txt.index('@{},{}'.format(x-txt.winfo_rootx(), y-txt.winfo_rooty()))
def endSelect(self):
txt = self.master
selStart = self.selStart
selEnd = self.formatMouseIndex()
if txt.compare(selStart, '>', selEnd): # backwards
selStart, selEnd = selEnd, selStart
selEnd = '{} +1c'.format(selEnd)
if txt.compare(selEnd, '>', END):
selEnd = txt.index(END)
selEnd = txt.index(selEnd)
txt.tag_remove(SEL, '1.0', END)
txt.tag_add(SEL, selStart, selEnd)
if len(txt.tag_ranges(SEL)) > 0:
txt.tag_raise(SEL)
self.selEnd = txt.index(SEL_LAST)
txt.focus_set()
def createSearchBox(self):
self.top = self.master.winfo_toplevel()
self.searchBox = TopWindow(self.top, 'Search for:', enduring=True, showNow=False)
self.searchBox.bind('<Escape>', self.searchBox.closeTop)
self.searchBox.bind('<Return>', self.handleCR)
searchBoxFrame = self.searchBox.twFrame
defaultFont = self.defaultFont = tkFont.nametofont(self.master.config('font')[-1])
self.lineSpace = defaultFont.metrics('linespace')
self.searchFontFace = defaultFont.cget('family')
self.searchFontSize = defaultFont.cget('size')
self.searchDirn = IntVar(value=1, name='textPopup_'+str(TextPopup._count)+'_searchDirn')
# - default backwards=1 (.search also accepts forwards=0)
self.searchResultLen = IntVar(name='textPopup_'+str(TextPopup._count)+'_searchResultLen')
# - search stores # of char.s if pattern found
self.searchDirnFwd = Radiobutton(searchBoxFrame, variable=self.searchDirn, indicatoron=0,
value=0, text='\\/', bg='#ddd', relief='raised', bd=2,
command=self.startSearch, font=defaultFont)
self.searchDirnBck = Radiobutton(searchBoxFrame, variable=self.searchDirn, indicatoron=0,
value=1, text='/\\', bg='#ddd', relief='raised', bd=2,
command=self.startSearch, font=defaultFont)
searchRegexText = 'Regex (POSIX extended REs with some extensions)'
searchEntryWidth = len(searchRegexText)
self.searchHistory = ScrollingListBox(searchBoxFrame, font=defaultFont, exportselection=0, height=5)
scrollW = self.searchHistory.scrollbar.winfo_reqwidth()
scrollW = int(3 * scrollW / defaultFont.measure('0'))
self.searchHistory.config(width=searchEntryWidth - scrollW)
self.searchHistory.bind('<<ListboxSelect>>', self.searchSelected)
if len(self.searchStrings):
self.searchHistory.setContents(self.searchStrings)
self.searchHistToggle = Button(searchBoxFrame, text='\\/', bg='#ddd', relief='raised', bd=2,
command=self.toggleSearchHist, font=defaultFont)
self.searchTarget = StringVar(name='textPopup_'+str(TextPopup._count)+'_searchTarget')
setBtns = self.register(self.buttonState)
self.searchTargetEntry = Entry(searchBoxFrame, textvariable=self.searchTarget,
exportselection=0, bg='#ddd', width=searchEntryWidth,
font=defaultFont, validate='key', validatecommand=(setBtns, '%P'))
self.searchTargetEntryClear = Button(searchBoxFrame, text='Clear', font=defaultFont, state=DISABLED,
command=lambda: self.searchTarget.set(''))
self.searchAuxFrame = Frame(searchBoxFrame)
self.searchCountBtn = Button(self.searchAuxFrame, text='Count', font=defaultFont, state=DISABLED,
command=lambda: self.startSearch(counting=True))
self.searchMarkall = Button(self.searchAuxFrame, text='Mark all', font=defaultFont, state=DISABLED,
command=lambda: self.startSearch(marking=True))
self.searchBackwards = IntVar(value=1, name='textPopup_'+str(TextPopup._count)+'_searchBackwards')
# - default search up, backwards=1
self.searchBackwardsBtn = Checkbutton(searchBoxFrame, variable=self.searchBackwards, pady=3,
text='Backwards', font=defaultFont) # pady=3 to match height of Button
self.searchWordsOnly = IntVar(name='textPopup_'+str(TextPopup._count)+'_searchWordsOnly')
# - default any match, word boundary not detected by tk.search
self.searchWordsOnlyBtn = Checkbutton(searchBoxFrame, variable=self.searchWordsOnly, pady=3,
text='Words only', font=defaultFont)
self.searchCase = IntVar(value=1, name='textPopup_'+str(TextPopup._count)+'_searchCase')
# - default insensitive, nocase=1
self.searchCaseBtn = Checkbutton(searchBoxFrame, variable=self.searchCase, pady=3,
text='Ignore case', font=defaultFont)
self.searchWrap = IntVar(name='textPopup_'+str(TextPopup._count)+'_searchWrap')
# - default off, stopindex='1.0' or END; search will wrap if not set
self.searchWrapBtn = Checkbutton(searchBoxFrame, variable=self.searchWrap, pady=3,
text='Wrap search', font=defaultFont)
self.searchRegex = IntVar(name='textPopup_'+str(TextPopup._count)+'_searchRegex')
# - default off, regexp=0 or exact=1; subset of Py's regexs: . ^ [c 1 …] (…) * + ? e1|e2
self.searchRegexBtn = Checkbutton(searchBoxFrame, variable=self.searchRegex, pady=3,
text=searchRegexText, font=defaultFont)
self.searchLabelStr = StringVar(name='textPopup_'+str(TextPopup._count)+'_searchLabelStr')
self.searchLabel = Label(searchBoxFrame, textvariable=self.searchLabelStr, font=defaultFont)
gI = self.searchGridInfo = {}
gI['DirnBck'] = {'row': '0', 'column': '0', 'sticky': 'nw', 'padx': '4', 'pady': '4', 'columnspan': '1', 'rowspan': '1'} #, 'ipady': '0', 'ipadx': '0'
gI['Entry'] = {'row': '0', 'column': '1', 'sticky': 'w', 'padx': '4', 'pady': '4', 'columnspan': '2', 'rowspan': '1'}
gI['Toggle'] = {'row': '0', 'column': '3', 'sticky': 'w', 'padx': '4', 'pady': '4', 'columnspan': '1', 'rowspan': '1'}
gI['Clear'] = {'row': '0', 'column': '4', 'sticky': 'e', 'padx': '4', 'pady': '4', 'columnspan': '1', 'rowspan': '1'}
gI['DirnFwd'] = {'row': '1', 'column': '0', 'sticky': 'nw', 'padx': '4', 'pady': '4', 'columnspan': '1', 'rowspan': '1'}
gI['History'] = {'row': '1', 'column': '1', 'sticky': 'nw', 'padx': '12', 'pady': '4', 'columnspan': '2', 'rowspan': '3'}
gI['Backwards'] = {'row': '1', 'column': '1', 'sticky': 'nw', 'padx': '12', 'pady': '4', 'columnspan': '1', 'rowspan': '1'}
gI['WordsOnly'] = {'row': '1', 'column': '2', 'sticky': 'nw', 'padx': '12', 'pady': '4', 'columnspan': '1', 'rowspan': '1'}
gI['Wrap'] = {'row': '2', 'column': '1', 'sticky': 'nw', 'padx': '12', 'pady': '4', 'columnspan': '1', 'rowspan': '1'}
gI['Case'] = {'row': '2', 'column': '2', 'sticky': 'nw', 'padx': '12', 'pady': '4', 'columnspan': '1', 'rowspan': '1'}
gI['Regex'] = {'row': '3', 'column': '1', 'sticky': 'sw', 'padx': '12', 'pady': '4', 'columnspan': '3', 'rowspan': '1'}
gI['Label'] = {'row': '4', 'column': '0', 'sticky': 'nw', 'padx': '4', 'pady': '4', 'columnspan': '5', 'rowspan': '1'} # , 'ipadx': '4'
gI['AuxFrame'] = {'row': '1', 'column': '3', 'sticky': 'ne', 'padx': '4', 'pady': '0', 'columnspan': '2', 'rowspan': '2'}
gI['Count'] = {'row': '0', 'column': '0', 'sticky': 'ne', 'padx': '0', 'pady': '4', 'columnspan': '2', 'rowspan': '1'}
gI['Markall'] = {'row': '1', 'column': '0', 'sticky': 'se', 'padx': '0', 'pady': '4', 'columnspan': '2', 'rowspan': '1'}
self.searchAuxFrame.grid(gI['AuxFrame'])
self.searchCountBtn.grid(gI['Count'])
self.searchMarkall.grid(gI['Markall'])
self.searchDirnBck.grid(gI['DirnBck'])
self.searchTargetEntry.grid(gI['Entry'])
self.searchHistToggle.grid(gI['Toggle'])
self.searchTargetEntryClear.grid(gI['Clear'])
self.searchDirnFwd.grid(gI['DirnFwd'])
self.searchBackwardsBtn.grid(gI['Backwards'])
self.searchWordsOnlyBtn.grid(gI['WordsOnly'])
self.searchWrapBtn.grid(gI['Wrap'])
self.searchCaseBtn.grid(gI['Case'])
self.searchRegexBtn.grid(gI['Regex'])
self.searchLabel.grid(gI['Label'])
def setupDimns(self):
self.searchBox.deiconify()
self.searchBox.lift()
self.update_idletasks()
self.searchWidth, self.searchHeight = self.searchBox.winfo_reqwidth(), self.searchBox.winfo_reqheight()
self.searchWidth += self.searchBox.winfo_rootx()
self.searchHeight += self.searchBox.winfo_rooty()
yForBtns = self.searchLabel.winfo_y() - self.searchWordsOnlyBtn.winfo_y()
dyHist = int((yForBtns - self.searchHistory.winfo_height()) / 2)
self.searchGridInfo['History']['pady'] = dyHist
def toggleSearchHist(self):
if self.searchHistory.winfo_ismapped():
self.searchHistory.closeBox()
gI = self.searchGridInfo
self.searchBackwardsBtn.grid(gI['Backwards'])
self.searchWordsOnlyBtn.grid(gI['WordsOnly'])
self.searchWrapBtn.grid(gI['Wrap'])
self.searchCaseBtn.grid(gI['Case'])
self.searchRegexBtn.grid(gI['Regex'])
else:
self.searchBackwardsBtn.grid_forget()
self.searchWordsOnlyBtn.grid_forget()
self.searchWrapBtn.grid_forget()
self.searchCaseBtn.grid_forget()
self.searchRegexBtn.grid_forget()
self.searchHistory.restoreBox(**self.searchGridInfo['History'])
searchStr = self.searchTargetEntry.get()
if searchStr in self.searchStrings:
idx = self.searchStrings.index(searchStr)
self.searchHistory.see(idx)
self.searchHistory.activate(idx)
def searchSelected(self, event=None):
currSelection = self.searchHistory.curselection() # returns tuple w/ indices of the selected element(s)
if len(currSelection) > 0:
searchStr = self.searchHistory.get(currSelection[0])
self.searchTarget.set(searchStr)
self.toggleSearchHist()
self.searchTargetEntry.focus_set()
return 'break'
def updateSearchHistory(self, searchStr):
if searchStr not in self.searchStrings:
self.searchStrings.insert(0, searchStr)
self.searchHistory.setContents(self.searchStrings)
def buttonState(self, contents):
if len(contents) == 0:
self.searchTargetEntryClear.config(state=DISABLED)
self.searchCountBtn.config(state=DISABLED)
self.searchMarkall.config(state=DISABLED)
else:
self.searchTargetEntryClear.config(state=NORMAL)
self.searchCountBtn.config(state=NORMAL)
self.searchMarkall.config(state=NORMAL)
return True # allow all changes
def getGeometry(self, widget, coords=False):
widget.update_idletasks()
info = widget.winfo_geometry()
widgetSize, Xoff, Yoff = info.split('+')
width, depth = widgetSize.split('x')
if coords:
return [int(Xoff), int(Yoff)]
else:
return [int(width), int(depth), int(Xoff), int(Yoff)]
def openSearchBox(self): # command for pop-up 'Search ...'
font = tkFont.nametofont(self.master.config('font')[-1])
if self.searchFontFace != font.cget('family') or self.searchFontSize != font.cget('size'):
# rebuild searchBox when font changes
mouseXY = None
if hasattr(self.searchBox, 'mouseXY'):
mouseXY = self.searchBox.mouseXY
self.searchBox.destroy()
self.createSearchBox()
if mouseXY:
self.searchBox.mouseXY = mouseXY
if not hasattr(self, 'searchWidth'):
self.setupDimns()
searchBox = self.searchBox
self.searchDirn.set(2) # so neither button is on (using .deselect, tcl error "expecting float, got ''" <wierd>)
self.searchLabelStr.set('')
self.lastPatternFound = True
self.patternMatched = False
txt = self.master
txtW = txtH = txtoffX = txtoffY = txtX = txtY = None
openAbove = False
selection = txt.tag_ranges(SEL)
openedBefore = hasattr(searchBox, 'mouseXY')
if len(selection) == 0:
self.searchTargetEntry.focus_set()
elif len(selection) == 2: # auto-add selection to Entry, set starting index
selIdx = self.lastSearchIdx = txt.index(SEL_FIRST)
selEndIdx = txt.index(SEL_LAST)
searchStr = txt.get(selIdx, selEndIdx)
self.searchTarget.set(searchStr)
self.updateSearchHistory(searchStr)
# check selection is visible so tkinter doesn't go BOOM
selBbox = txt.bbox(selIdx)
selEndBbox = txt.bbox(selEndIdx)
if selBbox is not None and selEndBbox is not None:
# create Rectangle's for txt, SEL & searchBox to check if there's an overlap
txtW, txtH, txtoffX, txtoffY = self.getGeometry(txt) # calls update_idletasks
txtX, txtY = txt.winfo_rootx(), txt.winfo_rooty()
selULx, selULy, _, _ = selBbox # relative to txt
selLRx, selLRy, width, height = selEndBbox # "
if width > height: # bbox returns very large width (>1000) for some char's, eg '\n'
width = height//2
selFullWidth = selLRy != selULy # spans multiple lines; ensure Rectangle is as wide as txt
if not selFullWidth:
selULx += txtX # absolute for Upper Left
selULy += txtY
selLRx += width + txtX # absolute for Lower Right
selLRy += height + txtY
searchULx, searchULy = searchBox.mouseXY if openedBefore else self.searchOpenXY
searchLRx = searchULx + self.searchWidth
searchLRy = searchULy + self.searchHeight
if (searchULx < selULx < searchLRx and searchULy < selULy < searchLRy) or \
(searchULx < selLRx < searchLRx and searchULy < selLRy < searchLRy) or \
selULx < searchULx < searchLRx < selLRx:
# searchBox will overlap/cover selection
openedBefore = False # force initial positon check below
def searchInWindow(newX, newY):
return txtX < newX < newX + self.searchWidth < txtX + txtW and \
txtY < newY < newY + self.searchHeight < txtY + txtH
if searchInWindow(searchULx, selLRy): # below
self.searchOpenXY = [searchULx, selLRy]
elif searchInWindow(searchULx, selULy - self.searchHeight): # above
self.searchOpenXY = [searchULx, selULy - self.searchHeight]
openAbove = True
else:
openedBefore = hasattr(searchBox, 'mouseXY') # abort movement
if openedBefore:
searchBox.restoreTop()
else: # ensure initial search box stays inside app
if txtW is None: # no selection so not set above
txtW, txtH, txtoffX, txtoffY = self.getGeometry(txt) # calls update_idletasks
txtX, txtY = txt.winfo_rootx(), txt.winfo_rooty()
appMinX, appMinY = txtX + txtoffX, txtY + txtoffY
appMaxX, appMaxY = appMinX + txtW, appMinY + txtH
searchOpenX, searchOpenY = self.searchOpenXY
if searchOpenX + self.searchWidth > appMaxX: # excceds right edge, right justify
searchOpenX = appMaxX - self.searchWidth
if searchOpenY > txtH / 2:
searchOpenY -= (0 if openAbove else self.searchHeight) + 2 * self.lineSpace
else:
searchOpenY += 2 * self.lineSpace
if searchOpenY < appMinY: # excceds top edge, top justify
searchOpenY = appMinY
if searchOpenY + self.searchHeight > appMaxY: # excceds bottom edge, bottom justify
searchOpenY = appMaxY - self.searchHeight
searchBox.showAtMouse([searchOpenX, searchOpenY])
def handleCR(self, event=None):
self.startSearch()
return 'break'
lastSearchIdx = '' # starting position of last on a subsequent search on same pattern
lastPattern = '' # last pattern searched
patternMatched = False
lastPatternFound = True
def startSearch(self, counting=False, marking=False):
reverseSearch = self.searchBackwards.get()
searchBack = self.searchDirn.get() # arrow buttons; for consistency, 1 => backwards
if searchBack == 0 or searchBack == 1: # came in via a button, they override searchBackwards
self.searchDirn.set(2) # reset button (ie. neither radiobutton)
else: # started w/ Return
searchBack = reverseSearch
pattern = self.searchTarget.get()
if len(pattern) == 0:
self.searchLabelStr.set('enter a target')
return
self.updateSearchHistory(pattern)
txt = self.master
wordsOnly = self.searchWordsOnly.get() == 1
wrapping = self.searchWrap.get() == 1
ignoreCase = self.searchCase.get() == 1
regularExpn = self.searchRegex.get() == 1
haveMarks = len(txt.tag_ranges('searchMark')) > 0
self.patternMatched = pattern == self.lastPattern and self.lastPatternFound
if not self.lastPattern or (marking and haveMarks):
txt.tag_remove('searchMark', '1.0', END)
self.searchMarkall.config(text='Mark all')
if marking and haveMarks: # button acts as a toggle
self.searchLabelStr.set('')
return
self.lastPattern = pattern
if self.lastSearchIdx == '': # first time visit
searchFrom = self.lastSearchIdx = self.formatMouseIndex()
else:
searchFrom = self.lastSearchIdx if searchBack else '{} +1c'.format(self.lastSearchIdx)
idx = searchFrom if searchBack else '{} -1c'.format(searchFrom)
stopSearch = None if wrapping or counting or marking else '1.0' if searchBack else END
findings = []
found = False
wrapped = False
while not found or counting or marking:
searchFrom = idx if searchBack else '{} +1c'.format(idx)
idx = ''
try:
idx = txt.search(pattern, searchFrom, backwards=searchBack, stopindex=stopSearch,
count=self.searchResultLen, nocase=ignoreCase, elide=1, regexp=regularExpn)
except TclError as exc:
errmsg = 'TclError: \n{}\n\n(www.tcl.tk/man/tcl8.5/TclCmd/re_syntax.htm)'.format(
exc.message.replace(':','\n'))
openMessages.append(OoInfoBox(self.top, errmsg, font=self.defaultFont))
debugLogger.error(errmsg)
except Exception as exc:
errmsg = 'Exception: {}'.format(exc)
if dca.g['debug']:
print(errmsg)
print_exc()
pdb.set_trace()
else:
debugLogger.exception(errmsg)
found = idx != ''
if not found: break
foundLength = self.searchResultLen.get()
if foundLength == 0: break # degenerate case for re's
endIdx = txt.index('{}+{}c'.format(idx, foundLength))
if wordsOnly:
if txt.compare(idx, '!=', '{} wordstart'.format(idx)) or \
txt.compare('{} +1c'.format(endIdx), '!=', '{} wordend'.format(endIdx)): # it's not a word
continue
if not found and not (counting or marking):
break # quit on 1st match in normal search
if idx in findings:
break # we've wrapped around
elif found:
findings.append(idx)
if marking:
txt.tag_add('searchMark', idx, endIdx)
haveMarks = len(txt.tag_ranges('searchMark')) > 0
self.searchMarkall.config(text='Clear marks' if haveMarks else 'Mark all')
if counting or marking:
count = len(findings)
self.searchLabelStr.set('{} matches {}'.format(
('no' if count == 0 else count), ('found' if counting else 'marked')))
return
if stopSearch is None and found and self.lastPatternFound: # check if we wrapped
wrapped = txt.compare(idx, '>=' if searchBack else '<=', self.lastSearchIdx)
if found: # "line.char" of start of match