예제 #1
0
    def run(self):
        code_node = CodeBlock.run(self)
        nodes.image()

        from PIL import Image

        lib_path = os.path.abspath('..')
        working_path = os.path.dirname(os.path.realpath(__file__))
        static_path = os.path.join(working_path, '..', '_static')

        sys.path.append(lib_path)
        os.chdir(working_path)

        node = PILNode()

        g = globals()
        l = locals()
        for line in self.content:
            result = exec(line, g, l)

        buffer = io.BytesIO()
        new_img = l.get('new_img')
        new_img.save(buffer, format='PNG')

        image_node = nodes.image()
        image_node['alt'] = 'New Image'
        image_node['uri'] = 'data:image/png;base64,' + base64.b64encode(
            buffer.getvalue()).decode()

        node += code_node
        node += image_node

        return [node]
예제 #2
0
    def run(self):

        # Needed to get access to options
        global options

        # Reference is the link to the svg file
        # Adds reference to the options list
        reference = directives.uri(self.arguments[0])
        self.options['uri'] = reference
        options.append(self.options['uri'])

        # Creates the svg class
        html_node = None
        if isLatex == False:

            html_node = gliffy()

            # Adds html class "gliffy_img" to all nodes created from now on
            self.options['classes'] = ['gliffy_img']

            # Creates an img version of the svg
            # Necessary to pass X Frame Options denial
            # Image is not visible in browser, hidden by gliffy_img class
            html_node += nodes.image(rawsource=self.options['uri'],
                                     **self.options)

        else:
            # This should insert the svg into the pdf but it does nothing
            uri = self.options['uri']
            uri = uri[:3] + "png"
            print("image uri is: " + uri)
            html_node = nodes.image(rawsource="test-svg.png", **self.options)
            self.add_name(html_node)

        return [html_node]
예제 #3
0
    def to_image(self, builder):
        if builder.format == 'html':
            reldir = "_images"
            outdir = os.path.join(builder.outdir, '_images')
        else:
            reldir = ""
            outdir = builder.outdir

        hashed = sha1((self['filename'] + self['sheet']).encode('utf-8')).hexdigest()
        filename = "astah-%s.png" % hashed
        path = os.path.join(outdir, filename)
        last_modified = os.stat(self['filename']).st_mtime

        if not os.path.exists(path) or os.stat(path).st_mtime < last_modified:
            ret = self.convert_to(path, builder=builder)
            if ret:
                os.utime(path, (last_modified, last_modified))
            else:
                return nodes.Text('')

        relfn = os.path.join(reldir, filename)
        image_node = nodes.image(candidates={'*': relfn}, **self.attributes)
        image_node['uri'] = relfn

        return image_node
예제 #4
0
def on_doctree_resolved(self, doctree, docname):
    if self.builder.format in ('html', 'slides'):
        return

    try:
        image_format = get_image_format_for(self.builder)
    except Exception as exc:
        if self.builder.config.rackdiag_debug:
            traceback.print_exc()

        self.builder.warn('rackdiag error: %s' % exc)
        for node in doctree.traverse(rackdiag_node):
            node.parent.remove(node)

        return

    for node in doctree.traverse(rackdiag_node):
        try:
            with Application():
                relfn = node.get_relpath(image_format, self.builder)
                image = node.to_drawer(image_format, self.builder)
                if not os.path.isfile(image.filename):
                    image.draw()
                    image.save()

                image = nodes.image(uri=relfn,
                                    candidates={'*': relfn},
                                    **node['options'])
                node.parent.replace(node, image)
        except Exception as exc:
            if self.builder.config.rackdiag_debug:
                traceback.print_exc()

            self.builder.warn('dot code %r: %s' % (node['code'], str(exc)))
            node.parent.remove(node)
예제 #5
0
    def run(self):
        m = graph_path.match(self.arguments[0])

        if not m:
            raise self.error('Did not understand reference to Graphviz file.')

        return [nodes.image(uri='graph/{}'.format(m.group(1)))]
예제 #6
0
def size_image(filename, width, height, attributes):
    attributes['uri'] = filename
    attributes['rawsource']=filename
    img = image(**attributes)
    img['width'] = '%f' % width
    img['height'] = '%f' % height
    return img
예제 #7
0
파일: photo.py 프로젝트: blais/nabu
def photo_directive(name, arguments, options, content, lineno, content_offset,
                    block_text, state, state_machine):
    """
    Special photo directive, which will display a thumbnail of the image with a
    link to a photo page.
    """
    reference = ''.join(arguments[0].split('\n'))
    if reference.find(' ') != -1:
        error = state_machine.reporter.error('Photo URI contains whitespace.',
                                             '',
                                             nodes.literal_block(
                                                 block_text, block_text),
                                             line=lineno)
        return [error]
    options['uri'] = reference
    options['photo'] = '1'
    image_node = nodes.image(block_text, **options)

    if 'align' in options and options['align'] == 'center':
        div_node = nodes.section(CLASS='photodiv')
        div_node.append(image_node)
        results = [div_node]
    else:
        results = [image_node]
    return results
    def run(self):
        path = os.path.abspath(os.path.join('output', 'images'))
        if not os.path.exists(path):
            os.makedirs(path)

        nodes = []
        body = '\n'.join(self.content)

        try:
            uml_format = self.options.get('format', 'png')
            url = global_siteurl + '/images/' + generate_uml_image(
                path, body, uml_format)
        except Exception as exc:
            error = self.state_machine.reporter.error(
                'Failed to run plantuml: %s' % exc,
                literal_block(self.block_text, self.block_text),
                line=self.lineno)
            nodes.append(error)
        else:
            alt = self.options.get('alt', 'uml diagram')
            classes = self.options.pop('class', ['uml'])
            imgnode = image(uri=url, classes=classes, alt=alt)
            nodes.append(imgnode)

        return nodes
