tikz_directive.py 9.11 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# -*- coding: utf-8 -*-

import base64
import codecs
import jinja2
import os
import tempfile
import shutil
import subprocess
import sys
from PIL import Image
from docutils import nodes
from docutils.parsers.rst import Directive
from docutils.parsers.rst import directives, states
from docutils.nodes import fully_normalize_name, whitespace_normalize_name
from docutils.parsers.rst.roles import set_classes


TEMPLATE_LATEX = u"""
\\documentclass{%- if document_options -%}[{{ document_options }}]{%- endif -%}{standalone}
{% if not do_not_use_default_packages -%}
\\usepackage[utf8]{inputenc}
\\usepackage[T1]{fontenc}
\\usepackage{lmodern}
25
\\usepackage[{%- if lang -%}{{ lang }}{%- else -%}english{%- endif -%}]{babel}
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
\\usepackage[usenames, dvipsnames, svgnames, table]{xcolor}
\\usepackage[pdftex]{graphicx}
{% endif -%}
{% for extra_package in extra_packages -%}
    \\usepackage{{ extra_package }}
{% endfor -%}
\\usepackage{tikz}
{% for tikz_lib in tikz_libs -%}
    \\usetikzlibrary{ {{ tikz_lib }} }
{% endfor -%}
\\begin{document}
\\begin{tikzpicture}{%- if tikzpicture_options -%}[{{ tikzpicture_options }}]{%- endif %}
    {{ tikz_code }}
\\end{tikzpicture}
\\end{document}
""".strip()


TMP_LATEX_FILENAME = "tikz_picture.tex"
TMP_PDF_FILENAME = "tikz_picture.pdf"
OUT_PDF_FILENAME = "_tikz_rendered{:04d}.pdf"
TMP_PNG_FILENAME = "tikz_picture.png"
OUT_PNG_FILENAME = "_tikz_rendered{:04d}.png"


VALID_OUTPUT_MODES = ("latex", "html")
_output_mode = "latex"


class InvalidOutputModeError(Exception):
    pass


def set_output_mode(output_mode):
    global _output_mode

    if output_mode in VALID_OUTPUT_MODES:
        _output_mode = output_mode
    else:
        raise InvalidOutputModeError("{} is not valid output mode".format(output_mode))


class TemporaryDirectory(object):
    def __init__(self):
        self.tmp_dir = tempfile.mkdtemp()

    def __enter__(self):
        return self.tmp_dir

    def __exit__(self, exception_type, value, traceback):
        shutil.rmtree(self.tmp_dir)
        self.tmp_dir = None


def render_tikz(tikz_code, options, output_png=False):
    self = render_tikz
    if not hasattr(self, "image_number"):
        self.image_number = 1
    if "do_not_use_default_packages" in options:
        options["do_not_use_default_packages"] = True
    if "extra_packages" in options:
        options["extra_packages"] = [package.strip() for package in options["extra_packages"].split(";")]
    if "tikz_libs" in options:
        options["tikz_libs"] = [tikz_lib.strip() for tikz_lib in options["tikz_libs"].split(",")]
    template = jinja2.Template(TEMPLATE_LATEX)
    latex_output = template.render(tikz_code=tikz_code, **options)
    out_pdf_filename = OUT_PDF_FILENAME.format(self.image_number)
    out_png_filename = OUT_PNG_FILENAME.format(self.image_number)
    with TemporaryDirectory() as tmp_dir:
        tmp_latex_path = os.path.join(tmp_dir, TMP_LATEX_FILENAME)
        tmp_pdf_path = os.path.join(tmp_dir, TMP_PDF_FILENAME)
        tmp_png_path = os.path.join(tmp_dir, TMP_PNG_FILENAME)
        with codecs.open(tmp_latex_path, "w", "utf-8") as f:
            f.write(latex_output)
        with open(os.devnull, "w") as devnull:
            try:
                subprocess.check_call(
                    ["latexmk", "-pdf", "-halt-on-error", TMP_LATEX_FILENAME],
                    cwd=tmp_dir,
                    stdout=devnull,
                    stderr=devnull,
                )
            except subprocess.CalledProcessError:
                with codecs.open(
                    os.path.join(tmp_dir, "{}.log".format(os.path.splitext(TMP_LATEX_FILENAME)[0])), "r", "utf-8"
                ) as f:
                    sys.stderr.write(f.read())
                raise
            if output_png:
                subprocess.check_call(
                    ["mudraw", "-r", "360", "-o", TMP_PNG_FILENAME, TMP_PDF_FILENAME],
                    cwd=tmp_dir,
                    stdout=devnull,
                    stderr=devnull,
                )
        if output_png:
            shutil.move(tmp_png_path, out_png_filename)
        else:
            shutil.move(tmp_pdf_path, out_pdf_filename)
    return out_png_filename if output_png else out_pdf_filename


