Files
open-webui/static/pyodide/matplotlib_pyodide-0.2.1-py3-none-any.whl

1912 lines
75 KiB
Plaintext
Raw Normal View History

2024-05-16 22:54:37 -10:00
PK2RnX6<>L<EFBFBD><00>matplotlib_pyodide/__init__.pyfrom importlib.metadata import PackageNotFoundError, version
try:
__version__ = version("matplotlib_pyodide")
except PackageNotFoundError:
# package is not installed
pass
PK2RnX<6E><58>}<7D>@<00>@%matplotlib_pyodide/browser_backend.pyimport math
from js import document
from matplotlib.backend_bases import FigureCanvasBase, NavigationToolbar2, TimerBase
from pyodide.ffi.wrappers import (
add_event_listener,
clear_interval,
clear_timeout,
set_interval,
set_timeout,
)
try:
from js import devicePixelRatio as DEVICE_PIXEL_RATIO
except ImportError:
DEVICE_PIXEL_RATIO = 1
class FigureCanvasWasm(FigureCanvasBase):
supports_blit = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._idle_scheduled = False
self._id = "matplotlib_" + hex(id(self))[2:]
self._title = ""
self._ratio = 1
matplotlib_figure_styles = self._add_matplotlib_styles()
if document.getElementById("matplotlib-figure-styles") is None:
document.head.appendChild(matplotlib_figure_styles)
def _add_matplotlib_styles(self):
toolbar_buttons_css_content = """
button.matplotlib-toolbar-button {
font-size: 14px;
color: #495057;
text-transform: uppercase;
background: #e9ecef;
padding: 9px 18px;
border: 1px solid #fff;
border-radius: 4px;
transition-duration: 0.4s;
}
button.matplotlib-toolbar-button#text {
font-family: -apple-system, BlinkMacSystemFont,
"Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell,
"Fira Sans", "Droid Sans", "Helvetica Neue", Arial,
sans-serif, "Apple Color Emoji", "Segoe UI Emoji",
"Segoe UI Symbol";
}
button.matplotlib-toolbar-button:hover {
color: #fff;
background: #495057;
}
"""
toolbar_buttons_style_element = document.createElement("style")
toolbar_buttons_style_element.id = "matplotlib-figure-styles"
toolbar_buttons_css = document.createTextNode(toolbar_buttons_css_content)
toolbar_buttons_style_element.appendChild(toolbar_buttons_css)
return toolbar_buttons_style_element
def get_element(self, name):
"""
Looks up an HTMLElement created for this figure.
"""
# TODO: Should we store a reference here instead of always looking it
# up? I'm a little concerned about weird Python/JS
# cross-memory-management issues...
return document.getElementById(self._id + name)
def get_dpi_ratio(self, context):
"""
Gets the ratio of physical pixels to logical pixels for the given HTML
Canvas context.
This is typically 2 on a HiDPI ("Retina") display, and 1 otherwise.
"""
backing_store = (
getattr(context, "backingStorePixelRatio", 0)
or getattr(context, "webkitBackingStorePixel", 0)
or getattr(context, "mozBackingStorePixelRatio", 0)
or getattr(context, "msBackingStorePixelRatio", 0)
or getattr(context, "oBackingStorePixelRatio", 0)
or getattr(context, "backendStorePixelRatio", 0)
or 1
)
return DEVICE_PIXEL_RATIO / backing_store
def show(self, *args, **kwargs):
# If we've already shown this canvas elsewhere, don't create a new one,
# just reuse it and scroll to the existing one.
existing = self.get_element("")
if existing is not None:
self.draw_idle()
existing.scrollIntoView()
return
# Disable the right-click context menu.
# Doesn't work in all browsers.
def ignore(event):
event.preventDefault()
return False
# Create the main canvas and determine the physical to logical pixel
# ratio
canvas = document.createElement("canvas")
context = canvas.getContext("2d")
self._ratio = self.get_dpi_ratio(context)
width, height = self.get_width_height()
width *= self._ratio
height *= self._ratio
div = self._create_root_element()
add_event_listener(div, "contextmenu", ignore)
div.setAttribute(
"style",
"margin: 0 auto; text-align: center;" + f"width: {width / self._ratio}px",
)
div.id = self._id
# The top bar
top = document.createElement("div")
top.id = self._id + "top"
top.setAttribute("style", "font-weight: bold; text-align: center")
top.textContent = self._title
div.appendChild(top)
# A div containing two canvases stacked on top of one another:
# - The bottom for rendering matplotlib content
# - The top for rendering interactive elements, such as the zoom
# rubberband
canvas_div = document.createElement("div")
canvas_div.setAttribute("style", "position: relative")
canvas.id = self._id + "canvas"
canvas.setAttribute("width", width)
canvas.setAttribute("height", height)
canvas.setAttribute(
"style",
"left: 0; top: 0; z-index: 0; outline: 0;"
+ "width: {}px; height: {}px".format(
width / self._ratio, height / self._ratio
),
)
canvas_div.appendChild(canvas)
rubberband = document.createElement("canvas")
rubberband.id = self._id + "rubberband"
rubberband.setAttribute("width", width)
rubberband.setAttribute("height", height)
rubberband.setAttribute(
"style",
"position: absolute; left: 0; top: 0; z-index: 0; "
+ "outline: 0; width: {}px; height: {}px".format(
width / self._ratio, height / self._ratio
),
)
# Canvas must have a "tabindex" attr in order to receive keyboard
# events
rubberband.setAttribute("tabindex", "0")
# Event handlers are added to the canvas "on top", even though most of
# the activity happens in the canvas below.
add_event_listener(rubberband, "mousemove", self.onmousemove)
add_event_listener(rubberband, "mouseup", self.onmouseup)
add_event_listener(rubberband, "mousedown", self.onmousedown)
add_event_listener(rubberband, "mouseenter", self.onmouseenter)
add_event_listener(rubberband, "mouseleave", self.onmouseleave)
add_event_listener(rubberband, "keyup", self.onkeyup)
add_event_listener(rubberband, "keydown", self.onkeydown)
context = rubberband.getContext("2d")
context.strokeStyle = "#000000"
context.setLineDash([2, 2])
canvas_div.appendChild(rubberband)
div.appendChild(canvas_div)
# The bottom bar, with toolbar and message display
bottom = document.createElement("div")
toolbar = self.toolbar.get_element()
bottom.appendChild(toolbar)
message = document.createElement("div")
message.id = self._id + "message"
message.setAttribute("style", "min-height: 1.5em")
bottom.appendChild(message)
div.appendChild(bottom)
self.draw()
def draw(self):
pass
def draw_idle(self):
if not self._idle_scheduled:
self._idle_scheduled = True
set_timeout(self.draw, 1)
def set_message(self, message):
message_display = self.get_element("message")
if message_display is not None:
message_display.textContent = message
def _convert_mouse_event(self, event):
width, height = self.get_width_height()
x = event.offsetX
y = height - event.offsetY
button = event.button + 1
# Disable the right-click context menu in some browsers
if button == 3:
event.preventDefault()
event.stopPropagation()
if button == 2:
button = 3
return x, y, button
def onmousemove(self, event):
x, y, button = self._convert_mouse_event(event)
self.motion_notify_event(x, y, guiEvent=event)
def onmouseup(self, event):
x, y, button = self._convert_mouse_event(event)
self.button_release_event(x, y, button, guiEvent=event)
def onmousedown(self, event):
x, y, button = self._convert_mouse_event(event)
self.button_press_event(x, y, button, guiEvent=event)
def onmouseenter(self, event):
# When the mouse is over the figure, get keyboard focus
self.get_element("rubberband").focus()
self.enter_notify_event(guiEvent=event)
def onmouseleave(self, event):
# When the mouse leaves the figure, drop keyboard focus
self.get_element("rubberband").blur()
self.leave_notify_event(guiEvent=event)
def onscroll(self, event):
x, y, button = self._convert_mouse_event(event)
self.scroll_event(x, y, event.deltaX, guiEvent=event)
_cursor_map = {0: "pointer", 1: "default", 2: "crosshair", 3: "move"}
def set_cursor(self, cursor):
rubberband = self.get_element("rubberband")
if rubberband is not None:
rubberband.style.cursor = self._cursor_map.get(cursor, 0)
# http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes
_SHIFT_LUT = {
59: ":",
61: "+",
173: "_",
186: ":",
187: "+",
188: "<",
189: "_",
190: ">",
191: "?",
192: "~",
219: "{",
220: "|",
221: "}",
222: '"',
}
_LUT = {
8: "backspace",
9: "tab",
13: "enter",
16: "shift",
17: "control",
18: "alt",
19: "pause",
20: "caps",
27: "escape",
32: " ",
33: "pageup",
34: "pagedown",
35: "end",
36: "home",
37: "left",
38: "up",
39: "right",
40: "down",
45: "insert",
46: "delete",
91: "super",
92: "super",
93: "select",
106: "*",
107: "+",
109: "-",
110: ".",
111: "/",
144: "num_lock",
145: "scroll_lock",
186: ":",
187: "=",
188: ",",
189: "-",
190: ".",
191: "/",
192: "`",
219: "[",
220: "\\",
221: "]",
222: "'",
}
def _create_root_element(self):
div = document.createElement("div")
mpl_target = getattr(document, "pyodideMplTarget", document.body)
mpl_target.appendChild(div)
return div
def _convert_key_event(self, event):
code = int(event.which)
value = chr(code)
shift = event.shiftKey and code != 16
ctrl = event.ctrlKey and code != 17
alt = event.altKey and code != 18
# letter keys
if 65 <= code <= 90:
if not shift:
value = value.lower()
else:
shift = False
# number keys
elif 48 <= code <= 57:
if shift:
value = ")!@#$%^&*("[int(value)]
shift = False
# function keys
elif 112 <= code <= 123:
value = "f%s" % (code - 111)
# number pad keys
elif 96 <= code <= 105:
value = "%s" % (code - 96)
# keys with shift alternatives
elif code in self._SHIFT_LUT and shift:
value = self._SHIFT_LUT[code]
shift = False
elif code in self._LUT:
value = self._LUT[code]
key = []
if shift:
key.append("shift")
if ctrl:
key.append("ctrl")
if alt:
key.append("alt")
key.append(value)
return "+".join(key)
def onkeydown(self, event):
key = self._convert_key_event(event)
self.key_press_event(key, guiEvent=event)
def onkeyup(self, event):
key = self._convert_key_event(event)
self.key_release_event(key, guiEvent=event)
def get_window_title(self):
top = self.get_element("top")
return top.textContent
def set_window_title(self, title):
top = self.get_element("top")
self._title = title
if top is not None:
top.textContent = title
# def resize_event(self):
# # TODO
# pass
# def close_event(self):
# # TODO
# pass
def draw_rubberband(self, x0, y0, x1, y1):
rubberband = self.get_element("rubberband")
width, height = self.get_width_height()
y0 = height - y0
y1 = height - y1
x0 = math.floor(x0) + 0.5
y0 = math.floor(y0) + 0.5
x1 = math.floor(x1) + 0.5
y1 = math.floor(y1) + 0.5
if x1 < x0:
x0, x1 = x1, x0
if y1 < y0:
y0, y1 = y1, y0
context = rubberband.getContext("2d")
context.clearRect(0, 0, width * self._ratio, height * self._ratio)
context.strokeRect(
x0 * self._ratio,
y0 * self._ratio,
(x1 - x0) * self._ratio,
(y1 - y0) * self._ratio,
)
def remove_rubberband(self):
rubberband = self.get_element("rubberband")
width, height = self.get_width_height()
context = rubberband.getContext("2d")
context.clearRect(0, 0, width * self._ratio, height * self._ratio)
def new_timer(self, *args, **kwargs):
return TimerWasm(*args, **kwargs)
_FONTAWESOME_ICONS = {
"home": "fa-home",
"back": "fa-arrow-left",
"forward": "fa-arrow-right",
"zoom_to_rect": "fa-search-plus",
"move": "fa-arrows",
"download": "fa-download",
None: None,
}
FILE_TYPES = {"png": "image/png", "svg": "image/svg+xml", "pdf": "application/pdf"}
class NavigationToolbar2Wasm(NavigationToolbar2):
def _init_toolbar(self):
pass
def get_element(self):
# Create the HTML content for the toolbar
div = document.createElement("span")
def add_spacer():
span = document.createElement("span")
span.style.minWidth = "16px"
span.textContent = "\u00a0"
div.appendChild(span)
for _text, _tooltip_text, image_file, name_of_method in self.toolitems:
if image_file in _FONTAWESOME_ICONS:
if image_file is None:
add_spacer()
else:
button = document.createElement("button")
button.classList.add("fa")
button.classList.add(_FONTAWESOME_ICONS[image_file])
button.classList.add("matplotlib-toolbar-button")
add_event_listener(button, "click", getattr(self, name_of_method))
div.appendChild(button)
for format, _mimetype in sorted(list(FILE_TYPES.items())):
button = document.createElement("button")
button.classList.add("fa")
button.textContent = format
button.classList.add("matplotlib-toolbar-button")
button.id = "text"
add_event_listener(button, "click", self.ondownload)
div.appendChild(button)
return div
def ondownload(self, event):
format = event.target.textContent
self.download(format, FILE_TYPES[format])
def download(self, format, mimetype):
pass
def set_message(self, message):
self.canvas.set_message(message)
def set_cursor(self, cursor):
self.canvas.set_cursor(cursor)
def draw_rubberband(self, event, x0, y0, x1, y1):
self.canvas.draw_rubberband(x0, y0, x1, y1)
def remove_rubberband(self):
self.canvas.remove_rubberband()
class TimerWasm(TimerBase):
def _timer_start(self):
self._timer_stop()
if self._single:
self._timer: int | None = set_timeout(self._on_timer, self.interval)
else:
self._timer = set_interval(self._on_timer, self.interval)
def _timer_stop(self):
if self._timer is None:
return
elif self._single:
clear_timeout(self._timer)
self._timer = None
else:
clear_interval(self._timer)
self._timer = None
def _timer_set_interval(self):
# Only stop and restart it if the timer has already been started
if self._timer is not None:
self._timer_stop()
self._timer_start()
PK2RnX<6E>d<EFBFBD><64><EFBFBD>;<00>;*matplotlib_pyodide/html5_canvas_backend.pyimport base64
import io
import math
import numpy as np
from matplotlib import __version__, interactive
from matplotlib.backend_bases import (
FigureManagerBase,
GraphicsContextBase,
RendererBase,
_Backend,
)
from matplotlib.cbook import maxdict
from matplotlib.colors import colorConverter, rgb2hex
from matplotlib.font_manager import findfont
from matplotlib.ft2font import LOAD_NO_HINTING, FT2Font
from matplotlib.mathtext import MathTextParser
from matplotlib.path import Path
from matplotlib.transforms import Affine2D
from PIL import Image
from PIL.PngImagePlugin import PngInfo
from matplotlib_pyodide.browser_backend import FigureCanvasWasm, NavigationToolbar2Wasm
try:
from js import FontFace, ImageData, document
except ImportError as err:
raise ImportError(
"html5_canvas_backend is only supported in the browser in the main thread"
) from err
from pyodide.ffi import create_proxy
_capstyle_d = {"projecting": "square", "butt": "butt", "round": "round"}
# The URLs of fonts that have already been loaded into the browser
_font_set = set()
_base_fonts_url = "/fonts/"
interactive(True)
class FigureCanvasHTMLCanvas(FigureCanvasWasm):
def __init__(self, *args, **kwargs):
FigureCanvasWasm.__init__(self, *args, **kwargs)
def draw(self):
# Render the figure using custom renderer
self._idle_scheduled = True
orig_dpi = self.figure.dpi
if self._ratio != 1:
self.figure.dpi *= self._ratio
try:
width, height = self.get_width_height()
canvas = self.get_element("canvas")
if canvas is None:
return
ctx = canvas.getContext("2d")
renderer = RendererHTMLCanvas(ctx, width, height, self.figure.dpi, self)
self.figure.draw(renderer)
except Exception as e:
raise RuntimeError("Rendering failed") from e
finally:
self.figure.dpi = orig_dpi
self._idle_scheduled = False
def get_pixel_data(self):
"""
Directly getting the underlying pixel data (using `getImageData()`)
results in a different (but similar) image than the reference image.
The method below takes a longer route
(pixels --> encode PNG --> decode PNG --> pixels)
but gives us the exact pixel data that the reference image has allowing
us to do a fair comparison test.
"""
canvas = self.get_element("canvas")
img_URL = canvas.toDataURL("image/png")[21:]
canvas_base64 = base64.b64decode(img_URL)
return np.asarray(Image.open(io.BytesIO(canvas_base64)))
def print_png(
self, filename_or_obj, *args, metadata=None, pil_kwargs=None, **kwargs
):
if metadata is None:
metadata = {}
if pil_kwargs is None:
pil_kwargs = {}
metadata = {
"Software": f"matplotlib version{__version__}, http://matplotlib.org/",
**metadata,
}
if "pnginfo" not in pil_kwargs:
pnginfo = PngInfo()
for k, v in metadata.items():
pnginfo.add_text(k, v)
pil_kwargs["pnginfo"] = pnginfo
pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
data = self.get_pixel_data()
(Image.fromarray(data).save(filename_or_obj, format="png", **pil_kwargs))
class NavigationToolbar2HTMLCanvas(NavigationToolbar2Wasm):
def download(self, format, mimetype):
"""
Creates a temporary `a` element with a URL containing the image
content, and then virtually clicks it. Kind of magical, but it
works...
"""
element = document.createElement("a")
data = io.BytesIO()
if format == "png":
FigureCanvasHTMLCanvas.print_png(self.canvas, data)
else:
try:
self.canvas.figure.savefig(data, format=format)
except Exception:
raise
element.setAttribute(
"href",
"data:{};base64,{}".format(
mimetype, base64.b64encode(data.getvalue()).decode("ascii")
),
)
element.setAttribute("download", f"plot.{format}")
element.style.display = "none"
document.body.appendChild(element)
element.click()
document.body.removeChild(element)
class GraphicsContextHTMLCanvas(GraphicsContextBase):
def __init__(self, renderer):
super().__init__()
self.stroke = True
self.renderer = renderer
def restore(self):
self.renderer.ctx.restore()
def set_capstyle(self, cs):
if cs in ["butt", "round", "projecting"]:
self._capstyle = cs
self.renderer.ctx.lineCap = _capstyle_d[cs]
else:
raise ValueError(f"Unrecognized cap style. Found {cs}")
def set_clip_rectangle(self, rectangle):
self.renderer.ctx.save()
if not rectangle:
self.renderer.ctx.restore()
return
x, y, w, h = np.round(rectangle.bounds)
self.renderer.ctx.beginPath()
self.renderer.ctx.rect(x, self.renderer.height - y - h, w, h)
self.renderer.ctx.clip()
def set_clip_path(self, path):
self.renderer.ctx.save()
if not path:
self.renderer.ctx.restore()
return
tpath, affine = path.get_transformed_path_and_affine()
affine = affine + Affine2D().scale(1, -1).translate(0, self.renderer.height)
self.renderer._path_helper(self.renderer.ctx, tpath, affine)
self.renderer.ctx.clip()
def set_dashes(self, dash_offset, dash_list):
self._dashes = dash_offset, dash_list
if dash_offset is not None:
self.renderer.ctx.lineDashOffset = dash_offset
if dash_list is None:
self.renderer.ctx.setLineDash([])
else:
dln = np.asarray(dash_list)
dl = list(self.renderer.points_to_pixels(dln))
self.renderer.ctx.setLineDash(dl)
def set_joinstyle(self, js):
if js in ["miter", "round", "bevel"]:
self._joinstyle = js
self.renderer.ctx.lineJoin = js
else:
raise ValueError(f"Unrecognized join style. Found {js}")
def set_linewidth(self, w):
self.stroke = w != 0
self._linewidth = float(w)
self.renderer.ctx.lineWidth = self.renderer.points_to_pixels(float(w))
class RendererHTMLCanvas(RendererBase):
def __init__(self, ctx, width, height, dpi, fig):
super().__init__()
self.fig = fig
self.ctx = ctx
self.width = width
self.height = height
self.ctx.width = self.width
self.ctx.height = self.height
self.dpi = dpi
self.fontd = maxdict(50)
self.mathtext_parser = MathTextParser("bitmap")
# Keep the state of fontfaces that are loading
self.fonts_loading = {}
def new_gc(self):
return GraphicsContextHTMLCanvas(renderer=self)
def points_to_pixels(self, points):
return (points / 72.0) * self.dpi
def _matplotlib_color_to_CSS(self, color, alpha, alpha_overrides, is_RGB=True):
if not is_RGB:
R, G, B, alpha = colorConverter.to_rgba(color)
color = (R, G, B)
if (len(color) == 4) and (alpha is None):
alpha = color[3]
if alpha is None:
CSS_color = rgb2hex(color[:3])
else:
R = int(color[0] * 255)
G = int(color[1] * 255)
B = int(color[2] * 255)
if len(color) == 3 or alpha_overrides:
CSS_color = f"""rgba({R:d}, {G:d}, {B:d}, {alpha:.3g})"""
else:
CSS_color = """rgba({:d}, {:d}, {:d}, {:.3g})""".format(
R, G, B, color[3]
)
return CSS_color
def _set_style(self, gc, rgbFace=None):
if rgbFace is not None:
self.ctx.fillStyle = self._matplotlib_color_to_CSS(
rgbFace, gc.get_alpha(), gc.get_forced_alpha()
)
if gc.get_capstyle():
self.ctx.lineCap = _capstyle_d[gc.get_capstyle()]
self.ctx.strokeStyle = self._matplotlib_color_to_CSS(
gc.get_rgb(), gc.get_alpha(), gc.get_forced_alpha()
)
self.ctx.lineWidth = self.points_to_pixels(gc.get_linewidth())
def _path_helper(self, ctx, path, transform, clip=None):
ctx.beginPath()
for points, code in path.iter_segments(transform, remove_nans=True, clip=clip):
if code == Path.MOVETO:
ctx.moveTo(points[0], points[1])
elif code == Path.LINETO:
ctx.lineTo(points[0], points[1])
elif code == Path.CURVE3:
ctx.quadraticCurveTo(*points)
elif code == Path.CURVE4:
ctx.bezierCurveTo(*points)
elif code == Path.CLOSEPOLY:
ctx.closePath()
def draw_path(self, gc, path, transform, rgbFace=None):
self._set_style(gc, rgbFace)
if rgbFace is None and gc.get_hatch() is None:
figure_clip = (0, 0, self.width, self.height)
else:
figure_clip = None
transform += Affine2D().scale(1, -1).translate(0, self.height)
self._path_helper(self.ctx, path, transform, figure_clip)
if rgbFace is not None:
self.ctx.fill()
self.ctx.fillStyle = "#000000"
if gc.stroke:
self.ctx.stroke()
def draw_markers(self, gc, marker_path, marker_trans, path, trans, rgbFace=None):
super().draw_markers(gc, marker_path, marker_trans, path, trans, rgbFace)
def draw_image(self, gc, x, y, im, transform=None):
im = np.flipud(im)
h, w, d = im.shape
y = self.ctx.height - y - h
im = np.ravel(np.uint8(np.reshape(im, (h * w * d, -1)))).tobytes()
pixels_proxy = create_proxy(im)
pixels_buf = pixels_proxy.getBuffer("u8clamped")
img_data = ImageData.new(pixels_buf.data, w, h)
self.ctx.save()
in_memory_canvas = document.createElement("canvas")
in_memory_canvas.width = w
in_memory_canvas.height = h
in_memory_canvas_context = in_memory_canvas.getContext("2d")
in_memory_canvas_context.putImageData(img_data, 0, 0)
self.ctx.drawImage(in_memory_canvas, x, y, w, h)
self.ctx.restore()
pixels_proxy.destroy()
pixels_buf.release()
def _get_font(self, prop):
key = hash(prop)
font_value = self.fontd.get(key)
if font_value is None:
fname = findfont(prop)
font_value = self.fontd.get(fname)
if font_value is None:
font = FT2Font(str(fname))
font_file_name = fname[fname.rfind("/") + 1 :]
font_value = font, font_file_name
self.fontd[fname] = font_value
self.fontd[key] = font_value
font, font_file_name = font_value
font.clear()
font.set_size(prop.get_size_in_points(), self.dpi)
return font, font_file_name
def get_text_width_height_descent(self, s, prop, ismath):
w: float
h: float
if ismath:
image, d = self.mathtext_parser.parse(s, self.dpi, prop)
image_arr = np.asarray(image)
h, w = image_arr.shape
else:
font, _ = self._get_font(prop)
font.set_text(s, 0.0, flags=LOAD_NO_HINTING)
w, h = font.get_width_height()
w /= 64.0
h /= 64.0
d = font.get_descent() / 64.0
return w, h, d
def _draw_math_text(self, gc, x, y, s, prop, angle):
rgba, descent = self.mathtext_parser.to_rgba(
s, gc.get_rgb(), self.dpi, prop.get_size_in_points()
)
height, width, _ = rgba.shape
angle = math.radians(angle)
if angle != 0:
self.ctx.save()
self.ctx.translate(x, y)
self.ctx.rotate(-angle)
self.ctx.translate(-x, -y)
self.draw_image(gc, x, -y - descent, np.flipud(rgba))
if angle != 0:
self.ctx.restore()
def load_font_into_web(self, loaded_face, font_url):
fontface = loaded_face.result()
document.fonts.add(fontface)
self.fonts_loading.pop(font_url, None)
# Redraw figure after font has loaded
self.fig.draw()
return fontface
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
if ismath:
self._draw_math_text(gc, x, y, s, prop, angle)
return
angle = math.radians(angle)
width, height, descent = self.get_text_width_height_descent(s, prop, ismath)
x -= math.sin(angle) * descent
y -= math.cos(angle) * descent - self.ctx.height
font_size = self.points_to_pixels(prop.get_size_in_points())
_, font_file_name = self._get_font(prop)
font_face_arguments = (
prop.get_name(),
f"url({_base_fonts_url + font_file_name})",
)
# The following snippet loads a font into the browser's
# environment if it wasn't loaded before. This check is necessary
# to help us avoid loading the same font multiple times. Further,
# it helps us to avoid the infinite loop of
# load font --> redraw --> load font --> redraw --> ....
if font_face_arguments not in _font_set:
_font_set.add(font_face_arguments)
f = FontFace.new(*font_face_arguments)
font_url = font_face_arguments[1]
self.fonts_loading[font_url] = f
f.load().add_done_callback(
lambda result: self.load_font_into_web(result, font_url)
)
font_property_string = "{} {} {:.3g}px {}, {}".format(
prop.get_style(),
prop.get_weight(),
font_size,
prop.get_name(),
prop.get_family()[0],
)
if angle != 0:
self.ctx.save()
self.ctx.translate(x, y)
self.ctx.rotate(-angle)
self.ctx.translate(-x, -y)
self.ctx.font = font_property_string
self.ctx.fillStyle = self._matplotlib_color_to_CSS(
gc.get_rgb(), gc.get_alpha(), gc.get_forced_alpha()
)
self.ctx.fillText(s, x, y)
self.ctx.fillStyle = "#000000"
if angle != 0:
self.ctx.restore()
class FigureManagerHTMLCanvas(FigureManagerBase):
def __init__(self, canvas, num):
super().__init__(canvas, num)
self.set_window_title("Figure %d" % num)
self.toolbar = NavigationToolbar2HTMLCanvas(canvas)
def show(self, *args, **kwargs):
self.canvas.show(*args, **kwargs)
def resize(self, w, h):
pass
def set_window_title(self, title):
self.canvas.set_window_title(title)
@_Backend.export
class _BackendHTMLCanvas(_Backend):
FigureCanvas = FigureCanvasHTMLCanvas
FigureManager = FigureManagerHTMLCanvas
@staticmethod
def show(*args, **kwargs):
from matplotlib import pyplot as plt
plt.gcf().canvas.show(*args, **kwargs)
PK2RnX<06>3L<33><00>"matplotlib_pyodide/wasm_backend.py"""
A matplotlib backend that renders to an HTML5 canvas in the same thread.
The Agg backend is used for the actual rendering underneath, and renders the
buffer to the HTML5 canvas. This happens with only a single copy of the data
into the Canvas -- passing the data from Python to JavaScript requires no
copies.
See matplotlib.backend_bases for documentation for most of the methods, since
this primarily is just overriding methods in the base class.
"""
# TODO: Figure resizing support
import base64
import io
from js import ImageData, document
from matplotlib import interactive
from matplotlib.backend_bases import FigureManagerBase, _Backend
from matplotlib.backends import backend_agg
from matplotlib_pyodide.browser_backend import FigureCanvasWasm, NavigationToolbar2Wasm
interactive(True)
class FigureCanvasAggWasm(backend_agg.FigureCanvasAgg, FigureCanvasWasm):
def __init__(self, *args, **kwargs):
backend_agg.FigureCanvasAgg.__init__(self, *args, **kwargs)
FigureCanvasWasm.__init__(self, *args, **kwargs)
def draw(self):
from pyodide.ffi import create_proxy
# Render the figure using Agg
self._idle_scheduled = True
orig_dpi = self.figure.dpi
if self._ratio != 1:
self.figure.dpi *= self._ratio
pixels_proxy = None
pixels_buf = None
try:
super().draw()
# Copy the image buffer to the canvas
width, height = self.get_width_height()
canvas = self.get_element("canvas")
if canvas is None:
return
pixels = self.buffer_rgba().tobytes()
pixels_proxy = create_proxy(pixels)
pixels_buf = pixels_proxy.getBuffer("u8clamped")
image_data = ImageData.new(pixels_buf.data, width, height)
ctx = canvas.getContext("2d")
ctx.putImageData(image_data, 0, 0)
finally:
self.figure.dpi = orig_dpi
self._idle_scheduled = False
if pixels_proxy:
pixels_proxy.destroy()
if pixels_buf:
pixels_buf.release()
class NavigationToolbar2AggWasm(NavigationToolbar2Wasm):
def download(self, format, mimetype):
# Creates a temporary `a` element with a URL containing the image
# content, and then virtually clicks it. Kind of magical, but it
# works...
element = document.createElement("a")
data = io.BytesIO()
try:
self.canvas.figure.savefig(data, format=format)
except Exception:
raise
element.setAttribute(
"href",
"data:{};base64,{}".format(
mimetype, base64.b64encode(data.getvalue()).decode("ascii")
),
)
element.setAttribute("download", f"plot.{format}")
element.style.display = "none"
document.body.appendChild(element)
element.click()
document.body.removeChild(element)
class FigureManagerAggWasm(FigureManagerBase):
def __init__(self, canvas, num):
FigureManagerBase.__init__(self, canvas, num)
self.set_window_title("Figure %d" % num)
self.toolbar = NavigationToolbar2AggWasm(canvas)
def show(self, *args, **kwargs):
self.canvas.show(*args, **kwargs)
def resize(self, w, h):
pass
def set_window_title(self, title):
self.canvas.set_window_title(title)
@_Backend.export
class _BackendWasmCoreAgg(_Backend):
FigureCanvas = FigureCanvasAggWasm
FigureManager = FigureManagerAggWasm
@staticmethod
def show(*args, **kwargs):
from matplotlib import pyplot as plt
plt.gcf().canvas.show(*args, **kwargs)
PK2RnX<6E>i0UAUA*matplotlib_pyodide-0.2.1.dist-info/LICENSEMozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
PK2RnX<6E>V<EFBFBD>8<EFBFBD>V<00>V+matplotlib_pyodide-0.2.1.dist-info/METADATAMetadata-Version: 2.1
Name: matplotlib-pyodide
Version: 0.2.1
Summary: HTML5 backends for Matplotlib compatible with Pyodide
Author: Pyodide developers
License: Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
Project-URL: Homepage, https://github.com/pyodide/matplotlib-pyodide
Project-URL: Bug Tracker, https://github.com/pyodide/matplotlib-pyodide/issues
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest-pyodide ==0.52.2 ; extra == 'test'
Requires-Dist: pytest-cov ; extra == 'test'
Requires-Dist: build ==0.10 ; extra == 'test'
# matplotlib-pyodide
[![PyPI Latest Release](https://img.shields.io/pypi/v/matplotlib-pyodide.svg)](https://pypi.org/project/matplotlib-pyodide/)
![GHA](https://github.com/pyodide/matplotlib-pyodide/actions/workflows/main.yml/badge.svg)
[![codecov](https://codecov.io/gh/pyodide/matplotlib-pyodide/branch/main/graph/badge.svg)](https://codecov.io/gh/pyodide/matplotlib-pyodide)
HTML5 backends for Matplotlib compatible with Pyodide
This package includes two matplotlib backends,
- the `wasm_backend` which from allows rendering the Agg buffer as static images into an HTML canvas
- an interactive HTML5 canvas backend `html5_canvas_backend` described in
[this blog post](https://blog.pyodide.org/posts/canvas-renderer-matplotlib-in-pyodide/)
## Installation
This package will be installed as a dependency when you load `matplotlib` in Pyodide.
## Usage
To change the backend in matplotlib,
- for the wasm backend,
```py
import matplotlib
matplotlib.use("module://matplotlib_pyodide.wasm_backend")
```
- for the interactive HTML5 backend;
```py
import matplotlib
matplotlib.use("module://matplotlib_pyodide.html5_canvas_backend")
```
By default, matplotlib figures will be rendered inside a div that's appended to the end of `document.body`.
You can override this behavior by setting `document.pyodideMplTarget` to an HTML element. If you had an HTML
element with id "target", you could configure the backend to render visualizations inside it with this code:
```py
document.pyodideMplTarget = document.getElementById('target')
```
For more information see the [matplotlib documentation](https://matplotlib.org/stable/users/explain/backends.html).
## License
pyodide-cli uses the [Mozilla Public License Version
2.0](https://choosealicense.com/licenses/mpl-2.0/).
PK2RnXI<><49>\\(matplotlib_pyodide-0.2.1.dist-info/WHEELWheel-Version: 1.0
Generator: bdist_wheel (0.41.2)
Root-Is-Purelib: true
Tag: py3-none-any
PK2RnX<6E>0.0matplotlib_pyodide-0.2.1.dist-info/top_level.txtmatplotlib_pyodide
PK2RnX<1C> //)matplotlib_pyodide-0.2.1.dist-info/RECORDmatplotlib_pyodide/__init__.py,sha256=ZIdCL09RKR80Zr_q2NRZUI2cmO7vdP-eg4DWNAN40aI,184
matplotlib_pyodide/browser_backend.py,sha256=-BrYWjGtPMncIKQKAzogYGckDirEoSYSQ-bInHgQdSQ,16520
matplotlib_pyodide/html5_canvas_backend.py,sha256=-hqapI4VhXqCMZGkf03d6BVvibx3uA0PMWD2He8J-SY,15309
matplotlib_pyodide/wasm_backend.py,sha256=JBC1HSQAd2r_tN_JS3UcgRNyaDHMisyqJ-kQvxJcZMg,3728
matplotlib_pyodide-0.2.1.dist-info/LICENSE,sha256=HyVuytGSiAUQ6ErWBHTqt1iSGHhLmlC8fO7jTCuR8dU,16725
matplotlib_pyodide-0.2.1.dist-info/METADATA,sha256=FIGfXk3DOxLyPCBJArF12MpIe2TlVMHLZLhQ2QJjmGw,22254
matplotlib_pyodide-0.2.1.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
matplotlib_pyodide-0.2.1.dist-info/top_level.txt,sha256=DknuCanWdBwuoPwJjAxxpWOeSeDktvupsrjO6jqitf0,19
matplotlib_pyodide-0.2.1.dist-info/RECORD,,
PK2RnX6<>L<EFBFBD><00><00>matplotlib_pyodide/__init__.pyPK2RnX<6E><58>}<7D>@<00>@%<00><01>matplotlib_pyodide/browser_backend.pyPK2RnX<6E>d<EFBFBD><64><EFBFBD>;<00>;*<00><01>Amatplotlib_pyodide/html5_canvas_backend.pyPK2RnX<06>3L<33><00>"<00><01>}matplotlib_pyodide/wasm_backend.pyPK2RnX<6E>i0UAUA*<00><01><>matplotlib_pyodide-0.2.1.dist-info/LICENSEPK2RnX<6E>V<EFBFBD>8<EFBFBD>V<00>V+<00>A<>matplotlib_pyodide-0.2.1.dist-info/METADATAPK2RnXI<><49>\\(<00>x%matplotlib_pyodide-0.2.1.dist-info/WHEELPK2RnX<6E>0.0<00>&matplotlib_pyodide-0.2.1.dist-info/top_level.txtPK2RnX<1C> //)<00>{&matplotlib_pyodide-0.2.1.dist-info/RECORDPK <00>)