예제 #9
0
def on_doctree_resolved(self, doctree, docname):
    if self.builder.format in ('html', 'slides'):
        return

    try:
        image_format = get_image_format_for(self.builder)
    except Exception as exc:
        if self.builder.config.rackdiag_debug:
            traceback.print_exc()

        self.builder.warn('rackdiag error: %s' % exc)
        for node in doctree.traverse(rackdiag_node):
            node.parent.remove(node)

        return

    for node in doctree.traverse(rackdiag_node):
        try:
            with Application():
                relfn = node.get_relpath(image_format, self.builder)
                image = node.to_drawer(image_format, self.builder)
                if not os.path.isfile(image.filename):
                    image.draw()
                    image.save()

                image = nodes.image(uri=relfn, candidates={'*': relfn}, **node['options'])
                node.parent.replace(node, image)
        except Exception as exc:
            if self.builder.config.rackdiag_debug:
                traceback.print_exc()

            self.builder.warn('dot code %r: %s' % (node['code'], str(exc)))
            node.parent.remove(node)
예제 #10
0
    def run(self):
        env = self.state.document.settings.env
        src_dir = env.srcdir
        uml_dir = os.path.join(src_dir, self.DIR_NAME)

        if os.path.basename(uml_dir) not in os.listdir(src_dir):
            os.mkdir(uml_dir)
        env.uml_dir = uml_dir
        module_path = self.arguments[0]
        os.chdir(uml_dir)
        basename = os.path.basename(module_path).split(".")[0]
        print call(['pyreverse', '-o', 'png', '-p', basename,
                    os.path.abspath(os.path.join(src_dir, module_path))])
        uri = directives.uri(os.path.join(self.DIR_NAME,
                                          "classes_{0}.png".format(basename)))
        scale = 100
        max_width = 1000
        if IMAGE:
            i = IMAGE.open(os.path.join(src_dir, uri))
            image_width = i.size[0]
            if image_width > max_width:
                scale = max_width * scale / image_width
        img = nodes.image(uri=uri, scale=scale)
        os.chdir(src_dir)
        return [img]
예제 #11
0
 def visit_img(self, node):
     image = nodes.image()
     image['uri'] = node.attrib.pop('src', '')
     alt = node.attrib.pop('alt', '')
     if alt:
         image += nodes.Text(alt)
     return image
예제 #12
0
    def run(self):
        """Perform task associated with this directive."""
        env = self.state.document.settings.env

        wkf_file = directives.uri(self.arguments[0])
        if not os.path.isabs(wkf_file):
            wkf_file = os.path.join(os.path.dirname(env.doc2path(env.docname)),
                                    wkf_file)

        wkf_name = os.path.splitext(wkf_file)[0]
        svg_file = "%s.svg" % wkf_name
        if out_of_date(wkf_file, svg_file):
            # render the workflow again
            with open(wkf_file, 'r') as f:
                wkf = json.load(f)

            w = self.options.get('width', 600)
            h = self.options.get('height', 600)

            drawing, bb = svg.export_workflow(wkf, {}, (w, h))
            del bb

            with open(svg_file, 'w') as f:
                f.write(drawing)

        self.options['uri'] = svg_file
        node = nodes.image(**self.options)

        return [node]
예제 #13
0
    def run(self):
        path = os.path.abspath(os.path.join("output", "images"))
        if not os.path.exists(path):
            os.makedirs(path)

        nodes = []
        body = "\n".join(self.content)

        try:
            uml_format = self.options.get("format", "png")
            url = (
                global_siteurl + "/images/" + generate_uml_image(path, body, uml_format)
            )
        except Exception as exc:
            error = self.state_machine.reporter.error(
                "Failed to run plantuml: %s" % exc,
                literal_block(self.block_text, self.block_text),
                line=self.lineno,
            )
            nodes.append(error)
        else:
            alt = self.options.get("alt", "uml diagram")
            classes = self.options.pop("class", ["uml"])
            imgnode = image(uri=url, classes=classes, alt=alt)
            nodes.append(imgnode)

        return nodes
예제 #14
0
    def run(self):
        reference = directives.uri(self.arguments[0])
        if 'gallery/' in reference:
            reference = reference.split('gallery/')[1]
            parts = reference.split('/')
            gallery_id = parts[0]
            photo_id = parts[2]
            if '#' in photo_id:
                photo_id = photo_id.split('#')[0]
            image_url = '%s/photos/%s-M.jpg' % (SMUGMUG, photo_id)
            lightbox = '%s/gallery/%s/1/#%s-A-LB' % (
                SMUGMUG, gallery_id, photo_id)
        else:
            # New style
            if 'A-LB' in reference:
                lightbox = reference
                photo_id = reference.split('#')[1]
                photo_id = photo_id.replace('-A-LB', '')
            else:
                lightbox = reference + '-A-LB'
                photo_id = reference.split('/')[-1]
            image_url = '%s/photos/%s-M.jpg' % (SMUGMUG, photo_id)

        self.options['uri'] = image_url
        image_node = nodes.image(rawsource=self.block_text,
                                 **self.options)
        reference_node = nodes.reference(refuri=lightbox)
        reference_node += image_node
        return [reference_node]
