rich_ipython_widget.py
295 lines
| 12.0 KiB
| text/x-python
|
PythonLexer
|
r6636 | #----------------------------------------------------------------------------- | ||
|
r6640 | # Copyright (c) 2010, IPython Development Team. | ||
|
r6636 | # | ||
# Distributed under the terms of the Modified BSD License. | ||||
# | ||||
# The full license is in the file COPYING.txt, distributed with this software. | ||||
#----------------------------------------------------------------------------- | ||||
|
r3304 | # Standard libary imports. | ||
from base64 import decodestring | ||||
|
r3154 | import os | ||
import re | ||||
|
r3304 | |||
# System libary imports. | ||||
from IPython.external.qt import QtCore, QtGui | ||||
|
r2758 | |||
# Local imports | ||||
|
r6638 | from IPython.utils.traitlets import Bool | ||
|
r2765 | from IPython.frontend.qt.svg import save_svg, svg_to_clipboard, svg_to_image | ||
|
r2758 | from ipython_widget import IPythonWidget | ||
class RichIPythonWidget(IPythonWidget): | ||||
""" An IPythonWidget that supports rich text, including lists, images, and | ||||
tables. Note that raw performance will be reduced compared to the plain | ||||
text version. | ||||
""" | ||||
|
r2835 | # RichIPythonWidget protected class variables. | ||
_payload_source_plot = 'IPython.zmq.pylab.backend_payload.add_plot_payload' | ||||
|
r6638 | _jpg_supported = Bool(False) | ||
|
r2758 | #--------------------------------------------------------------------------- | ||
|
r2776 | # 'object' interface | ||
|
r2758 | #--------------------------------------------------------------------------- | ||
|
r2776 | def __init__(self, *args, **kw): | ||
|
r2758 | """ Create a RichIPythonWidget. | ||
""" | ||||
|
r2776 | kw['kind'] = 'rich' | ||
super(RichIPythonWidget, self).__init__(*args, **kw) | ||||
|
r3361 | |||
# Configure the ConsoleWidget HTML exporter for our formats. | ||||
self._html_exporter.image_tag = self._get_image_tag | ||||
|
r3364 | # Dictionary for resolving document resource names to SVG data. | ||
self._name_to_svg_map = {} | ||||
|
r2765 | |||
|
r6636 | # Do we support jpg ? | ||
# it seems that sometime jpg support is a plugin of QT, so try to assume | ||||
# it is not always supported. | ||||
|
r6638 | _supported_format = map(str, QtGui.QImageReader.supportedImageFormats()) | ||
self._jpg_supported = 'jpeg' in _supported_format | ||||
|
r6636 | |||
|
r2765 | #--------------------------------------------------------------------------- | ||
# 'ConsoleWidget' protected interface | ||||
#--------------------------------------------------------------------------- | ||||
|
r2990 | def _context_menu_make(self, pos): | ||
""" Reimplemented to return a custom context menu for images. | ||||
|
r2765 | """ | ||
format = self._control.cursorForPosition(pos).charFormat() | ||||
name = format.stringProperty(QtGui.QTextFormat.ImageName) | ||||
|
r3307 | if name: | ||
|
r2765 | menu = QtGui.QMenu() | ||
menu.addAction('Copy Image', lambda: self._copy_image(name)) | ||||
menu.addAction('Save Image As...', lambda: self._save_image(name)) | ||||
menu.addSeparator() | ||||
|
r3364 | svg = self._name_to_svg_map.get(name, None) | ||
if svg is not None: | ||||
|
r2765 | menu.addSeparator() | ||
menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg)) | ||||
|
r4872 | menu.addAction('Save SVG As...', | ||
|
r2765 | lambda: save_svg(svg, self._control)) | ||
|
r3307 | else: | ||
menu = super(RichIPythonWidget, self)._context_menu_make(pos) | ||||
|
r2990 | return menu | ||
|
r3277 | |||
#--------------------------------------------------------------------------- | ||||
# 'BaseFrontendMixin' abstract interface | ||||
#--------------------------------------------------------------------------- | ||||
|
r6638 | def _pre_image_append(self, msg, prompt_number): | ||
""" Append the Out[] prompt and make the output nicer | ||||
Shared code for some the following if statement | ||||
""" | ||||
self.log.debug("pyout: %s", msg.get('content', '')) | ||||
self._append_plain_text(self.output_sep, True) | ||||
self._append_html(self._make_out_prompt(prompt_number), True) | ||||
self._append_plain_text('\n', True) | ||||
|
r3277 | |||
|
r3278 | def _handle_pyout(self, msg): | ||
""" Overridden to handle rich data types, like SVG. | ||||
""" | ||||
if not self._hidden and self._is_from_this_session(msg): | ||||
content = msg['content'] | ||||
prompt_number = content['execution_count'] | ||||
data = content['data'] | ||||
if data.has_key('image/svg+xml'): | ||||
|
r6638 | self._pre_image_append(msg, prompt_number) | ||
|
r4057 | self._append_svg(data['image/svg+xml'], True) | ||
self._append_html(self.output_sep2, True) | ||||
|
r3279 | elif data.has_key('image/png'): | ||
|
r6638 | self._pre_image_append(msg, prompt_number) | ||
|
r4773 | self._append_png(decodestring(data['image/png'].encode('ascii')), True) | ||
|
r4057 | self._append_html(self.output_sep2, True) | ||
|
r6636 | elif data.has_key('image/jpeg') and self._jpg_supported: | ||
|
r6638 | self._pre_image_append(msg, prompt_number) | ||
|
r6636 | self._append_jpg(decodestring(data['image/jpeg'].encode('ascii')), True) | ||
self._append_html(self.output_sep2, True) | ||||
|
r3278 | else: | ||
# Default back to the plain text representation. | ||||
return super(RichIPythonWidget, self)._handle_pyout(msg) | ||||
|
r3277 | def _handle_display_data(self, msg): | ||
|
r3278 | """ Overridden to handle rich data types, like SVG. | ||
|
r3277 | """ | ||
if not self._hidden and self._is_from_this_session(msg): | ||||
source = msg['content']['source'] | ||||
data = msg['content']['data'] | ||||
metadata = msg['content']['metadata'] | ||||
# Try to use the svg or html representations. | ||||
# FIXME: Is this the right ordering of things to try? | ||||
if data.has_key('image/svg+xml'): | ||||
|
r4793 | self.log.debug("display: %s", msg.get('content', '')) | ||
|
r3277 | svg = data['image/svg+xml'] | ||
|
r4057 | self._append_svg(svg, True) | ||
|
r3279 | elif data.has_key('image/png'): | ||
|
r4793 | self.log.debug("display: %s", msg.get('content', '')) | ||
|
r3279 | # PNG data is base64 encoded as it passes over the network | ||
# in a JSON structure so we decode it. | ||||
|
r4773 | png = decodestring(data['image/png'].encode('ascii')) | ||
|
r4057 | self._append_png(png, True) | ||
|
r6636 | elif data.has_key('image/jpeg') and self._jpg_supported: | ||
self.log.debug("display: %s", msg.get('content', '')) | ||||
jpg = decodestring(data['image/jpeg'].encode('ascii')) | ||||
self._append_jpg(jpg, True) | ||||
|
r3277 | else: | ||
# Default back to the plain text representation. | ||||
return super(RichIPythonWidget, self)._handle_display_data(msg) | ||||
|
r2758 | #--------------------------------------------------------------------------- | ||
|
r2765 | # 'RichIPythonWidget' protected interface | ||
#--------------------------------------------------------------------------- | ||||
|
r6636 | def _append_jpg(self, jpg, before_prompt=False): | ||
""" Append raw JPG data to the widget.""" | ||||
self._append_custom(self._insert_jpg, jpg, before_prompt) | ||||
|
r4057 | def _append_png(self, png, before_prompt=False): | ||
""" Append raw PNG data to the widget. | ||||
|
r3277 | """ | ||
|
r4057 | self._append_custom(self._insert_png, png, before_prompt) | ||
|
r3279 | |||
|
r4057 | def _append_svg(self, svg, before_prompt=False): | ||
""" Append raw SVG data to the widget. | ||||
|
r3279 | """ | ||
|
r4057 | self._append_custom(self._insert_svg, svg, before_prompt) | ||
|
r3277 | |||
|
r2765 | def _add_image(self, image): | ||
""" Adds the specified QImage to the document and returns a | ||||
QTextImageFormat that references it. | ||||
""" | ||||
document = self._control.document() | ||||
|
r3304 | name = str(image.cacheKey()) | ||
|
r2765 | document.addResource(QtGui.QTextDocument.ImageResource, | ||
QtCore.QUrl(name), image) | ||||
format = QtGui.QTextImageFormat() | ||||
format.setName(name) | ||||
return format | ||||
def _copy_image(self, name): | ||||
""" Copies the ImageResource with 'name' to the clipboard. | ||||
""" | ||||
image = self._get_image(name) | ||||
QtGui.QApplication.clipboard().setImage(image) | ||||
def _get_image(self, name): | ||||
""" Returns the QImage stored as the ImageResource with 'name'. | ||||
""" | ||||
document = self._control.document() | ||||
|
r3364 | image = document.resource(QtGui.QTextDocument.ImageResource, | ||
QtCore.QUrl(name)) | ||||
return image | ||||
|
r2765 | |||
|
r3361 | def _get_image_tag(self, match, path = None, format = "png"): | ||
|
r3132 | """ Return (X)HTML mark-up for the image-tag given by match. | ||
Parameters | ||||
---------- | ||||
|
r3361 | match : re.SRE_Match | ||
|
r3132 | A match to an HTML image tag as exported by Qt, with | ||
match.group("Name") containing the matched image ID. | ||||
path : string|None, optional [default None] | ||||
|
r3361 | If not None, specifies a path to which supporting files may be | ||
written (e.g., for linked images). If None, all images are to be | ||||
included inline. | ||||
|
r3132 | |||
|
r6636 | format : "png"|"svg"|"jpg", optional [default "png"] | ||
|
r3132 | Format for returned or referenced images. | ||
""" | ||||
|
r6636 | if format in ("png","jpg"): | ||
|
r3125 | try: | ||
image = self._get_image(match.group("name")) | ||||
except KeyError: | ||||
return "<b>Couldn't find image %s</b>" % match.group("name") | ||||
|
r3361 | if path is not None: | ||
|
r3154 | if not os.path.exists(path): | ||
os.mkdir(path) | ||||
relpath = os.path.basename(path) | ||||
|
r6637 | if image.save("%s/qt_img%s.%s" % (path, match.group("name"), format), | ||
|
r3361 | "PNG"): | ||
|
r6636 | return '<img src="%s/qt_img%s.%s">' % (relpath, | ||
match.group("name"),format) | ||||
|
r3125 | else: | ||
return "<b>Couldn't save image!</b>" | ||||
else: | ||||
ba = QtCore.QByteArray() | ||||
buffer_ = QtCore.QBuffer(ba) | ||||
buffer_.open(QtCore.QIODevice.WriteOnly) | ||||
|
r6636 | image.save(buffer_, format.upper()) | ||
|
r3125 | buffer_.close() | ||
|
r6636 | return '<img src="data:image/%s;base64,\n%s\n" />' % ( | ||
format,re.sub(r'(.{60})',r'\1\n',str(ba.toBase64()))) | ||||
|
r3125 | |||
|
r3361 | elif format == "svg": | ||
|
r3125 | try: | ||
|
r3364 | svg = str(self._name_to_svg_map[match.group("name")]) | ||
|
r3125 | except KeyError: | ||
return "<b>Couldn't find image %s</b>" % match.group("name") | ||||
# Not currently checking path, because it's tricky to find a | ||||
# cross-browser way to embed external SVG images (e.g., via | ||||
# object or embed tags). | ||||
# Chop stand-alone header from matplotlib SVG | ||||
offset = svg.find("<svg") | ||||
assert(offset > -1) | ||||
|
r4872 | |||
|
r3125 | return svg[offset:] | ||
else: | ||||
return '<b>Unrecognized image format</b>' | ||||
|
r3277 | |||
|
r6636 | def _insert_jpg(self, cursor, jpg): | ||
""" Insert raw PNG data into the widget.""" | ||||
self._insert_img(cursor, jpg, 'jpg') | ||||
|
r4057 | def _insert_png(self, cursor, png): | ||
""" Insert raw PNG data into the widget. | ||||
""" | ||||
|
r6636 | self._insert_img(cursor, png, 'png') | ||
def _insert_img(self, cursor, img, fmt): | ||||
""" insert a raw image, jpg or png """ | ||||
|
r4057 | try: | ||
image = QtGui.QImage() | ||||
|
r6636 | image.loadFromData(img, fmt.upper()) | ||
|
r4057 | except ValueError: | ||
|
r6636 | self._insert_plain_text(cursor, 'Received invalid %s data.'%fmt) | ||
|
r4057 | else: | ||
format = self._add_image(image) | ||||
cursor.insertBlock() | ||||
cursor.insertImage(format) | ||||
cursor.insertBlock() | ||||
def _insert_svg(self, cursor, svg): | ||||
""" Insert raw SVG data into the widet. | ||||
""" | ||||
try: | ||||
image = svg_to_image(svg) | ||||
except ValueError: | ||||
self._insert_plain_text(cursor, 'Received invalid SVG data.') | ||||
else: | ||||
format = self._add_image(image) | ||||
self._name_to_svg_map[format.name()] = svg | ||||
cursor.insertBlock() | ||||
cursor.insertImage(format) | ||||
cursor.insertBlock() | ||||
|
r3361 | def _save_image(self, name, format='PNG'): | ||
""" Shows a save dialog for the ImageResource with 'name'. | ||||
""" | ||||
dialog = QtGui.QFileDialog(self._control, 'Save Image') | ||||
dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) | ||||
dialog.setDefaultSuffix(format.lower()) | ||||
dialog.setNameFilter('%s file (*.%s)' % (format, format.lower())) | ||||
if dialog.exec_(): | ||||
filename = dialog.selectedFiles()[0] | ||||
image = self._get_image(name) | ||||
image.save(filename, format) | ||||