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