예제 #15
0
def latexformula_role(name,
                      rawtext,
                      text,
                      lineno,
                      inliner,
                      options={},
                      content=[]):
    if _backend == 'latex':
        options['format'] = 'latex'
        return roles.raw_role(name, rawtext, text, lineno, inliner, options,
                              content)
    else:
        # XXX: make the place of the image directory configurable
        sourcedir = py.path.local(inliner.document.settings._source).dirpath()
        imagedir = sourcedir.join("img")
        if not imagedir.check():
            imagedir.mkdir()
        # create halfway senseful imagename:
        # use hash of formula + alphanumeric characters of it
        # could
        imagename = "%s_%s.png" % (hash(text), "".join(
            [c for c in text if c.isalnum()]))
        image = imagedir.join(imagename)
        latexformula2png(unescape(text, True), image)
        imagenode = nodes.image(image.relto(sourcedir),
                                uri=image.relto(sourcedir))
        return [imagenode], []
예제 #16
0
    def to_image(self, builder):
        if builder.format == 'html':
            reldir = "_images"
            outdir = os.path.join(builder.outdir, '_images')
        else:
            reldir = ""
            outdir = builder.outdir

        hashed = sha1(
            (self['filename'] + self['sheet']).encode('utf-8')).hexdigest()
        filename = "astah-%s.png" % hashed
        path = os.path.join(outdir, filename)
        last_modified = os.stat(self['filename']).st_mtime

        if not os.path.exists(path) or os.stat(path).st_mtime < last_modified:
            ret = self.convert_to(path, builder=builder)
            if ret:
                os.utime(path, (last_modified, last_modified))
            else:
                return nodes.Text('')

        relfn = os.path.join(reldir, filename)
        image_node = nodes.image(candidates={'*': relfn}, **self.attributes)
        image_node['uri'] = relfn

        return image_node
예제 #17
0
    def visit(self, docname, image_node):
        rel_imagedir, abs_imagedir = get_imagedir(self.app, docname)
        basename = self.get_filename_for(image_node)
        if URI_PATTERN.match(image_node['uri']):
            srcpath = image_node['uri']
        else:
            srcpath = os.path.join(self.app.srcdir, image_node['uri'])
        abs_imgpath = os.path.join(abs_imagedir, basename)

        last_modified = self.get_last_modified_for(image_node)
        if last_modified is None:
            ret = False
        elif not os.path.exists(abs_imgpath) or os.stat(abs_imgpath).st_mtime < last_modified:
            ensuredir(os.path.dirname(abs_imgpath))
            ret = self.convert(image_node,
                               os.path.normpath(srcpath),
                               os.path.normpath(abs_imgpath))
        else:
            ret = True

        if ret:
            if last_modified is not None and os.path.exists(abs_imgpath):
                os.utime(abs_imgpath, (last_modified, last_modified))

            rel_imgpath = posixpath.join(rel_imagedir, basename)
            newnode = nodes.image(**image_node.attributes)
            newnode['candidates'] = {'*': rel_imgpath}
            newnode['uri'] = rel_imgpath
            image_node.replace_self(newnode)
        else:
            image_node.parent.remove(image_node)
예제 #18
0
    def run(self):
        env = self.state.document.settings.env
        src_dir = env.srcdir
        uml_dir = os.path.join(src_dir, self.DIR_NAME)

        if os.path.basename(uml_dir) not in os.listdir(src_dir):
            os.mkdir(uml_dir)
        env.uml_dir = uml_dir
        module_path = self.arguments[0]
        os.chdir(uml_dir)
        basename = os.path.basename(module_path).split(".")[0]
        print call([
            'pyreverse', '-o', 'png', '-p', basename,
            os.path.abspath(os.path.join(src_dir, module_path))
        ])
        uri = directives.uri(
            os.path.join(self.DIR_NAME, "classes_{0}.png".format(basename)))
        scale = 100
        max_width = 1000
        if IMAGE:
            i = IMAGE.open(os.path.join(src_dir, uri))
            image_width = i.size[0]
            if image_width > max_width:
                scale = max_width * scale / image_width
        img = nodes.image(uri=uri, scale=scale)
        os.chdir(src_dir)
        return [img]
예제 #19
0
    def apply(self, **kwargs: typing.Any) -> None:
        source = os.path.dirname(self.document["source"])
        for node in self.document.traverse(svgbob):

            if self.builder_supports_svg():
                img = image()
                img["svgbob"] = node
                img["alt"] = node["code"]
                if "align" in node:
                    img["align"] = node["align"]
                if "class" in node:
                    img["class"] = node["class"]

                options = {
                    "font_size": node["options"].get("font-size"),
                    "font_family": node["options"].get("font-family"),
                    "fill_color": node["options"].get("fill-color"),
                    "background_color":
                    node["options"].get("background-color"),
                    "stroke_color": node["options"].get("stroke-color"),
                    "stroke_width": node["options"].get("stroke-width"),
                    "scale": node["options"].get("scale"),
                }

                out = self.render(node, options)
                img["uri"] = os.path.relpath(out, source)
                node.replace_self(img)

            else:
                contents = node["code"].split("\n")
                rawnode = literal_block(node["code"], node["code"])
                node.replace_self(rawnode)
