1
# source: http://stackoverflow.com/questions/2758159/how-to-embed-a-python-interpreter-in-a-pyqt-widget
4
import traceback, platform
5
from PyQt4 import QtCore
6
from PyQt4 import QtGui
7
from electrum import util
10
if platform.system() == 'Windows':
11
MONOSPACE_FONT = 'Lucida Console'
12
elif platform.system() == 'Darwin':
13
MONOSPACE_FONT = 'Monaco'
15
MONOSPACE_FONT = 'monospace'
18
class Console(QtGui.QPlainTextEdit):
19
def __init__(self, prompt='>> ', startup_message='', parent=None):
20
QtGui.QPlainTextEdit.__init__(self, parent)
27
self.setGeometry(50, 75, 600, 400)
28
self.setWordWrapMode(QtGui.QTextOption.WrapAnywhere)
29
self.setUndoRedoEnabled(False)
30
self.document().setDefaultFont(QtGui.QFont(MONOSPACE_FONT, 10, QtGui.QFont.Normal))
31
self.showMessage(startup_message)
33
self.updateNamespace({'run':self.run_script})
36
def set_json(self, b):
39
def run_script(self, filename):
40
with open(filename) as f:
42
result = eval(script, self.namespace, self.namespace)
46
def updateNamespace(self, namespace):
47
self.namespace.update(namespace)
49
def showMessage(self, message):
50
self.appendPlainText(message)
59
prompt = '.' * len(self.prompt)
63
self.completions_pos = self.textCursor().position()
64
self.completions_visible = False
66
self.appendPlainText(prompt)
67
self.moveCursor(QtGui.QTextCursor.End)
71
curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text())
72
curr_line = curr_line.rstrip()
73
curr_line = curr_line[len(self.prompt):]
76
def setCommand(self, command):
77
if self.getCommand() == command:
81
curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text())
82
self.moveCursor(QtGui.QTextCursor.End)
83
for i in range(len(curr_line) - len(self.prompt)):
84
self.moveCursor(QtGui.QTextCursor.Left, QtGui.QTextCursor.KeepAnchor)
86
self.textCursor().removeSelectedText()
87
self.textCursor().insertText(command)
88
self.moveCursor(QtGui.QTextCursor.End)
91
def show_completions(self, completions):
92
if self.completions_visible:
93
self.hide_completions()
96
c.setPosition(self.completions_pos)
98
completions = map(lambda x: x.split('.')[-1], completions)
99
t = '\n' + ' '.join(completions)
103
self.completions_end = c.position()
105
self.moveCursor(QtGui.QTextCursor.End)
106
self.completions_visible = True
109
def hide_completions(self):
110
if not self.completions_visible:
112
c = self.textCursor()
113
c.setPosition(self.completions_pos)
114
l = self.completions_end - self.completions_pos
115
for x in range(l): c.deleteChar()
117
self.moveCursor(QtGui.QTextCursor.End)
118
self.completions_visible = False
121
def getConstruct(self, command):
123
prev_command = self.construct[-1]
124
self.construct.append(command)
125
if not prev_command and not command:
126
ret_val = '\n'.join(self.construct)
132
if command and command[-1] == (':'):
133
self.construct.append(command)
138
def getHistory(self):
141
def setHisory(self, history):
142
self.history = history
144
def addToHistory(self, command):
145
if command and (not self.history or self.history[-1] != command):
146
self.history.append(command)
147
self.history_index = len(self.history)
149
def getPrevHistoryEntry(self):
151
self.history_index = max(0, self.history_index - 1)
152
return self.history[self.history_index]
155
def getNextHistoryEntry(self):
157
hist_len = len(self.history)
158
self.history_index = min(hist_len, self.history_index + 1)
159
if self.history_index < hist_len:
160
return self.history[self.history_index]
163
def getCursorPosition(self):
164
c = self.textCursor()
165
return c.position() - c.block().position() - len(self.prompt)
167
def setCursorPosition(self, position):
168
self.moveCursor(QtGui.QTextCursor.StartOfLine)
169
for i in range(len(self.prompt) + position):
170
self.moveCursor(QtGui.QTextCursor.Right)
172
def register_command(self, c, func):
174
self.updateNamespace(methods)
177
def runCommand(self):
178
command = self.getCommand()
179
self.addToHistory(command)
181
command = self.getConstruct(command)
184
tmp_stdout = sys.stdout
187
def __init__(self, write_func):
188
self.write_func = write_func
194
def write(self, text):
196
stripped_text = text.rstrip('\n')
197
self.write_func(stripped_text)
198
QtCore.QCoreApplication.processEvents()
199
self.skip = not self.skip
201
if type(self.namespace.get(command)) == type(lambda:None):
202
self.appendPlainText("'%s' is a function. Type '%s()' to use it in the Python console."%(command, command))
206
sys.stdout = stdoutProxy(self.appendPlainText)
209
result = eval(command, self.namespace, self.namespace)
212
util.print_json(result)
214
self.appendPlainText(repr(result))
216
exec command in self.namespace
220
traceback_lines = traceback.format_exc().split('\n')
221
# Remove traceback mentioning this file, and a linebreak
223
traceback_lines.pop(i)
224
self.appendPlainText('\n'.join(traceback_lines))
225
sys.stdout = tmp_stdout
230
def keyPressEvent(self, event):
231
if event.key() == QtCore.Qt.Key_Tab:
235
self.hide_completions()
237
if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
240
if event.key() == QtCore.Qt.Key_Home:
241
self.setCursorPosition(0)
243
if event.key() == QtCore.Qt.Key_PageUp:
245
elif event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace):
246
if self.getCursorPosition() == 0:
248
elif event.key() == QtCore.Qt.Key_Up:
249
self.setCommand(self.getPrevHistoryEntry())
251
elif event.key() == QtCore.Qt.Key_Down:
252
self.setCommand(self.getNextHistoryEntry())
254
elif event.key() == QtCore.Qt.Key_L and event.modifiers() == QtCore.Qt.ControlModifier:
257
super(Console, self).keyPressEvent(event)
261
def completions(self):
262
cmd = self.getCommand()
263
lastword = re.split(' |\(|\)',cmd)[-1]
264
beginning = cmd[0:-len(lastword)]
266
path = lastword.split('.')
267
ns = self.namespace.keys()
273
obj = self.namespace.get(path[0])
274
prefix = path[0] + '.'
280
if x[0] == '_':continue
282
if xx.startswith(lastword):
283
completions.append(xx)
287
self.hide_completions()
288
elif len(completions) == 1:
289
self.hide_completions()
290
self.setCommand(beginning + completions[0])
293
p = os.path.commonprefix(completions)
294
if len(p)>len(lastword):
295
self.hide_completions()
296
self.setCommand(beginning + p)
298
self.show_completions(completions)
301
welcome_message = '''
302
---------------------------------------------------------------
303
Welcome to a primitive Python interpreter.
304
---------------------------------------------------------------
307
if __name__ == '__main__':
308
app = QtGui.QApplication(sys.argv)
309
console = Console(startup_message=welcome_message)
310
console.updateNamespace({'myVar1' : app, 'myVar2' : 1234})
312
sys.exit(app.exec_())