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_nvc 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:
43 # eval is generally considered bad practice. use it wisely!
44 result = eval(script, self.namespace, self.namespace)
48 def updateNamespace(self, namespace):
49 self.namespace.update(namespace)
51 def showMessage(self, message):
52 self.appendPlainText(message)
61 prompt = '.' * len(self.prompt)
65 self.completions_pos = self.textCursor().position()
66 self.completions_visible = False
68 self.appendPlainText(prompt)
69 self.moveCursor(QtGui.QTextCursor.End)
73 curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text())
74 curr_line = curr_line.rstrip()
75 curr_line = curr_line[len(self.prompt):]
78 def setCommand(self, command):
79 if self.getCommand() == command:
83 curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text())
84 self.moveCursor(QtGui.QTextCursor.End)
85 for i in range(len(curr_line) - len(self.prompt)):
86 self.moveCursor(QtGui.QTextCursor.Left, QtGui.QTextCursor.KeepAnchor)
88 self.textCursor().removeSelectedText()
89 self.textCursor().insertText(command)
90 self.moveCursor(QtGui.QTextCursor.End)
93 def show_completions(self, completions):
94 if self.completions_visible:
95 self.hide_completions()
98 c.setPosition(self.completions_pos)
100 completions = map(lambda x: x.split('.')[-1], completions)
101 t = '\n' + ' '.join(completions)
105 self.completions_end = c.position()
107 self.moveCursor(QtGui.QTextCursor.End)
108 self.completions_visible = True
111 def hide_completions(self):
112 if not self.completions_visible:
114 c = self.textCursor()
115 c.setPosition(self.completions_pos)
116 l = self.completions_end - self.completions_pos
117 for x in range(l): c.deleteChar()
119 self.moveCursor(QtGui.QTextCursor.End)
120 self.completions_visible = False
123 def getConstruct(self, command):
125 prev_command = self.construct[-1]
126 self.construct.append(command)
127 if not prev_command and not command:
128 ret_val = '\n'.join(self.construct)
134 if command and command[-1] == (':'):
135 self.construct.append(command)
140 def getHistory(self):
143 def setHisory(self, history):
144 self.history = history
146 def addToHistory(self, command):
147 if command.find("importprivkey") > -1:
150 if command and (not self.history or self.history[-1] != command):
151 self.history.append(command)
152 self.history_index = len(self.history)
154 def getPrevHistoryEntry(self):
156 self.history_index = max(0, self.history_index - 1)
157 return self.history[self.history_index]
160 def getNextHistoryEntry(self):
162 hist_len = len(self.history)
163 self.history_index = min(hist_len, self.history_index + 1)
164 if self.history_index < hist_len:
165 return self.history[self.history_index]
168 def getCursorPosition(self):
169 c = self.textCursor()
170 return c.position() - c.block().position() - len(self.prompt)
172 def setCursorPosition(self, position):
173 self.moveCursor(QtGui.QTextCursor.StartOfLine)
174 for i in range(len(self.prompt) + position):
175 self.moveCursor(QtGui.QTextCursor.Right)
177 def register_command(self, c, func):
179 self.updateNamespace(methods)
182 def runCommand(self):
183 command = self.getCommand()
184 self.addToHistory(command)
186 command = self.getConstruct(command)
189 tmp_stdout = sys.stdout
192 def __init__(self, write_func):
193 self.write_func = write_func
199 def write(self, text):
201 stripped_text = text.rstrip('\n')
202 self.write_func(stripped_text)
203 QtCore.QCoreApplication.processEvents()
204 self.skip = not self.skip
206 if type(self.namespace.get(command)) == type(lambda:None):
207 self.appendPlainText("'%s' is a function. Type '%s()' to use it in the Python console."%(command, command))
211 sys.stdout = stdoutProxy(self.appendPlainText)
214 # eval is generally considered bad practice. use it wisely!
215 result = eval(command, self.namespace, self.namespace)
218 util.print_json(result)
220 self.appendPlainText(repr(result))
222 # exec is generally considered bad practice. use it wisely!
223 exec command in self.namespace
227 traceback_lines = traceback.format_exc().split('\n')
228 # Remove traceback mentioning this file, and a linebreak
230 traceback_lines.pop(i)
231 self.appendPlainText('\n'.join(traceback_lines))
232 sys.stdout = tmp_stdout
237 def keyPressEvent(self, event):
238 if event.key() == QtCore.Qt.Key_Tab:
242 self.hide_completions()
244 if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
247 if event.key() == QtCore.Qt.Key_Home:
248 self.setCursorPosition(0)
250 if event.key() == QtCore.Qt.Key_PageUp:
252 elif event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace):
253 if self.getCursorPosition() == 0:
255 elif event.key() == QtCore.Qt.Key_Up:
256 self.setCommand(self.getPrevHistoryEntry())
258 elif event.key() == QtCore.Qt.Key_Down:
259 self.setCommand(self.getNextHistoryEntry())
261 elif event.key() == QtCore.Qt.Key_L and event.modifiers() == QtCore.Qt.ControlModifier:
264 super(Console, self).keyPressEvent(event)
268 def completions(self):
269 cmd = self.getCommand()
270 lastword = re.split(' |\(|\)',cmd)[-1]
271 beginning = cmd[0:-len(lastword)]
273 path = lastword.split('.')
274 ns = self.namespace.keys()
280 obj = self.namespace.get(path[0])
281 prefix = path[0] + '.'
287 if x[0] == '_':continue
289 if xx.startswith(lastword):
290 completions.append(xx)
294 self.hide_completions()
295 elif len(completions) == 1:
296 self.hide_completions()
297 self.setCommand(beginning + completions[0])
300 p = os.path.commonprefix(completions)
301 if len(p)>len(lastword):
302 self.hide_completions()
303 self.setCommand(beginning + p)
305 self.show_completions(completions)
308 welcome_message = '''
309 ---------------------------------------------------------------
310 Welcome to a primitive Python interpreter.
311 ---------------------------------------------------------------
314 if __name__ == '__main__':
315 app = QtGui.QApplication(sys.argv)
316 console = Console(startup_message=welcome_message)
317 console.updateNamespace({'myVar1' : app, 'myVar2' : 1234})
319 sys.exit(app.exec_())