예제 #20
0
    def to_image(self, builder):
        if builder.format == 'html':
            reldir = "_images"
            outdir = os.path.join(builder.outdir, '_images')
        else:
            reldir = ""
            outdir = builder.outdir

        try:
            cacoo = Cacoo(builder.config.cacoo_apikey)
            last_modified = cacoo.get_last_modified(self['diagramid'])

            filename = "cacoo-%s.png" % self['diagramid'].replace('#', '-')
            path = os.path.join(outdir, filename)
            if not os.path.exists(path) or os.stat(path).st_mtime < last_modified:
                ensuredir(outdir)
                with open(path, 'wb') as fd:
                    fd.write(cacoo.get_image(self['diagramid']).read())
                os.utime(path, (last_modified, last_modified))
        except Exception as exc:
            builder.warn('Fail to download cacoo image: %s (check your cacoo_apikey or diagramid)' % exc)
            return nodes.Text('')

        relfn = os.path.join(reldir, filename)
        image_node = nodes.image(candidates={'*': relfn}, **self.attributes)
        image_node['uri'] = relfn

        return image_node
예제 #21
0
def process_graphviz_nodes(app, doctree, docname):
    for node in doctree.traverse(graphviz):
        try:
            content = '\n'.join(node['graphviz_content'])
            filename = '%s' % sha(content).hexdigest()
            outfn = os.path.join(app.builder.outdir, '_images', 'graphviz', filename)
            if not os.path.exists(os.path.dirname(outfn)):
                os.makedirs(os.path.dirname(outfn))
            # iterate over the above-listed types
            for format_mime, format_ext in _output_formats.iteritems():
                graphviz_process = Popen([
                    getattr(app.builder.config, 'graphviz_dot', 'dot'),
                    '-T%s' % (format_ext,),
                    '-o', '%s.%s' % (outfn, format_ext), 
                ], stdin=PIPE)
                graphviz_process.stdin.write(content)
                graphviz_process.stdin.close()
                graphviz_process.wait()
                relfn = '_images/graphviz/%s' % (filename,)
            newnode = nodes.image()
            newnode['candidates'] = dict( [ (format_mime, '%s.%s' % (relfn, format_ext)) for (format_mime, format_ext) in _output_formats.iteritems() ] )

            # and that's all, folks!
            node.replace_self(newnode)
        except Exception, err:
            from traceback import format_exception_only
            msg = ''.join(format_exception_only(err.__class__, err))
            newnode = doctree.reporter.error('Exception occured evaluating '
                                             'graphviz expression: \n%s' %
                                             msg, base_node=node)
            node.replace_self(newnode)
예제 #22
0
파일: images.py 프로젝트: xcore/xdoc
    def run(self):
        if 'align' in self.options:
            if isinstance(self.state, states.SubstitutionDef):
                # Check for align_v_values.
                if self.options['align'] not in self.align_v_values:
                    raise self.error(
                        'Error in "%s" directive: "%s" is not a valid value '
                        'for the "align" option within a substitution '
                        'definition.  Valid values for "align" are: "%s".'
                        % (self.name, self.options['align'],
                           '", "'.join(self.align_v_values)))
            elif self.options['align'] not in self.align_h_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_h_values)))
        messages = []
        reference = directives.uri(self.arguments[0])
        self.options['uri'] = reference
        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']


        image_node = nodes.image(self.block_text, **self.options)

        if 'iconmargin' in self.options:
            image_node['classes'].append('iconmargin')

        set_classes(self.options)

        if 'iconmarginheight' in self.options:
            image_node['iconmarginheight'] = \
               int(self.options['iconmarginheight'])

        if 'iconmarginraise' in self.options:
            image_node['iconmarginraise'] = True


        if reference_node:
            reference_node += image_node
            return messages + [reference_node]
        else:
            return messages + [image_node]
예제 #23
0
    def run(self):
        self.assert_has_content()

        text = "\n".join(self.content)
        parsed = highlight(text, PythonLexer(), HtmlFormatter())

        result = [nodes.raw("", parsed, format="html")]

        options_dict = dict(self.options)
        opt_size = options_dict.get("size", (100, 100))

        fn = options_dict.get("filename") or "{}.png".format(sha(text).hexdigest())

        env = self.state.document.settings.env
        rel_filename, filename = env.relfn2path(fn)

        outfn = os.path.join(env.app.builder.outdir, "_static", rel_filename)
        ensuredir(os.path.dirname(outfn))
        script_to_render = BOT_HEADER.format(size=opt_size) + text
        if os.path.isfile(outfn):
            raise ShoebotError("File %s exists, not overwriting.")
        try:
            cmd = ["sbot", "-o", "%s" % outfn, script_to_render]
            subprocess.call(cmd)
        except Exception as e:
            print("oops %e" % e)
            print("cmd: ")
            print(" ".join(cmd))
            raise ShoebotError(str(e))

        image_node = nodes.image(uri="_static/{}".format(rel_filename), alt="test")
        result.insert(0, image_node)

        return result
예제 #24
0
def latex_visit_plantuml(self, node):
    if 'latex_format' in node:
        fmt = node['latex_format']
    else:
        fmt = self.builder.config.plantuml_latex_output_format
    if fmt == 'none':
        raise nodes.SkipNode
    try:
        try:
            fileformat, postproc = _KNOWN_LATEX_FORMATS[fmt]
        except KeyError:
            raise PlantUmlError(
                'plantuml_latex_output_format must be one of %s, but is %r' %
                (', '.join(map(repr, _KNOWN_LATEX_FORMATS)), fmt))
        refname, outfname = render_plantuml(self, node, fileformat)
        refname, outfname = postproc(self, refname, outfname)
    except PlantUmlError as err:
        self.builder.warn(str(err))
        raise nodes.SkipNode

    # put node representing rendered image
    img_node = nodes.image(uri=refname, **node.attributes)
    img_node.delattr('uml')
    if not img_node.hasattr('alt'):
        img_node['alt'] = node['uml']
    node.append(img_node)
