/
magic_helper.py
211 lines (175 loc) · 7.42 KB
/
magic_helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
"""MagicHelper - dockable widget showing magic commands for the MainWindow
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# stdlib imports
import json
import re
import sys
# System library imports
from IPython.external.qt import QtGui,QtCore
from IPython.core.magic import magic_escapes
class MagicHelper(QtGui.QDockWidget):
"""MagicHelper - dockable widget for convenient search and running of
magic command for IPython QtConsole.
"""
#---------------------------------------------------------------------------
# signals
#---------------------------------------------------------------------------
pasteRequested = QtCore.Signal(str, name = 'pasteRequested')
"""This signal is emitted when user wants to paste selected magic
command into the command line.
"""
runRequested = QtCore.Signal(str, name = 'runRequested')
"""This signal is emitted when user wants to execute selected magic command
"""
readyForUpdate = QtCore.Signal(name = 'readyForUpdate')
"""This signal is emitted when MagicHelper is ready to be populated.
Since kernel querying mechanisms are out of scope of this class,
it expects its owner to invoke MagicHelper.populate_magic_helper()
as a reaction on this event.
"""
#---------------------------------------------------------------------------
# constructor
#---------------------------------------------------------------------------
def __init__(self, name, parent):
super(MagicHelper, self).__init__(name, parent)
self.data = None
class MinListWidget(QtGui.QListWidget):
"""Temp class to overide the default QListWidget size hint
in order to make MagicHelper narrow
"""
def sizeHint(self):
s = QtCore.QSize()
s.setHeight(super(MinListWidget,self).sizeHint().height())
s.setWidth(self.sizeHintForColumn(0))
return s
# construct content
self.frame = QtGui.QFrame()
self.search_label = QtGui.QLabel("Search:")
self.search_line = QtGui.QLineEdit()
self.search_class = QtGui.QComboBox()
self.search_list = MinListWidget()
self.paste_button = QtGui.QPushButton("Paste")
self.run_button = QtGui.QPushButton("Run")
# layout all the widgets
main_layout = QtGui.QVBoxLayout()
search_layout = QtGui.QHBoxLayout()
search_layout.addWidget(self.search_label)
search_layout.addWidget(self.search_line, 10)
main_layout.addLayout(search_layout)
main_layout.addWidget(self.search_class)
main_layout.addWidget(self.search_list, 10)
action_layout = QtGui.QHBoxLayout()
action_layout.addWidget(self.paste_button)
action_layout.addWidget(self.run_button)
main_layout.addLayout(action_layout)
self.frame.setLayout(main_layout)
self.setWidget(self.frame)
# connect all the relevant signals to handlers
self.visibilityChanged[bool].connect( self._update_magic_helper )
self.search_class.activated[int].connect(
self.class_selected
)
self.search_line.textChanged[str].connect(
self.search_changed
)
self.search_list.itemDoubleClicked.connect(
self.paste_requested
)
self.paste_button.clicked[bool].connect(
self.paste_requested
)
self.run_button.clicked[bool].connect(
self.run_requested
)
#---------------------------------------------------------------------------
# implementation
#---------------------------------------------------------------------------
def _update_magic_helper(self, visible):
"""Start update sequence.
This method is called when MagicHelper becomes visible. It clears
the content and emits readyForUpdate signal. The owner of the
instance is expected to invoke populate_magic_helper() when magic
info is available.
"""
if not visible or self.data is not None:
return
self.data = {}
self.search_class.clear()
self.search_class.addItem("Populating...")
self.search_list.clear()
self.readyForUpdate.emit()
def populate_magic_helper(self, data):
"""Expects data returned by lsmagics query from kernel.
Populates the search_class and search_list with relevant items.
"""
self.search_class.clear()
self.search_list.clear()
self.data = data['data'].get('application/json', {})
self.search_class.addItem('All Magics', 'any')
classes = set()
for mtype in sorted(self.data):
subdict = self.data[mtype]
for name in sorted(subdict):
classes.add(subdict[name])
for cls in sorted(classes):
label = re.sub("([a-zA-Z]+)([A-Z][a-z])","\g<1> \g<2>", cls)
self.search_class.addItem(label, cls)
self.filter_magic_helper('.', 'any')
def class_selected(self, index):
"""Handle search_class selection changes
"""
item = self.search_class.itemData(index)
regex = self.search_line.text()
self.filter_magic_helper(regex = regex, cls = item)
def search_changed(self, search_string):
"""Handle search_line text changes.
The text is interpreted as a regular expression
"""
item = self.search_class.itemData(
self.search_class.currentIndex()
)
self.filter_magic_helper(regex = search_string, cls = item)
def _get_current_search_item(self, item = None):
"""Retrieve magic command currently selected in the search_list
"""
text = None
if not isinstance(item, QtGui.QListWidgetItem):
item = self.search_list.currentItem()
text = item.text()
return text
def paste_requested(self, item = None):
"""Emit pasteRequested signal with currently selected item text
"""
text = self._get_current_search_item(item)
if text is not None:
self.pasteRequested.emit(text)
def run_requested(self, item = None):
"""Emit runRequested signal with currently selected item text
"""
text = self._get_current_search_item(item)
if text is not None:
self.runRequested.emit(text)
def filter_magic_helper(self, regex, cls):
"""Update search_list with magic commands whose text match
regex and class match cls.
If cls equals 'any' - any class matches.
"""
if regex == "" or regex is None:
regex = '.'
if cls is None:
cls = 'any'
self.search_list.clear()
for mtype in sorted(self.data):
subdict = self.data[mtype]
prefix = magic_escapes[mtype]
for name in sorted(subdict):
mclass = subdict[name]
pmagic = prefix + name
if (re.match(regex, name) or re.match(regex, pmagic)) and \
(cls == 'any' or cls == mclass):
self.search_list.addItem(pmagic)