abaff867775038c9476213b365f1ab704ffeb423
[electrum-nvc.git] / lib / qt_console.py
1 # source: http://stackoverflow.com/questions/2758159/how-to-embed-a-python-interpreter-in-a-pyqt-widget
2
3 import sys, os, re
4 import traceback
5 from PyQt4 import QtCore
6 from PyQt4 import QtGui
7
8
9
10 class Console(QtGui.QPlainTextEdit):
11     def __init__(self, prompt='>> ', startup_message='', parent=None):
12         QtGui.QPlainTextEdit.__init__(self, parent)
13
14         self.prompt = prompt
15         self.history = []
16         self.namespace = {}
17         self.construct = []
18
19         self.setGeometry(50, 75, 600, 400)
20         self.setWordWrapMode(QtGui.QTextOption.WrapAnywhere)
21         self.setUndoRedoEnabled(False)
22         self.document().setDefaultFont(QtGui.QFont("monospace", 10, QtGui.QFont.Normal))
23         self.showMessage(startup_message)
24
25         self.updateNamespace({'run':self.run_script})
26     
27     def run_script(self, filename):
28         with open(filename) as f:
29             script = f.read()
30         result = eval(script, self.namespace, self.namespace)
31
32
33
34     def updateNamespace(self, namespace):
35         self.namespace.update(namespace)
36
37     def showMessage(self, message):
38         self.appendPlainText(message)
39         self.newPrompt()
40
41     def clear(self):
42         self.setPlainText('')
43         self.newPrompt()
44
45     def newPrompt(self):
46         if self.construct:
47             prompt = '.' * len(self.prompt)
48         else:
49             prompt = self.prompt
50
51         self.completions_pos = self.textCursor().position()
52         self.completions_visible = False
53
54         self.appendPlainText(prompt)
55         self.moveCursor(QtGui.QTextCursor.End)
56
57     def getCommand(self):
58         doc = self.document()
59         curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text())
60         curr_line = curr_line.rstrip()
61         curr_line = curr_line[len(self.prompt):]
62         return curr_line
63
64     def setCommand(self, command):
65         if self.getCommand() == command:
66             return
67         self.moveCursor(QtGui.QTextCursor.End)
68         self.moveCursor(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.KeepAnchor)
69         for i in range(len(self.prompt)):
70             self.moveCursor(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor)
71         self.textCursor().removeSelectedText()
72         self.textCursor().insertText(command)
73         self.moveCursor(QtGui.QTextCursor.End)
74
75
76     def show_completions(self, completions):
77         if self.completions_visible:
78             self.hide_completions()
79
80         c = self.textCursor()
81         c.setPosition(self.completions_pos)
82
83         completions = map(lambda x: x.split('.')[-1], completions)
84         t = '\n' + ' '.join(completions)
85         if len(t) > 500:
86             t = t[:500] + '...'
87         c.insertText(t)
88         self.completions_end = c.position()
89
90         self.moveCursor(QtGui.QTextCursor.End)
91         self.completions_visible = True
92         
93
94     def hide_completions(self):
95         if not self.completions_visible:
96             return
97         c = self.textCursor()
98         c.setPosition(self.completions_pos)
99         l = self.completions_end - self.completions_pos
100         for x in range(l): c.deleteChar()
101
102         self.moveCursor(QtGui.QTextCursor.End)
103         self.completions_visible = False
104
105
106     def getConstruct(self, command):
107         if self.construct:
108             prev_command = self.construct[-1]
109             self.construct.append(command)
110             if not prev_command and not command:
111                 ret_val = '\n'.join(self.construct)
112                 self.construct = []
113                 return ret_val
114             else:
115                 return ''
116         else:
117             if command and command[-1] == (':'):
118                 self.construct.append(command)
119                 return ''
120             else:
121                 return command
122
123     def getHistory(self):
124         return self.history
125
126     def setHisory(self, history):
127         self.history = history
128
129     def addToHistory(self, command):
130         if command and (not self.history or self.history[-1] != command):
131             self.history.append(command)
132         self.history_index = len(self.history)
133
134     def getPrevHistoryEntry(self):
135         if self.history:
136             self.history_index = max(0, self.history_index - 1)
137             return self.history[self.history_index]
138         return ''
139
140     def getNextHistoryEntry(self):
141         if self.history:
142             hist_len = len(self.history)
143             self.history_index = min(hist_len, self.history_index + 1)
144             if self.history_index < hist_len:
145                 return self.history[self.history_index]
146         return ''
147
148     def getCursorPosition(self):
149         return self.textCursor().columnNumber() - len(self.prompt)
150
151     def setCursorPosition(self, position):
152         self.moveCursor(QtGui.QTextCursor.StartOfLine)
153         for i in range(len(self.prompt) + position):
154             self.moveCursor(QtGui.QTextCursor.Right)
155
156     def runCommand(self):
157         command = self.getCommand()
158         self.addToHistory(command)
159
160         command = self.getConstruct(command)
161
162         if command:
163             tmp_stdout = sys.stdout
164
165             class stdoutProxy():
166                 def __init__(self, write_func):
167                     self.write_func = write_func
168                     self.skip = False
169
170                 def flush(self):
171                     pass
172
173                 def write(self, text):
174                     if not self.skip:
175                         stripped_text = text.rstrip('\n')
176                         self.write_func(stripped_text)
177                         QtCore.QCoreApplication.processEvents()
178                     self.skip = not self.skip
179
180             if command == 'help()':
181                 self.appendPlainText("no help here!")
182                 self.newPrompt()
183                 return
184
185             sys.stdout = stdoutProxy(self.appendPlainText)
186             try:
187                 try:
188                     result = eval(command, self.namespace, self.namespace)
189                     if result != None:
190                         self.appendPlainText(repr(result))
191                 except SyntaxError:
192                     exec command in self.namespace
193             except SystemExit:
194                 self.close()
195             except:
196                 traceback_lines = traceback.format_exc().split('\n')
197                 # Remove traceback mentioning this file, and a linebreak
198                 for i in (3,2,1,-1):
199                     traceback_lines.pop(i)
200                 self.appendPlainText('\n'.join(traceback_lines))
201             sys.stdout = tmp_stdout
202         self.newPrompt()
203
204     def keyPressEvent(self, event):
205         if event.key() == QtCore.Qt.Key_Tab:
206             self.completions()
207             return
208
209         self.hide_completions()
210
211         if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
212             self.runCommand()
213             return
214         if event.key() == QtCore.Qt.Key_Home:
215             self.setCursorPosition(0)
216             return
217         if event.key() == QtCore.Qt.Key_PageUp:
218             return
219         elif event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace):
220             if self.getCursorPosition() == 0:
221                 return
222         elif event.key() == QtCore.Qt.Key_Up:
223             self.setCommand(self.getPrevHistoryEntry())
224             return
225         elif event.key() == QtCore.Qt.Key_Down:
226             self.setCommand(self.getNextHistoryEntry())
227             return
228         elif event.key() == QtCore.Qt.Key_L and event.modifiers() == QtCore.Qt.ControlModifier:
229             self.clear()
230
231         super(Console, self).keyPressEvent(event)
232
233
234
235     def completions(self):
236         cmd = self.getCommand()
237         lastword = re.split(' |\(|\)',cmd)[-1]
238         beginning = cmd[0:-len(lastword)]
239
240         path = lastword.split('.')
241         ns = self.namespace.keys()
242
243         if len(path) == 1:
244             ns = ns
245             prefix = ''
246         else:
247             obj = self.namespace.get(path[0])
248             prefix = path[0] + '.'
249             ns = dir(obj)
250             
251
252         completions = []
253         for x in ns:
254             if x[0] == '_':continue
255             xx = prefix + x
256             if xx.startswith(lastword):
257                 completions.append(xx)
258                 
259         if not completions:
260             self.hide_completions()
261         elif len(completions) == 1:
262             self.hide_completions()
263             self.setCommand(beginning + completions[0])
264         else:
265             # find common prefix
266             p = os.path.commonprefix(completions)
267             if len(p)>len(lastword):
268                 self.hide_completions()
269                 self.setCommand(beginning + p)
270             else:
271                 self.show_completions(completions)
272
273
274 welcome_message = '''
275    ---------------------------------------------------------------
276      Welcome to a primitive Python interpreter.
277    ---------------------------------------------------------------
278 '''
279
280 if __name__ == '__main__':
281     app = QtGui.QApplication(sys.argv)
282     console = Console(startup_message=welcome_message)
283     console.updateNamespace({'myVar1' : app, 'myVar2' : 1234})
284     console.show();
285     sys.exit(app.exec_())