def convert_png_to_html_base64(png_filepath):
    with open(png_filepath.encode(sys.getfilesystemencoding()), "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())
    return "data:image/png;base64," + encoded_string


class Tikz(Directive):
    align_values = ("left", "center", "right")

    required_arguments = 0
    optional_arguments = 1
    option_spec = {
        "alt": directives.unchanged,
        "height": directives.length_or_unitless,
        "width": directives.length_or_percentage_or_unitless,
        "scale": directives.percentage,
        "align": lambda argument: directives.choice(argument, Tikz.align_values),
        "name": directives.unchanged,
        "target": directives.unchanged_required,
        "class": directives.class_option,
        "document_options": directives.unchanged,
149
        "lang": directives.unchanged,
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        "do_not_use_default_packages": directives.flag,
        "extra_packages": directives.unchanged,
        "tikz_libs": directives.unchanged,
        "tikzpicture_options": directives.unchanged,
    }
    has_content = True

    def run(self):
        if len(self.arguments) > 0:
            read_from_file = True
            tikz_source_filename = self.arguments[0]
        else:
            read_from_file = False
        if "align" in self.options and self.options["align"] not in self.align_values:
            raise self.error(
                'Error in "%s" directive: "%s" is not a valid value for '
                'the "align" option.  Valid values for "align" are: "%s".'
                % (self.name, self.options["align"], '", "'.join(self.align_values))
            )
        if "document_options" not in self.options:
170
            self.options["document_options"] = "12pt, border=5pt"
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
        is_output_mode_html = _output_mode == "html"
        messages = []
        if read_from_file:
            with codecs.open(tikz_source_filename, "r", "utf-8") as f:
                content = f.read()
        else:
            content = self.content
        rendered_tikz_filename = render_tikz("\n".join(content), self.options, output_png=is_output_mode_html)
        if is_output_mode_html:
            reference = directives.uri(convert_png_to_html_base64(rendered_tikz_filename))
        else:
            reference = directives.uri(rendered_tikz_filename)
        self.options["uri"] = reference
        if is_output_mode_html and not any(attr in self.options for attr in ("height", "width", "scale")):
            try:
                image = Image.open(rendered_tikz_filename.encode(sys.getfilesystemencoding()))
            except (IOError, UnicodeEncodeError):
                pass  # TODO: warn?
            else:
                self.options["width"] = "{}pt".format(image.size[0] / 5)
        reference_node = None
        if "target" in self.options:
            block = states.escape2null(self.options["target"]).splitlines()
            block = [line for line in block]
            target_type, data = self.state.parse_target(block, self.block_text, self.lineno)
            if target_type == "refuri":
                reference_node = nodes.reference(refuri=data)
            elif target_type == "refname":
                reference_node = nodes.reference(
                    refname=fully_normalize_name(data), name=whitespace_normalize_name(data)
                )
                reference_node.indirect_reference_name = data
                self.state.document.note_refname(reference_node)
            else:  # malformed target
                messages.append(data)  # data is a system message
            del self.options["target"]
        set_classes(self.options)
        image_node = nodes.image(self.block_text, **self.options)
        self.add_name(image_node)
        if reference_node:
            reference_node += image_node
            return messages + [reference_node]
        else:
            return messages + [image_node]


class TikzFigure(Tikz):
    option_spec = Tikz.option_spec.copy()
    option_spec["figwidth"] = lambda argument: directives.length_or_percentage_or_unitless(argument, "px")
    option_spec["figclass"] = directives.class_option
    option_spec["align"] = lambda argument: directives.choice(argument, TikzFigure.align_values)
    option_spec["caption"] = directives.unchanged
    has_content = True

    def run(self):
        figwidth = self.options.pop("figwidth", None)
        figclasses = self.options.pop("figclass", None)
        align = self.options.pop("align", None)
        caption = self.options.pop("caption", None)
        (image_node,) = Tikz.run(self)
        if isinstance(image_node, nodes.system_message):
            return [image_node]
        figure_node = nodes.figure("", image_node)
        if figwidth is not None:
            figure_node["width"] = figwidth
        if figclasses:
            figure_node["classes"] += figclasses
        if align:
            figure_node["align"] = align
        if caption:
            caption = nodes.caption("", text=caption)
            figure_node += caption
        return [figure_node]