예제 #25
0
    def visit(self, docname, image_node):
        rel_imagedir, abs_imagedir = get_imagedir(self.app, docname)
        basename = self.get_filename_for(image_node)
        if URI_PATTERN.match(image_node['uri']):
            srcpath = image_node['uri']
        else:
            srcpath = os.path.join(self.app.srcdir, image_node['uri'])
        abs_imgpath = os.path.join(abs_imagedir, basename)

        last_modified = self.get_last_modified_for(image_node)
        if last_modified is None:
            ret = False
        elif not os.path.exists(
                abs_imgpath) or os.stat(abs_imgpath).st_mtime < last_modified:
            ensuredir(os.path.dirname(abs_imgpath))
            ret = self.convert(image_node, os.path.normpath(srcpath),
                               os.path.normpath(abs_imgpath))
        else:
            ret = True

        if ret:
            if last_modified is not None and os.path.exists(abs_imgpath):
                os.utime(abs_imgpath, (last_modified, last_modified))

            rel_imgpath = posixpath.join(rel_imagedir, basename)
            newnode = nodes.image(**image_node.attributes)
            newnode['candidates'] = {'*': rel_imgpath}
            newnode['uri'] = rel_imgpath
            image_node.replace_self(newnode)
        else:
            image_node.parent.remove(image_node)
예제 #26
0
    def run(self):
        """Perform task associated with this directive."""
        env = self.state.document.settings.env

        wkf_file = directives.uri(self.arguments[0])
        if not os.path.isabs(wkf_file):
            wkf_file = os.path.join(os.path.dirname(env.doc2path(env.docname)),
                                    wkf_file)

        wkf_name = os.path.splitext(wkf_file)[0]
        svg_file = "%s.svg" % wkf_name
        if out_of_date(wkf_file, svg_file):
            # render the workflow again
            with open(wkf_file, 'r') as f:
                wkf = json.load(f)

            w = self.options.get('width', 600)
            h = self.options.get('height', 600)

            drawing, bb = svg.export_workflow(wkf, {}, (w, h))
            del bb

            with open(svg_file, 'w') as f:
                f.write(drawing)

        self.options['uri'] = svg_file
        node = nodes.image(**self.options)

        return [node]
예제 #27
0
def replace_sphinx_gallery_nodes(builder, doctree):
    """
    replace sphinx-gallery nodes with images

    sphinx-gallery nodes are pre-processed and replaced with respective images
    in the processed documentation set.

    Args:
        builder: the builder
        doctree: the doctree to replace blocks on
    """

    # allow users to disabled third-party implemented extension changes
    restricted = builder.config.confluence_adv_restricted
    if 'ext-sphinx_gallery' in restricted:
        return

    if not sphinx_gallery:
        return

    for node in doctree.traverse(sphinx_gallery_imgsgnode):
        new_node = nodes.image(candidates={'?'}, **node.attributes)
        if 'align' in node:
            new_node['align'] = node['align']
        node.replace_self(new_node)
예제 #28
0
    def node2image(self, node, diagram):
        options = node['options']
        filename = self.image_filename(node)
        fontmap = self.create_fontmap()
        _format = self.global_options['format'].lower()

        if _format == 'svg' and self.global_options['inline_svg'] is True:
            filename = None

        kwargs = dict(self.global_options)
        del kwargs['format']
        drawer = DiagramDraw(_format, diagram, filename,
                             fontmap=fontmap, **kwargs)

        if filename is None or not os.path.isfile(filename):
            drawer.draw()
            content = drawer.save()

            if _format == 'svg' and self.global_options['inline_svg'] is True:
                size = drawer.pagesize()
                if 'maxwidth' in options and options['maxwidth'] < size[0]:
                    ratio = float(options['maxwidth']) / size[0]
                    new_size = (options['maxwidth'], int(size[1] * ratio))
                    content = drawer.save(new_size)

                return nodes.raw('', content, format='html')

        size = drawer.pagesize()
        if 'maxwidth' in options and options['maxwidth'] < size[0]:
            ratio = float(options['maxwidth']) / size[0]
            thumb_size = (options['maxwidth'], int(size[1] * ratio))

            thumb_filename = self.image_filename(node, prefix='_thumb')
            if not os.path.isfile(thumb_filename):
                drawer.filename = thumb_filename
                drawer.draw()
                drawer.save(thumb_size)

            image = nodes.image(uri=thumb_filename, target=filename)
        else:
            image = nodes.image(uri=filename)

        if node['alt']:
            image['alt'] = node['alt']

        return image
예제 #29
0
def smt_link_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
    label = text
    settings = inliner.document.settings
    ref = "%s/%s/%s/" % (settings.sumatra_record_store, settings.sumatra_project, label)
    set_classes(options)
    node = nodes.reference(rawtext, "", refuri=ref, **options)
    node += nodes.image(uri=settings.sumatra_link_icon, alt="smt:" + utils.unescape(text))
    return [node], []
예제 #30
0
def emoji_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    text = text.lower()
    node = nodes.image(
        uri='http://www.tortue.me/emoji/{0}.png'.format(text),
        alt=text,
        classes=['emoji'],
    )
    return [node], []
