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