1 # source: http://stackoverflow.com/questions/2758159/how-to-embed-a-python-interpreter-in-a-pyqt-widget
5 from PyQt4 import QtCore
6 from PyQt4 import QtGui
7 from electrum import util
11 class Console(QtGui.QPlainTextEdit):
12 def __init__(self, prompt='>> ', startup_message='', parent=None):
13 QtGui.QPlainTextEdit.__init__(self, parent)
20 self.setGeometry(50, 75, 600, 400)
21 self.setWordWrapMode(QtGui.QTextOption.WrapAnywhere)
22 self.setUndoRedoEnabled(False)
23 self.document().setDefaultFont(QtGui.QFont("monospace", 10, QtGui.QFont.Normal))
24 self.showMessage(startup_message)
26 self.updateNamespace({'run':self.run_script})
29 def set_json(self, b):
32 def run_script(self, filename):
33 with open(filename) as f:
35 result = eval(script, self.namespace, self.namespace)
39 def updateNamespace(self, namespace):
40 self.namespace.update(namespace)
42 def showMessage(self, message):
43 self.appendPlainText(message)
52 prompt = '.' * len(self.prompt)
56 self.completions_pos = self.textCursor().position()
57 self.completions_visible = False
59 self.appendPlainText(prompt)
60 self.moveCursor(QtGui.QTextCursor.End)
64 curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text())
65 curr_line = curr_line.rstrip()
66 curr_line = curr_line[len(self.prompt):]
69 def setCommand(self, command):
70 if self.getCommand() == command:
72 self.moveCursor(QtGui.QTextCursor.End)
73 self.moveCursor(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.KeepAnchor)
74 for i in range(len(self.prompt)):
75 self.moveCursor(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor)
76 self.textCursor().removeSelectedText()
77 self.textCursor().insertText(command)
78 self.moveCursor(QtGui.QTextCursor.End)
81 def show_completions(self, completions):
82 if self.completions_visible:
83 self.hide_completions()
86 c.setPosition(self.completions_pos)
88 completions = map(lambda x: x.split('.')[-1], completions)
89 t = '\n' + ' '.join(completions)
93 self.completions_end = c.position()
95 self.moveCursor(QtGui.QTextCursor.End)
96 self.completions_visible = True
99 def hide_completions(self):
100 if not self.completions_visible:
102 c = self.textCursor()
103 c.setPosition(self.completions_pos)
104 l = self.completions_end - self.completions_pos
105 for x in range(l): c.deleteChar()
107 self.moveCursor(QtGui.QTextCursor.End)
108 self.completions_visible = False
111 def getConstruct(self, command):
113 prev_command = self.construct[-1]
114 self.construct.append(command)
115 if not prev_command and not command:
116 ret_val = '\n'.join(self.construct)
122 if command and command[-1] == (':'):
123 self.construct.append(command)
128 def getHistory(self):
131 def setHisory(self, history):
132 self.history = history
134 def addToHistory(self, command):
135 if command and (not self.history or self.history[-1] != command):
136 self.history.append(command)
137 self.history_index = len(self.history)
139 def getPrevHistoryEntry(self):
141 self.history_index = max(0, self.history_index - 1)
142 return self.history[self.history_index]
145 def getNextHistoryEntry(self):
147 hist_len = len(self.history)
148 self.history_index = min(hist_len, self.history_index + 1)
149 if self.history_index < hist_len:
150 return self.history[self.history_index]
153 def getCursorPosition(self):
154 return self.textCursor().columnNumber() - len(self.prompt)
156 def setCursorPosition(self, position):
157 self.moveCursor(QtGui.QTextCursor.StartOfLine)
158 for i in range(len(self.prompt) + position):
159 self.moveCursor(QtGui.QTextCursor.Right)
161 def runCommand(self):
162 command = self.getCommand()
163 self.addToHistory(command)
165 command = self.getConstruct(command)
168 tmp_stdout = sys.stdout
171 def __init__(self, write_func):
172 self.write_func = write_func
178 def write(self, text):
180 stripped_text = text.rstrip('\n')
181 self.write_func(stripped_text)
182 QtCore.QCoreApplication.processEvents()
183 self.skip = not self.skip
185 if command == 'help()':
186 self.appendPlainText("no help here!")
190 sys.stdout = stdoutProxy(self.appendPlainText)
193 result = eval(command, self.namespace, self.namespace)
196 util.print_json(result)
198 self.appendPlainText(repr(result))
200 exec command in self.namespace
204 traceback_lines = traceback.format_exc().split('\n')
205 # Remove traceback mentioning this file, and a linebreak
207 traceback_lines.pop(i)
208 self.appendPlainText('\n'.join(traceback_lines))
209 sys.stdout = tmp_stdout
214 def keyPressEvent(self, event):
215 if event.key() == QtCore.Qt.Key_Tab:
219 self.hide_completions()
221 if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
224 if event.key() == QtCore.Qt.Key_Home:
225 self.setCursorPosition(0)
227 if event.key() == QtCore.Qt.Key_PageUp:
229 elif event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace):
230 if self.getCursorPosition() == 0:
232 elif event.key() == QtCore.Qt.Key_Up:
233 self.setCommand(self.getPrevHistoryEntry())
235 elif event.key() == QtCore.Qt.Key_Down:
236 self.setCommand(self.getNextHistoryEntry())
238 elif event.key() == QtCore.Qt.Key_L and event.modifiers() == QtCore.Qt.ControlModifier:
241 super(Console, self).keyPressEvent(event)
245 def completions(self):
246 cmd = self.getCommand()
247 lastword = re.split(' |\(|\)',cmd)[-1]
248 beginning = cmd[0:-len(lastword)]
250 path = lastword.split('.')
251 ns = self.namespace.keys()
257 obj = self.namespace.get(path[0])
258 prefix = path[0] + '.'
264 if x[0] == '_':continue
266 if xx.startswith(lastword):
267 completions.append(xx)
271 self.hide_completions()
272 elif len(completions) == 1:
273 self.hide_completions()
274 self.setCommand(beginning + completions[0])
277 p = os.path.commonprefix(completions)
278 if len(p)>len(lastword):
279 self.hide_completions()
280 self.setCommand(beginning + p)
282 self.show_completions(completions)
285 welcome_message = '''
286 ---------------------------------------------------------------
287 Welcome to a primitive Python interpreter.
288 ---------------------------------------------------------------
291 if __name__ == '__main__':
292 app = QtGui.QApplication(sys.argv)
293 console = Console(startup_message=welcome_message)
294 console.updateNamespace({'myVar1' : app, 'myVar2' : 1234})
296 sys.exit(app.exec_())