예제 #31
0
    def run(self):

        path = os.path.abspath(os.path.join('content', 'uml'))

        if not os.path.exists(path):
            os.makedirs(path)

        nodes = []

        body = '\n'.join(self.content)
        tf = tempfile.NamedTemporaryFile(delete=True)
        tf.write(body.encode('utf8'))
        tf.flush()

        imgext = ".png"

        # make a name
        name = tf.name + imgext

        output_path = os.path.join(path, os.path.basename(name))

        alt = self.options.get('alt', 'ditaa diagram')
        classes = self.options.pop('class', ['ditaa'])
        cmdline = ['ditaa', '-v', '-o', tf.name, output_path]

        try:
            p = Popen(cmdline, stdout=PIPE, stderr=PIPE)
            out, err = p.communicate()
        except Exception as exc:
            error = self.state_machine.reporter.error(
                'Failed to run ditaa: %s' % (exc, ),
                literal_block(self.block_text, self.block_text),
                line=self.lineno)
            nodes.append(error)
        else:
            if p.returncode == 0:
                # renaming output image using an hash code, just to not pullate
                # output directory with a growing number of images
                name = os.path.join(path, os.path.basename(name))
                newname = os.path.join(path, "%08x" % (adler32(body.encode('utf8')) & 0xffffffff))+imgext

                try:  # for Windows
                    os.remove(newname)
                except Exception as exc:
                    logger.debug('File '+newname+' does not exist, not deleted')

                os.rename(name, newname)
                url = global_siteurl + '/uml/' + os.path.basename(newname)
                imgnode = image(uri=url, classes=classes, alt=alt)
                nodes.append(imgnode)
            else:
                error = self.state_machine.reporter.error(
                    'Error in "%s" directive: %s' % (self.name, err),
                    literal_block(self.block_text, self.block_text),
                    line=self.lineno)
                nodes.append(error)

        return nodes
예제 #32
0
    def apply(self, **kwargs):
        iter_ = self.startnode.traverse(nodes.paragraph, siblings=1)

        if len(iter_):
            para = iter_[0]
            iter_ = para.traverse(nodes.Text)
            details = self.startnode.details

            if len(iter_):
                textnode = iter_[0]
                charnode = spannode = restnode = None

                char = details['char']
                if not textnode.startswith(char):
                    error("Dropcap: next paragraph doesn't start with: '%s'." %
                          char)
                    return

                span = details.get('span', '')
                if not textnode.startswith(span):
                    error("Dropcap: next paragraph doesn't start with: '%s'." %
                          span)
                    return
                if span and not span.startswith(char):
                    error("Dropcap: span doesn't start with: '%s'." % char)
                    return
                if span == char:
                    span = ''

                if span:
                    # split into char/span/rest
                    restnode = nodes.Text(textnode.astext()[len(span):])
                    spannode = nodes.inline()
                    spannode.append(
                        nodes.Text(textnode.astext()[len(char):len(span)]))
                    spannode['classes'].append('dropspan')
                else:
                    # split into char/rest
                    restnode = nodes.Text(textnode.astext()[len(char):])
                    spannode = nodes.inline('', '')
                    spannode['classes'].append('dropspan')

                if 'image' in details:
                    charnode = nodes.image()
                    charnode['uri'] = details['image']
                    charnode['alt'] = char
                    # debug ("Inserting image %s as dropcap." % uri)
                else:
                    charnode = nodes.inline()
                    charnode.append(nodes.Text(char))
                    # debug ("Inserting char %s as dropcap." % char)

                charnode['classes'].append('dropcap')
                charnode.attributes.update(details)

                para.replace(textnode, [charnode, spannode, restnode])

        self.startnode.parent.remove(self.startnode)
예제 #33
0
def emoji_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    text = text.lower()
    LOGGER.warn('The role :emoji:`{0}` is deprecated. Use |{0}| instead'.format(text))
    node = nodes.image(
        uri='http://www.tortue.me/emoji/{0}.png'.format(text),
        alt=text,
        classes=['emoji'],
    )
    return [node], []
예제 #34
0
def emoji_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    text = text.lower()
    LOGGER.warn('The role :emoji:`{0}` is deprecated. Use |{0}| instead'.format(text))
    node = nodes.image(
        uri='https://cdnjs.cloudflare.com/ajax/libs/emojify.js/1.1.0/images/basic/{0}.png'.format(text),
        alt=text,
        classes=['emoji'],
    )
    return [node], []
예제 #35
0
    def visit_image(self, mdnode):
        img_node = nodes.image()
        img_node['uri'] = mdnode.destination

        if mdnode.title:
            img_node['alt'] = mdnode.title

        self.current_node.append(img_node)
        self.current_node = img_node
    def visit_image(self, mdnode):
        img_node = nodes.image()
        img_node['uri'] = mdnode.destination

        if mdnode.title:
            img_node['alt'] = mdnode.title

        self.current_node.append(img_node)
        self.current_node = img_node
예제 #37
0
def pdf_visit_plantuml(self, node):
    try:
        refname, outfname = render_plantuml(self, node, "eps")
        refname, outfname = _convert_eps_to_pdf(self, refname, outfname)
    except PlantUmlError as err:
        self.builder.warn(str(err))
        raise nodes.SkipNode
    rep = nodes.image(uri=outfname, alt=node.get("alt", node["uml"]))
    node.parent.replace(node, rep)
