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.find("importprivkey") > -1:
148 if command and (not self.history or self.history[-1] != command):
149 self.history.append(command)
150 self.history_index = len(self.history)
152 def getPrevHistoryEntry(self):
154 self.history_index = max(0, self.history_index - 1)
155 return self.history[self.history_index]
158 def getNextHistoryEntry(self):
160 hist_len = len(self.history)
161 self.history_index = min(hist_len, self.history_index + 1)
162 if self.history_index < hist_len:
163 return self.history[self.history_index]
166 def getCursorPosition(self):
167 c = self.textCursor()
168 return c.position() - c.block().position() - len(self.prompt)
170 def setCursorPosition(self, position):
171 self.moveCursor(QtGui.QTextCursor.StartOfLine)
172 for i in range(len(self.prompt) + position):
173 self.moveCursor(QtGui.QTextCursor.Right)
175 def register_command(self, c, func):
177 self.updateNamespace(methods)
180 def runCommand(self):
181 command = self.getCommand()
182 self.addToHistory(command)
184 command = self.getConstruct(command)
187 tmp_stdout = sys.stdout
190 def __init__(self, write_func):
191 self.write_func = write_func
197 def write(self, text):
199 stripped_text = text.rstrip('\n')
200 self.write_func(stripped_text)
201 QtCore.QCoreApplication.processEvents()
202 self.skip = not self.skip
204 if type(self.namespace.get(command)) == type(lambda:None):
205 self.appendPlainText("'%s' is a function. Type '%s()' to use it in the Python console."%(command, command))
209 sys.stdout = stdoutProxy(self.appendPlainText)
212 result = eval(command, self.namespace, self.namespace)
215 util.print_json(result)
217 self.appendPlainText(repr(result))
219 exec command in self.namespace
223 traceback_lines = traceback.format_exc().split('\n')
224 # Remove traceback mentioning this file, and a linebreak
226 traceback_lines.pop(i)
227 self.appendPlainText('\n'.join(traceback_lines))
228 sys.stdout = tmp_stdout
233 def keyPressEvent(self, event):
234 if event.key() == QtCore.Qt.Key_Tab:
238 self.hide_completions()
240 if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
243 if event.key() == QtCore.Qt.Key_Home:
244 self.setCursorPosition(0)
246 if event.key() == QtCore.Qt.Key_PageUp:
248 elif event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace):
249 if self.getCursorPosition() == 0:
251 elif event.key() == QtCore.Qt.Key_Up:
252 self.setCommand(self.getPrevHistoryEntry())
254 elif event.key() == QtCore.Qt.Key_Down:
255 self.setCommand(self.getNextHistoryEntry())
257 elif event.key() == QtCore.Qt.Key_L and event.modifiers() == QtCore.Qt.ControlModifier:
260 super(Console, self).keyPressEvent(event)
264 def completions(self):
265 cmd = self.getCommand()
266 lastword = re.split(' |\(|\)',cmd)[-1]
267 beginning = cmd[0:-len(lastword)]
269 path = lastword.split('.')
270 ns = self.namespace.keys()
276 obj = self.namespace.get(path[0])
277 prefix = path[0] + '.'
283 if x[0] == '_':continue
285 if xx.startswith(lastword):
286 completions.append(xx)
290 self.hide_completions()
291 elif len(completions) == 1:
292 self.hide_completions()
293 self.setCommand(beginning + completions[0])
296 p = os.path.commonprefix(completions)
297 if len(p)>len(lastword):
298 self.hide_completions()
299 self.setCommand(beginning + p)
301 self.show_completions(completions)
304 welcome_message = '''
305 ---------------------------------------------------------------
306 Welcome to a primitive Python interpreter.
307 ---------------------------------------------------------------
310 if __name__ == '__main__':
311 app = QtGui.QApplication(sys.argv)
312 console = Console(startup_message=welcome_message)
313 console.updateNamespace({'myVar1' : app, 'myVar2' : 1234})
315 sys.exit(app.exec_())