forked from wonder-sk/qgis-first-aid-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
debugwidget.py
300 lines (231 loc) · 9.14 KB
/
debugwidget.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
from __future__ import absolute_import
#-----------------------------------------------------------
# Copyright (C) 2015 Martin Dobias
#-----------------------------------------------------------
# Licensed under the terms of GNU GPL 2
#
# 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 2 of the License, or
# (at your option) any later version.
#---------------------------------------------------------------------
from qgis.PyQt.QtWidgets import (QWidget,
QLineEdit,
QTextEdit,
QVBoxLayout,
QMessageBox,
QSplitter,
QApplication,
QLabel,
QDialog,
QDialogButtonBox)
from future import standard_library
standard_library.install_aliases()
from builtins import str
import sip
sip.setapi('QVariant', 2)
sip.setapi('QString', 2)
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
from qgis.gui import QgsGui
import sys
from .variablesview import VariablesView
from .sourceview import SourceView
from .framesview import FramesView
import code
import traceback
from contextlib import contextmanager
def frame_from_traceback(tb, index):
while index > 0:
#print vindex, tb
tb = tb.tb_next
index -= 1
return tb.tb_frame
@contextmanager
def stdout_redirected(new_stdout):
save_stdout = sys.stdout
sys.stdout = new_stdout
try:
yield None
finally:
sys.stdout = save_stdout
class ConsoleInput(QLineEdit):
execLine = pyqtSignal(str)
def __init__(self, parent=None):
QLineEdit.__init__(self, parent)
self.history = []
self.history_index = 0
def keyPressEvent(self, event):
if event.key() == Qt.Key_Up:
self.history_index = max(self.history_index - 1, -len(self.history))
self.setText(self.history[self.history_index])
elif event.key() == Qt.Key_Down:
if self.history_index == 0:
return
elif self.history_index == -1:
self.history_index = 0
self.clear()
else:
self.history_index += 1
self.setText(self.history[self.history_index])
elif event.key() == Qt.Key_Return:
self.history_index = 0
self.history.append(self.text())
self.execLine.emit(self.text())
else:
QLineEdit.keyPressEvent(self, event)
class ConsoleWidget(QWidget):
def __init__(self, exc_info, parent=None):
QWidget.__init__(self, parent)
self.compiler = code.CommandCompiler() # for console
self.tb = exc_info[2]
self.entries = traceback.extract_tb(self.tb)
self.console = ConsoleInput()
self.console.setPlaceholderText(">>> Python Console")
self.console.execLine.connect(self.exec_console)
self.console.setFont(QFont("Courier"))
self.console_out = QTextEdit()
self.console_out.setReadOnly(True)
self.console_out.setFont(QFont("Courier"))
self.console_out.setVisible(False) # initially hidden
self.console_outs = ['']*len(self.entries)
self.frame_vars = [None]*len(self.entries)
l = QVBoxLayout()
l.addWidget(self.console_out)
l.addWidget(self.console)
l.setContentsMargins(0,0,0,0)
self.setLayout(l)
def go_to_frame(self, index):
self.console_out.setPlainText(self.console_outs[index])
self.current_frame_index = index
def exec_console(self, line):
index = self.current_frame_index
if index < 0: return
# cache frame variables (globals and locals)
# because every time we ask for frame.f_locals, a new dict instance
# is created - we keep our local cache that may contain some changes
if self.frame_vars[index] is None:
#print "init", index
frame = frame_from_traceback(self.tb, index)
self.frame_vars[index] = (dict(frame.f_globals), dict(frame.f_locals))
frame_vars = self.frame_vars[index]
#print frame_vars[1]
try:
c = self.compiler(line, "<console>", "single")
except (OverflowError, SyntaxError, ValueError) as e:
QMessageBox.critical(self, "Error", str(e))
return
if c is None:
QMessageBox.critical(self, "Error", "Code not complete")
return
import io
io = io.StringIO() if sys.version_info.major >= 3 else io.BytesIO()
try:
with stdout_redirected(io):
exec(c, frame_vars[0], frame_vars[1])
except:
etype, value, tb = sys.exc_info()
QMessageBox.critical(self, "Error", etype.__name__ + "\n" + str(value))
return
stuff = self.console_outs[index]
stuff += ">>> " + line + "\n"
stuff += io.getvalue()
self.console_outs[index] = stuff
self.console_out.setPlainText(stuff)
self.console_out.setVisible(True)
# make sure we are at the end
c = self.console_out.textCursor()
c.movePosition(QTextCursor.End)
self.console_out.setTextCursor(c)
self.console_out.ensureCursorVisible()
self.console.setText('')
class DebugWidget(QWidget):
def __init__(self, exc_info, parent=None):
QWidget.__init__(self, parent)
etype, value, tb = exc_info
self.tb = tb
self.entries = traceback.extract_tb(tb)
self.setWindowTitle('Python Error')
msg = str(value).replace("\n", "<br>").replace(" ", " ")
self.error = QLabel("<h1>"+etype.__name__+"</h1><b>"+msg+"</b>")
self.error.setTextInteractionFlags(Qt.TextSelectableByMouse)
self.frames = FramesView()
self.frames.setTraceback(tb)
self.frames.selectionModel().currentChanged.connect(self.current_frame_changed)
self.source = SourceView()
self.splitterSrc = QSplitter(Qt.Horizontal)
self.splitterSrc.addWidget(self.frames)
self.splitterSrc.addWidget(self.source)
self.splitterSrc.setStretchFactor(0, 1)
self.splitterSrc.setStretchFactor(1, 2)
self.variables = VariablesView()
self.console = ConsoleWidget(exc_info)
self.splitterMain = QSplitter(Qt.Vertical)
self.splitterMain.addWidget(self.splitterSrc)
interactive_widget = QWidget()
interactive_layout = QVBoxLayout()
interactive_layout.setContentsMargins(0, 0, 0, 0)
interactive_layout.addWidget(self.variables, 1)
interactive_layout.addWidget(self.console)
interactive_widget.setLayout(interactive_layout)
self.splitterMain.addWidget(interactive_widget)
l = QVBoxLayout()
l.addWidget(self.error)
l.addWidget(self.splitterMain)
l.setContentsMargins(0,0,0,0)
self.setLayout(l)
self.resize(800,600)
s = QSettings()
self.splitterSrc.restoreState(s.value("/FirstAid/splitterSrc", b""))
self.splitterMain.restoreState(s.value("/FirstAid/splitterMain", b""))
# select the last frame
self.frames.setCurrentIndex(self.frames.model().index(len(self.entries)-1))
def closeEvent(self, event):
s = QSettings()
s.setValue("/FirstAid/splitterSrc", self.splitterSrc.saveState())
s.setValue("/FirstAid/splitterMain", self.splitterMain.saveState())
QWidget.closeEvent(self, event)
def current_frame_changed(self, current, previous):
row = current.row()
if row >= 0 and row < len(self.entries):
self.go_to_frame(row)
def go_to_frame(self, index):
filename = self.entries[index][0]
lineno = self.entries[index][1]
self.source.openFile(filename)
self.source.jumpToLine(lineno)
local_vars = frame_from_traceback(self.tb, index).f_locals
self.variables.setVariables(local_vars)
self.console.go_to_frame(index)
class DebugDialog(QDialog):
def __init__(self, exc_info, parent=None):
QDialog.__init__(self, parent)
self.setObjectName('FirstAidDebugDialog')
self.setWindowTitle('Python Error')
self.debug_widget = DebugWidget(exc_info)
layout = QVBoxLayout()
layout.addWidget(self.debug_widget, 1)
self.button_box = QDialogButtonBox(QDialogButtonBox.Close)
self.button_box.rejected.connect(self.reject)
layout.addWidget(self.button_box)
self.setLayout(layout)
QgsGui.enableAutoGeometryRestore(self)
#####################################
# test
def err_here(a,b):
c = a+b
c += d
def call_err():
a = 1
b = 2
err_here(a,b)
if __name__ == '__main__':
a = QApplication(sys.argv)
QCoreApplication.setOrganizationName("Test")
QCoreApplication.setApplicationName("Test App")
try:
call_err()
except Exception as e:
w = DebugWidget(sys.exc_info())
w.show()
a.exec_()