예제 #38
0
def pdf_visit_plantuml(self, node):
    try:
        refname, outfname = render_plantuml(self, node, 'eps')
        refname, outfname = _convert_eps_to_pdf(self, refname, outfname)
    except PlantUmlError as err:
        self.builder.warn(str(err))
        raise nodes.SkipNode
    rep = nodes.image(uri=outfname, alt=node.get('alt', node['uml']))
    node.parent.replace(node, rep)
예제 #39
0
    def run(self):
        if not os.path.exists(OUTPUT_DIR):
            os.makedirs(OUTPUT_DIR)

        nodes = []

        body = '\n'.join(self.content)
        tf = tempfile.NamedTemporaryFile(delete=False)
        tf.write(body.encode('utf8'))
        tf.flush()

        # make a filename
        filename_template = self.options.pop('filename', '{checksum}.png')
        filename = filename_template.format({
            'checksum':
            hashlib.sha256(body.encode('utf-8')).hexdigest()[0:12],
        })

        alt = self.options.get('alt', 'ditaa diagram')
        classes = self.options.pop('class', ['ditaa'])
        cmdline_opts = self.options.pop('cmdline', '').split(' ')

        cmdline = [
            'ditaa',
            tf.name,
            os.path.join(OUTPUT_DIR, filename),
            '--overwrite',
            '--encoding',
            'utf8',
        ] + cmdline_opts

        try:
            p = subprocess.run(cmdline, capture_output=True)
        except Exception as exc:
            error = self.state_machine.reporter.error(
                'Failed to run ditaa: %s' % (exc, ),
                literal_block(self.block_text, self.block_text),
                line=self.lineno)
            nodes.append(error)
        else:
            if p.returncode == 0:
                url = OUTPUT_URL_PATH + '/' + filename
                imgnode = image(uri=url, classes=classes, alt=alt)
                nodes.append(imgnode)
            else:
                error = self.state_machine.reporter.error(
                    'Error in "%s" directive: %s' % (self.name, p.stderr),
                    literal_block(self.block_text, self.block_text),
                    line=self.lineno)
                nodes.append(error)
        finally:
            os.unlink(tf.name)

        self.state.document.settings.record_dependencies.add(
            "####MAGIC####CONFIG:DITAA_OUTPUT_URL_PATH")
        return nodes
예제 #40
0
def image(node):
    """
    An image element

    The first child is the alt text. reStructuredText can't handle titles
    """
    o = nodes.image(uri=node.destination)
    if node.first_child is not None:
        o['alt'] = node.first_child.literal
    return o
예제 #41
0
def image(block):
    img_node = nodes.image()

    img_node['uri'] = block.destination

    if block.title:
        img_node['title'] = block.title

    img_node['alt'] = text_only(block.label)
    return img_node
예제 #42
0
def test_clean_astext():
    node = nodes.paragraph(text='hello world')
    assert 'hello world' == clean_astext(node)

    node = nodes.image(alt='hello world')
    assert '' == clean_astext(node)

    node = nodes.paragraph(text='hello world')
    node += nodes.raw('', 'raw text', format='html')
    assert 'hello world' == clean_astext(node)
예제 #43
0
def test_clean_astext():
    node = nodes.paragraph(text='hello world')
    assert 'hello world' == clean_astext(node)

    node = nodes.image(alt='hello world')
    assert '' == clean_astext(node)

    node = nodes.paragraph(text='hello world')
    node += nodes.raw('', 'raw text', format='html')
    assert 'hello world' == clean_astext(node)
def create_image_node(block):
    soup = BeautifulSoup(block.c, 'html.parser')
    images = soup.find_all('img')

    for img in images:
        img_node = nodes.image()
        img_node['uri'] = img.attrs.pop('src')
        for attr, value in img.attrs.items():
            img_node[attr] = value
        return img_node
예제 #45
0
def create_image_node(block):
    soup = BeautifulSoup(block.c, "html.parser")
    images = soup.find_all("img")

    for img in images:
        img_node = nodes.image()
        img_node["uri"] = img.attrs.pop("src")
        for attr, value in img.attrs.items():
            img_node[attr] = value
        return img_node
예제 #46
0
def confluence_visit_plantuml(self, node):
    _render_batches_on_vist(self)
    fmt = self.builder.config.plantuml_output_format
    with _prepare_html_render(self, fmt) as (fileformats, _):
        _, outfname = render_plantuml(self, node, fileformats[0])

    # put node representing rendered image
    img_node = nodes.image(uri=outfname, alt=node.get('alt', node['uml']))
    node.replace_self(img_node)
    self.visit_image(img_node)
예제 #47
0
def image(block):
    img_node = nodes.image()

    img_node['uri'] = block.destination

    if block.title:
        img_node['title'] = block.title

    img_node['alt'] = text_only(block.label)
    return img_node
예제 #48
0
def image(node):
    """
    An image element

    The first child is the alt text. reStructuredText can't handle titles
    """
    o = nodes.image(uri=node.destination)
    if node.first_child is not None:
        o['alt'] = node.first_child.literal
    return o
예제 #49
0
def emoji_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
    text = text.lower()
    LOGGER.warn(
        'The role :emoji:`{0}` is deprecated. Use |{0}| instead'.format(text))
    node = nodes.image(
        uri='http://www.tortue.me/emoji/{0}.png'.format(text),
        alt=text,
        classes=['emoji'],
    )
    return [node], []
