e7d05e9bbcc26ea8924309ce35a5714d36606a4f
[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, platform
5 from PyQt4 import QtCore
6 from PyQt4 import QtGui
7 from electrum import util
8
9
10 if platform.system() == 'Windows':
11     MONOSPACE_FONT = 'Lucida Console'
12 elif platform.system() == 'Darwin':
13     MONOSPACE_FONT = 'Monaco'
14 else:
15     MONOSPACE_FONT = 'monospace'
16
17
18 class Console(QtGui.QPlainTextEdit):
19     def __init__(self, prompt='>> ', startup_message='', parent=None):
20         QtGui.QPlainTextEdit.__init__(self, parent)
21
22         self.prompt = prompt
23         self.history = []
24         self.namespace = {}
25         self.construct = []
26
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)
32
33         self.updateNamespace({'run':self.run_script})
34         self.set_json(False)
35
36     def set_json(self, b):
37         self.is_json = b
38     
39     def run_script(self, filename):
40         with open(filename) as f:
41             script = f.read()
42
43         # eval is generally considered bad practice. use it wisely!
44         result = eval(script, self.namespace, self.namespace)
45
46
47
48     def updateNamespace(self, namespace):
49         self.namespace.update(namespace)
50
51     def showMessage(self, message):
52         self.appendPlainText(message)
53         self.newPrompt()
54
55     def clear(self):
56         self.setPlainText('')
57         self.newPrompt()
58
59     def newPrompt(self):
60         if self.construct:
61             prompt = '.' * len(self.prompt)
62         else:
63             prompt = self.prompt
64
65         self.completions_pos = self.textCursor().position()
66         self.completions_visible = False
67
68         self.appendPlainText(prompt)
69         self.moveCursor(QtGui.QTextCursor.End)
70
71     def getCommand(self):
72         doc = self.document()
73         curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text())
74         curr_line = curr_line.rstrip()
75         curr_line = curr_line[len(self.prompt):]
76         return curr_line
77
78     def setCommand(self, command):
79         if self.getCommand() == command:
80             return
81
82         doc = self.document()
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)
87
88         self.textCursor().removeSelectedText()
89         self.textCursor().insertText(command)
90         self.moveCursor(QtGui.QTextCursor.End)
91
92
93     def show_completions(self, completions):
94         if self.completions_visible:
95             self.hide_completions()
96
97         c = self.textCursor()
98         c.setPosition(self.completions_pos)
99
100         completions = map(lambda x: x.split('.')[-1], completions)
101         t = '\n' + ' '.join(completions)
102         if len(t) > 500:
103             t = t[:500] + '...'
104         c.insertText(t)
105         self.completions_end = c.position()
106
107         self.moveCursor(QtGui.QTextCursor.End)
108         self.completions_visible = True
109         
110
111     def hide_completions(self):
112         if not self.completions_visible:
113             return
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()
118
119         self.moveCursor(QtGui.QTextCursor.End)
120         self.completions_visible = False
121
122
123     def getConstruct(self, command):
124         if self.construct:
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)
129                 self.construct = []
130                 return ret_val
131             else:
132                 return ''
133         else:
134             if command and command[-1] == (':'):
135                 self.construct.append(command)
136                 return ''
137             else:
138                 return command
139
140     def getHistory(self):
141         return self.history
142
143     def setHisory(self, history):
144         self.history = history
145
146     def addToHistory(self, command):
147         if command.find("importprivkey") > -1:
148             return
149         
150         if command and (not self.history or self.history[-1] != command):
151             self.history.append(command)
152         self.history_index = len(self.history)
153
154     def getPrevHistoryEntry(self):
155         if self.history:
156             self.history_index = max(0, self.history_index - 1)
157             return self.history[self.history_index]
158         return ''
159
160     def getNextHistoryEntry(self):
161         if self.history:
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]
166         return ''
167
168     def getCursorPosition(self):
169         c = self.textCursor()
170         return c.position() - c.block().position() - len(self.prompt)
171
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)
176
177     def register_command(self, c, func):
178         methods = { c: func}
179         self.updateNamespace(methods)
180         
181
182     def runCommand(self):
183         command = self.getCommand()
184         self.addToHistory(command)
185
186         command = self.getConstruct(command)
187
188         if command:
189             tmp_stdout = sys.stdout
190
191             class stdoutProxy():
192                 def __init__(self, write_func):
193                     self.write_func = write_func
194                     self.skip = False
195
196                 def flush(self):
197                     pass
198
199                 def write(self, text):
200                     if not self.skip:
201                         stripped_text = text.rstrip('\n')
202                         self.write_func(stripped_text)
203                         QtCore.QCoreApplication.processEvents()
204                     self.skip = not self.skip
205
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))
208                 self.newPrompt()
209                 return
210
211             sys.stdout = stdoutProxy(self.appendPlainText)
212             try:
213                 try:
214                     # eval is generally considered bad practice. use it wisely!
215                     result = eval(command, self.namespace, self.namespace)
216                     if result != None:
217                         if self.is_json:
218                             util.print_json(result)
219                         else:
220                             self.appendPlainText(repr(result))
221                 except SyntaxError:
222                     # exec is generally considered bad practice. use it wisely!
223                     exec command in self.namespace
224             except SystemExit:
225                 self.close()
226             except Exception:
227                 traceback_lines = traceback.format_exc().split('\n')
228                 # Remove traceback mentioning this file, and a linebreak
229                 for i in (3,2,1,-1):
230                     traceback_lines.pop(i)
231                 self.appendPlainText('\n'.join(traceback_lines))
232             sys.stdout = tmp_stdout
233         self.newPrompt()
234         self.set_json(False)
235                     
236
237     def keyPressEvent(self, event):
238         if event.key() == QtCore.Qt.Key_Tab:
239             self.completions()
240             return
241
242         self.hide_completions()
243
244         if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
245             self.runCommand()
246             return
247         if event.key() == QtCore.Qt.Key_Home:
248             self.setCursorPosition(0)
249             return
250         if event.key() == QtCore.Qt.Key_PageUp:
251             return
252         elif event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace):
253             if self.getCursorPosition() == 0:
254                 return
255         elif event.key() == QtCore.Qt.Key_Up:
256             self.setCommand(self.getPrevHistoryEntry())
257             return
258         elif event.key() == QtCore.Qt.Key_Down:
259             self.setCommand(self.getNextHistoryEntry())
260             return
261         elif event.key() == QtCore.Qt.Key_L and event.modifiers() == QtCore.Qt.ControlModifier:
262             self.clear()
263
264         super(Console, self).keyPressEvent(event)
265
266
267
268     def completions(self):
269         cmd = self.getCommand()
270         lastword = re.split(' |\(|\)',cmd)[-1]
271         beginning = cmd[0:-len(lastword)]
272
273         path = lastword.split('.')
274         ns = self.namespace.keys()
275
276         if len(path) == 1:
277             ns = ns
278             prefix = ''
279         else:
280             obj = self.namespace.get(path[0])
281             prefix = path[0] + '.'
282             ns = dir(obj)
283             
284
285         completions = []
286         for x in ns:
287             if x[0] == '_':continue
288             xx = prefix + x
289             if xx.startswith(lastword):
290                 completions.append(xx)
291         completions.sort()
292                 
293         if not completions:
294             self.hide_completions()
295         elif len(completions) == 1:
296             self.hide_completions()
297             self.setCommand(beginning + completions[0])
298         else:
299             # find common prefix
300             p = os.path.commonprefix(completions)
301             if len(p)>len(lastword):
302                 self.hide_completions()
303                 self.setCommand(beginning + p)
304             else:
305                 self.show_completions(completions)
306
307
308 welcome_message = '''
309    ---------------------------------------------------------------
310      Welcome to a primitive Python interpreter.
311    ---------------------------------------------------------------
312 '''
313
314 if __name__ == '__main__':
315     app = QtGui.QApplication(sys.argv)
316     console = Console(startup_message=welcome_message)
317     console.updateNamespace({'myVar1' : app, 'myVar2' : 1234})
318     console.show();
319     sys.exit(app.exec_())