Source code for matplotlib.backends.backend_svg

import base64
import codecs
import datetime
import gzip
import hashlib
from io import BytesIO
import itertools
import logging
import os
import re
import uuid

import numpy as np
from PIL import Image

import matplotlib as mpl
from matplotlib import cbook, font_manager as fm
from matplotlib.backend_bases import (
     _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
from matplotlib.backends.backend_mixed import MixedModeRenderer
from matplotlib.colors import rgb2hex
from matplotlib.dates import UTC
from matplotlib.path import Path
from matplotlib import _path
from matplotlib.transforms import Affine2D, Affine2DBase


_log = logging.getLogger(__name__)


# ----------------------------------------------------------------------
# SimpleXMLWriter class
#
# Based on an original by Fredrik Lundh, but modified here to:
#   1. Support modern Python idioms
#   2. Remove encoding support (it's handled by the file writer instead)
#   3. Support proper indentation
#   4. Minify things a little bit

# --------------------------------------------------------------------
# The SimpleXMLWriter module is
#
# Copyright (c) 2001-2004 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS.  IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------


def _escape_cdata(s):
    s = s.replace("&", "&")
    s = s.replace("<", "&lt;")
    s = s.replace(">", "&gt;")
    return s


_escape_xml_comment = re.compile(r'-(?=-)')


def _escape_comment(s):
    s = _escape_cdata(s)
    return _escape_xml_comment.sub('- ', s)


def _escape_attrib(s):
    s = s.replace("&", "&amp;")
    s = s.replace("'", "&apos;")
    s = s.replace('"', "&quot;")
    s = s.replace("<", "&lt;")
    s = s.replace(">", "&gt;")
    return s


def _quote_escape_attrib(s):
    return ('"' + _escape_cdata(s) + '"' if '"' not in s else
            "'" + _escape_cdata(s) + "'" if "'" not in s else
            '"' + _escape_attrib(s) + '"')


def _short_float_fmt(x):
    """
    Create a short string representation of a float, which is %f
    formatting with trailing zeros and the decimal point removed.
    """
    return f'{x:f}'.rstrip('0').rstrip('.')


[docs] class XMLWriter: """ Parameters ---------- file : writable text file-like object """ def __init__(self, file): self.__write = file.write if hasattr(file, "flush"): self.flush = file.flush self.__open = 0 # true if start tag is open self.__tags = [] self.__data = [] self.__indentation = " " * 64 def __flush(self, indent=True): # flush internal buffers if self.__open: if indent: self.__write(">\n") else: self.__write(">") self.__open = 0 if self.__data: data = ''.join(self.__data) self.__write(_escape_cdata(data)) self.__data = []
[docs] def start(self, tag, attrib={}, **extra): """ Open a new element. Attributes can be given as keyword arguments, or as a string/string dictionary. The method returns an opaque identifier that can be passed to the :meth:`close` method, to close all open elements up to and including this one. Parameters ---------- tag Element tag. attrib Attribute dictionary. Alternatively, attributes can be given as keyword arguments. Returns ------- An element identifier. """ self.__flush() tag = _escape_cdata(tag) self.__data = [] self.__tags.append(tag) self.__write(self.__indentation[:len(self.__tags) - 1]) self.__write(f"<{tag}") for k, v in {**attrib, **extra}.items(): if v: k = _escape_cdata(k) v = _quote_escape_attrib(v) self.__write(f' {k}={v}') self.__open = 1 return len(self.__tags) - 1
[docs] def comment(self, comment): """ Add a comment to the output stream. Parameters ---------- comment : str Comment text. """ self.__flush() self.__write(self.__indentation[:len(self.__tags)]) self.__write(f"<!-- {_escape_comment(comment)} -->\n")
[docs] def data(self, text): """ Add character data to the output stream. Parameters ---------- text : str Character data. """ self.__data.append(text)
[docs] def end(self, tag=None, indent=True): """ Close the current element (opened by the most recent call to :meth:`start`). Parameters ---------- tag Element tag. If given, the tag must match the start tag. If omitted, the current element is closed. indent : bool, default: True """ if tag: assert self.__tags, f"unbalanced end({tag})" assert _escape_cdata(tag) == self.__tags[-1], \ f"expected end({self.__tags[-1]}), got {tag}" else: assert self.__tags, "unbalanced end()" tag = self.__tags.pop() if self.__data: self.__flush(indent) elif self.__open: self.__open = 0 self.__write("/>\n") return if indent: self.__write(self.__indentation[:len(self.__tags)]) self.__write(f"</{tag}>\n")
[docs] def close(self, id): """ Close open elements, up to (and including) the element identified by the given identifier. Parameters ---------- id Element identifier, as returned by the :meth:`start` method. """ while len(self.__tags) > id: self.end()
[docs] def element(self, tag, text=None, attrib={}, **extra): """ Add an entire element. This is the same as calling :meth:`start`, :meth:`data`, and :meth:`end` in sequence. The *text* argument can be omitted. """ self.start(tag, attrib, **extra) if text: self.data(text) self.end(indent=False)
[docs] def flush(self): """Flush the output stream.""" pass # replaced by the constructor
def _generate_transform(transform_list): parts = [] for type, value in transform_list: if (type == 'scale' and (value == (1,) or value == (1, 1)) or type == 'translate' and value == (0, 0) or type == 'rotate' and value == (0,)): continue if type == 'matrix' and isinstance(value, Affine2DBase): value = value.to_values() parts.append('{}({})'.format( type, ' '.join(_short_float_fmt(x) for x in value))) return ' '.join(parts) def _generate_css(attrib): return "; ".join(f"{k}: {v}" for k, v in attrib.items()) _capstyle_d = {'projecting': 'square', 'butt': 'butt', 'round': 'round'} def _check_is_str(info, key): if not isinstance(info, str): raise TypeError(f'Invalid type for {key} metadata. Expected str, not ' f'{type(info)}.') def _check_is_iterable_of_str(infos, key): if np.iterable(infos): for info in infos: if not isinstance(info, str): raise TypeError(f'Invalid type for {key} metadata. Expected ' f'iterable of str, not {type(info)}.') else: raise TypeError(f'Invalid type for {key} metadata. Expected str or ' f'iterable of str, not {type(infos)}.')
[docs] class RendererSVG(RendererBase): def __init__(self, width, height, svgwriter, basename=None, image_dpi=72, *, metadata=None): self.width = width self.height = height self.writer = XMLWriter(svgwriter) self.image_dpi = image_dpi # actual dpi at which we rasterize stuff if basename is None: basename = getattr(svgwriter, "name", "") if not isinstance(basename, str): basename = "" self.basename = basename self._groupd = {} self._image_counter = itertools.count() self._clip_path_ids = {} self._clipd = {} self._markers = {} self._path_collection_id = 0 self._hatchd = {} self._has_gouraud = False self._n_gradients = 0 super().__init__() self._glyph_map = dict() str_height = _short_float_fmt(height) str_width = _short_float_fmt(width) svgwriter.write(svgProlog) self._start_id = self.writer.start( 'svg', width=f'{str_width}pt', height=f'{str_height}pt', viewBox=f'0 0 {str_width} {str_height}', xmlns="http://www.w3.org/2000/svg", version="1.1", id=mpl.rcParams['svg.id'], attrib={'xmlns:xlink': "http://www.w3.org/1999/xlink"}) self._write_metadata(metadata) self._write_default_style() def _get_clippath_id(self, clippath): """ Returns a stable and unique identifier for the *clippath* argument object within the current rendering context. This allows plots that include custom clip paths to produce identical SVG output on each render, provided that the :rc:`svg.hashsalt` config setting and the ``SOURCE_DATE_EPOCH`` build-time environment variable are set to fixed values. """ if clippath not in self._clip_path_ids: self._clip_path_ids[clippath] = len(self._clip_path_ids) return self._clip_path_ids[clippath]
[docs] def finalize(self): self._write_clips() self._write_hatches() self.writer.close(self._start_id) self.writer.flush()
def _write_metadata(self, metadata): # Add metadata following the Dublin Core Metadata Initiative, and the # Creative Commons Rights Expression Language. This is mainly for # compatibility with Inkscape. if metadata is None: metadata = {} metadata = { 'Format': 'image/svg+xml', 'Type': 'http://purl.org/dc/dcmitype/StillImage', 'Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org/', **metadata } writer = self.writer if 'Title' in metadata: title = metadata['Title'] _check_is_str(title, 'Title') writer.element('title', text=title) # Special handling. date = metadata.get('Date', None) if date is not None: if isinstance(date, str): dates = [date] elif isinstance(date, (datetime.datetime, datetime.date)): dates = [date.isoformat()] elif np.iterable(date): dates = [] for d in date: if isinstance(d, str): dates.append(d) elif isinstance(d, (datetime.datetime, datetime.date)): dates.append(d.isoformat()) else: raise TypeError( f'Invalid type for Date metadata. ' f'Expected iterable of str, date, or datetime, ' f'not {type(d)}.') else: raise TypeError(f'Invalid type for Date metadata. ' f'Expected str, date, datetime, or iterable ' f'of the same, not {type(date)}.') metadata['Date'] = '/'.join(dates) elif 'Date' not in metadata: # Do not add `Date` if the user explicitly set `Date` to `None` # Get source date from SOURCE_DATE_EPOCH, if set. # See https://reproducible-builds.org/specs/source-date-epoch/ date = os.getenv("SOURCE_DATE_EPOCH") if date: date = datetime.datetime.fromtimestamp(int(date), datetime.timezone.utc) metadata['Date'] = date.replace(tzinfo=UTC).isoformat() else: metadata['Date'] = datetime.datetime.today().isoformat() mid = None def ensure_metadata(mid): if mid is not None: return mid mid = writer.start('metadata') writer.start('rdf:RDF', attrib={ 'xmlns:dc': "http://purl.org/dc/elements/1.1/", 'xmlns:cc': "http://creativecommons.org/ns#", 'xmlns:rdf': "http://www.w3.org/1999/02/22-rdf-syntax-ns#", }) writer.start('cc:Work') return mid uri = metadata.pop('Type', None) if uri is not None: mid = ensure_metadata(mid) writer.element('dc:type', attrib={'rdf:resource': uri}) # Single value only. for key in ['Title', 'Coverage', 'Date', 'Description', 'Format', 'Identifier', 'Language', 'Relation', 'Source']: info = metadata.pop(key, None) if info is not None: mid = ensure_metadata(mid) _check_is_str(info, key) writer.element(f'dc:{key.lower()}', text=info) # Multiple Agent values. for key in ['Creator', 'Contributor', 'Publisher', 'Rights']: agents = metadata.pop(key, None) if agents is None: continue if isinstance(agents, str): agents = [agents] _check_is_iterable_of_str(agents, key) # Now we know that we have an iterable of str mid = ensure_metadata(mid) writer.start(f'dc:{key.lower()}') for agent in agents: writer.start('cc:Agent') writer.element('dc:title', text=agent) writer.end('cc:Agent') writer.end(f'dc:{key.lower()}') # Multiple values. keywords = metadata.pop('Keywords', None) if keywords is not None: if isinstance(keywords, str): keywords = [keywords] _check_is_iterable_of_str(keywords, 'Keywords') # Now we know that we have an iterable of str mid = ensure_metadata(mid) writer.start('dc:subject') writer.start('rdf:Bag') for keyword in keywords: writer.element('rdf:li', text=keyword) writer.end('rdf:Bag') writer.end('dc:subject') if mid is not None: writer.close(mid) if metadata: raise ValueError('Unknown metadata key(s) passed to SVG writer: ' + ','.join(metadata)) def _write_default_style(self): writer = self.writer default_style = _generate_css({ 'stroke-linejoin': 'round', 'stroke-linecap': 'butt'}) writer.start('defs') writer.element('style', type='text/css', text='*{%s}' % default_style) writer.end('defs') def _make_id(self, type, content): salt = mpl.rcParams['svg.hashsalt'] if salt is None: salt = str(uuid.uuid4()) m = hashlib.sha256() m.update(salt.encode('utf8')) m.update(str(content).encode('utf8')) return f'{type}{m.hexdigest()[:10]}' def _make_flip_transform(self, transform): return transform + Affine2D().scale(1, -1).translate(0, self.height) def _get_hatch(self, gc, rgbFace): """ Create a new hatch pattern """ if rgbFace is not None: rgbFace = tuple(rgbFace) edge = gc.get_hatch_color() if edge is not None: edge = tuple(edge) dictkey = (gc.get_hatch(), rgbFace, edge) oid = self._hatchd.get(dictkey) if oid is None: oid = self._make_id('h', dictkey) self._hatchd[dictkey] = ((gc.get_hatch_path(), rgbFace, edge), oid) else: _, oid = oid return oid def _write_hatches(self): if not len(self._hatchd): return HATCH_SIZE = 72 writer = self.writer writer.start('defs') for (path, face, stroke), oid in self._hatchd.values(): writer.start( 'pattern', id=oid, patternUnits="userSpaceOnUse", x="0", y="0", width=str(HATCH_SIZE), height=str(HATCH_SIZE)) path_data = self._convert_path( path, Affine2D() .scale(HATCH_SIZE).scale(1.0, -1.0).translate(0, HATCH_SIZE), simplify=False) if face is None: fill = 'none' else: fill = rgb2hex(face) writer.element( 'rect', x="0", y="0", width=str(HATCH_SIZE+1), height=str(HATCH_SIZE+1), fill=fill) hatch_style = { 'fill': rgb2hex(stroke), 'stroke': rgb2hex(stroke), 'stroke-width': str(mpl.rcParams['hatch.linewidth']), 'stroke-linecap': 'butt', 'stroke-linejoin': 'miter' } if stroke[3] < 1: hatch_style['stroke-opacity'] = str(stroke[3]) writer.element( 'path', d=path_data, style=_generate_css(hatch_style) ) writer.end('pattern') writer.end('defs') def _get_style_dict(self, gc, rgbFace): """Generate a style string from the GraphicsContext and rgbFace.""" attrib = {} forced_alpha = gc.get_forced_alpha() if gc.get_hatch() is not None: attrib['fill'] = f"url(#{self._get_hatch(gc, rgbFace)})" if (rgbFace is not None and len(rgbFace) == 4 and rgbFace[3] != 1.0 and not forced_alpha): attrib['fill-opacity'] = _short_float_fmt(rgbFace[3]) else: if rgbFace is None: attrib['fill'] = 'none' else: if tuple(rgbFace[:3]) != (0, 0, 0): attrib['fill'] = rgb2hex(rgbFace) if (len(rgbFace) == 4 and rgbFace[3] != 1.0 and not forced_alpha): attrib['fill-opacity'] = _short_float_fmt(rgbFace[3]) if forced_alpha and gc.get_alpha() != 1.0: attrib['opacity'] = _short_float_fmt(gc.get_alpha()) offset, seq = gc.get_dashes() if seq is not None: attrib['stroke-dasharray'] = ','.join( _short_float_fmt(val) for val in seq) attrib['stroke-dashoffset'] = _short_float_fmt(float(offset)) linewidth = gc.get_linewidth() if linewidth: rgb = gc.get_rgb() attrib['stroke'] = rgb2hex(rgb) if not forced_alpha and rgb[3] != 1.0: attrib['stroke-opacity'] = _short_float_fmt(rgb[3]) if linewidth != 1.0: attrib['stroke-width'] = _short_float_fmt(linewidth) if gc.get_joinstyle() != 'round': attrib['stroke-linejoin'] = gc.get_joinstyle() if gc.get_capstyle() != 'butt': attrib['stroke-linecap'] = _capstyle_d[gc.get_capstyle()] return attrib def _get_style(self, gc, rgbFace): return _generate_css(self._get_style_dict(gc, rgbFace)) def _get_clip_attrs(self, gc): cliprect = gc.get_clip_rectangle() clippath, clippath_trans = gc.get_clip_path() if clippath is not None: clippath_trans = self._make_flip_transform(clippath_trans) dictkey = (self._get_clippath_id(clippath), str(clippath_trans)) elif cliprect is not None: x, y, w, h = cliprect.bounds y = self.height-(y+h) dictkey = (x, y, w, h) else: return {} clip = self._clipd.get(dictkey) if clip is None: oid = self._make_id('p', dictkey) if clippath is not None: self._clipd[dictkey] = ((clippath, clippath_trans), oid) else: self._clipd[dictkey] = (dictkey, oid) else: _, oid = clip return {'clip-path': f'url(#{oid})'} def _write_clips(self): if not len(self._clipd): return writer = self.writer writer.start('defs') for clip, oid in self._clipd.values(): writer.start('clipPath', id=oid) if len(clip) == 2: clippath, clippath_trans = clip path_data = self._convert_path( clippath, clippath_trans, simplify=False) writer.element('path', d=path_data) else: x, y, w, h = clip writer.element( 'rect', x=_short_float_fmt(x), y=_short_float_fmt(y), width=_short_float_fmt(w), height=_short_float_fmt(h)) writer.end('clipPath') writer.end('defs')
[docs] def open_group(self, s, gid=None): # docstring inherited if gid: self.writer.start('g', id=gid) else: self._groupd[s] = self._groupd.get(s, 0) +