예제 #50
0
    def apply (self, **kwargs):
        iter_ = self.startnode.traverse (nodes.paragraph, siblings = 1)

        if len (iter_):
            para = iter_[0]
            iter_ = para.traverse (nodes.Text)
            details = self.startnode.details

            if len (iter_):
                textnode = iter_[0]
                charnode = spannode = restnode = None

                char = details['char']
                if not textnode.startswith (char):
                    error ("Dropcap: next paragraph doesn't start with: '%s'." % char)
                    return

                span = details.get ('span', '')
                if not textnode.startswith (span):
                    error ("Dropcap: next paragraph doesn't start with: '%s'." % span)
                    return
                if span and not span.startswith (char):
                    error ("Dropcap: span doesn't start with: '%s'." % char)
                    return
                if span == char:
                    span = ''

                if span:
                    # split into char/span/rest
                    restnode = nodes.Text (textnode.astext ()[len (span):])
                    spannode = nodes.inline ()
                    spannode.append (nodes.Text (textnode.astext ()[len (char):len (span)]))
                    spannode['classes'].append ('dropspan')
                else:
                    # split into char/rest
                    restnode = nodes.Text (textnode.astext ()[len (char):])
                    spannode = nodes.inline ('', '')
                    spannode['classes'].append ('dropspan')
                
                if (not self.document.settings.no_images) and ('image' in details):
                    charnode = nodes.image ()
                    charnode['uri'] = details['image']
                    charnode['alt'] = char
                    # debug ("Inserting image %s as dropcap." % uri)
                else:
                    charnode = nodes.inline ()
                    charnode.append (nodes.Text (char))
                    # debug ("Inserting char %s as dropcap." % char)

                charnode['classes'].append ('dropcap')
                charnode.attributes.update (details)

                para.replace (textnode, [charnode, spannode, restnode])

        self.startnode.parent.remove (self.startnode)
예제 #51
0
    def run(self):
        # remove 'align' processing
        # remove 'target' processing

        self.options.pop('align', None)
        reference = directives.uri(self.arguments[0])
        self.options['uri'] = reference
        set_classes(self.options)
        image_node = nodes.image(self.block_text, **self.options)
        self.add_name(image_node)
        return [image_node]
예제 #52
0
def image(name, arguments, options, content, lineno,
          content_offset, block_text, state, state_machine):
    reference = ''.join(arguments[0].split('\n'))
    if reference.find(' ') != -1:
        error = state_machine.reporter.error(
              'Image URI contains whitespace.',
              nodes.literal_block(block_text, block_text), line=lineno)
        return [error]
    options['uri'] = reference
    image_node = nodes.image(block_text, **options)
    return [image_node]
예제 #53
0
    def run(self):
        img_url = self.arguments[0]
        par_node = nodes.paragraph()
        name = self.options.get('name', os.path.split(self.arguments[0])[1])

        image_container = nodes.container()
        image_node = nodes.image(uri=img_url, alt=name)
        image_container += image_node
        label_node = nodes.emphasis(name, name)
        par_node += [image_container, label_node]

        return [par_node]
예제 #54
0
def latex_math(tex):
    """ Process `tex` and produce image nodes. """
    image_names = latex_snippet_to_png(tex)

    the_nodes = []
    alt = tex
    for pageno, name in enumerate(image_names):

        the_nodes.append(nodes.image(uri=name, alt=alt))
        alt = ''

    return the_nodes
예제 #55
0
def AAFigureDirective(name, arguments, options, content, lineno,
                  content_offset, block_text, state, state_machine):
    text = '\n'.join(content)

    global aafigure_counter

    # ensure that options are present and initialized with defaults if not given
    if 'background' not in options: options['background'] = '#ffffff'
    if 'foreground' not in options: options['foreground'] = '#000000'
    if 'fill' not in options: options['fill'] = options['foreground'] # fill = fore by default
    if 'scale' not in options: options['scale'] = 1
    if 'line_width' not in options: options['line_width'] = 2
    if 'format' not in options: options['format'] = DEFAULT_FORMAT
    if 'aspect' not in options: options['aspect'] = 1
    if 'proportional' not in options: options['proportional'] = False
    if 'name' not in options:
        options['name'] = 'aafigure-%i' % aafigure_counter
        aafigure_counter += 1

    output_name = options['name'] + '.' + options['format'].lower()
    try:
        (visitor, output) = aafigure.render(text, output_name, options)
    except aafigure.UnsupportedFormatError as e:
        result = [state_machine.reporter.error(str(e),
            nodes.literal_block(block_text, block_text),
            line=lineno
        )]
    output.close()

    if options['format'] == 'svg':
        #~ svgout.visit(aaimg, xml_header = False)
        # insert data into html using a raw node
        attributes = {'format': 'html'}
        #~ # result = [nodes.raw('', '<embed src="%s" %s type="image/svg+xml"/>' % (
        result = [nodes.raw('', '<object type="image/svg+xml" data="%s" %s>'
                '</object>' % (output_name, visitor.get_size_attrs()),
                **attributes)]
        #~ result = [nodes.raw('', io.getvalue(), **attributes)]
    elif options['format'] == 'pdf':
        # Return a link.
        wrapper = nodes.generated()
        wrapper.append(nodes.reference('', '%s (PDF)' % options['name'],
            refuri=os.path.basename(output_name)
        ))
        result = [wrapper]
    else:
        # Return an image directive.
        image_options = {}
        image_options['uri'] = os.path.basename(output_name)
        result = [nodes.image(output_name, **image_options)]

    return result