|
| 1 | +__all__ = ["GraphicsContextRendererCairo", "install", "uninstall"] |
| 2 | + |
| 3 | +from matplotlib.backend_bases import GraphicsContextBase, RendererBase |
| 4 | +from matplotlib.backends import backend_cairo |
| 5 | +from matplotlib.font_manager import ttfFontProperty |
| 6 | +from matplotlib.mathtext import MathtextBackendCairo, MathTextParser |
| 7 | +from . import _mpl_cairo |
| 8 | + |
| 9 | + |
| 10 | +class MathtextBackendCairo2(MathtextBackendCairo): |
| 11 | + def render_glyph(self, ox, oy, info): |
| 12 | + self.glyphs.append( |
| 13 | + # Convert to ttfFontProperty here. |
| 14 | + (ttfFontProperty(info.font), |
| 15 | + info.fontsize, |
| 16 | + chr(info.num), |
| 17 | + ox, |
| 18 | + oy - info.offset - self.height)) |
| 19 | + |
| 20 | + |
| 21 | +MathTextParser._backend_mapping["cairo2"] = MathtextBackendCairo2 |
| 22 | + |
| 23 | + |
| 24 | +class GraphicsContextRendererCairo( |
| 25 | + _mpl_cairo.GraphicsContextRendererCairo, |
| 26 | + GraphicsContextBase, |
| 27 | + RendererBase): |
| 28 | + def __init__(self, *args, **kwargs): |
| 29 | + super().__init__(*args, **kwargs) |
| 30 | + self.mathtext_parser = MathTextParser("cairo2") |
| 31 | + |
| 32 | + |
| 33 | +# Keep the two classes separate, so that we can figure out who inherits what. |
| 34 | + |
| 35 | + |
| 36 | +class GraphicsContextCairo(GraphicsContextRendererCairo): |
| 37 | + pass |
| 38 | + |
| 39 | + |
| 40 | +class RendererCairo(GraphicsContextRendererCairo): |
| 41 | + pass |
| 42 | + |
| 43 | + |
| 44 | +_class_pairs = [ |
| 45 | + (backend_cairo.GraphicsContextCairo, GraphicsContextRendererCairo), |
| 46 | + (backend_cairo.RendererCairo, RendererCairo)] |
| 47 | + |
| 48 | + |
| 49 | +def _swap(class_pairs): |
| 50 | + for old, new in class_pairs: |
| 51 | + for cls in old.__subclasses__(): |
| 52 | + idx = cls.__bases__.index(old) |
| 53 | + cls.__bases__ = cls.__bases__[:idx] + (new,) + cls.__bases__[idx + 1:] |
| 54 | + setattr(backend_cairo, new.__name__, new) |
| 55 | + |
| 56 | + |
| 57 | +def install(): |
| 58 | + """Switch to new cairo backend implementation. |
| 59 | + """ |
| 60 | + _swap(_class_pairs) |
| 61 | + |
| 62 | + |
| 63 | +def uninstall(): |
| 64 | + """Switch back to upstream cairo backend implementation. |
| 65 | + """ |
| 66 | + _swap([(new, old) for old, new in _class_pairs]) |
0 commit comments