def run(self):
        env = self.state.document.settings.env
        definitions = env.numbered_blocks_definitions

        (figure,) = Figure.run(self)
        if isinstance(figure, nodes.system_message):
            return [figure]

        id = "%s-%d" % (self.name, env.new_serialno(self.name))
        figure['ids'] = [id]
        figure['classes'].append('numbered-block')
        figure['type'] = self.name
        numbered = definitions[self.name]['numbered'] and 'nonumber' not in self.options
        figure['numbered'] = numbered

        # Move name from image to figure and register as target
        image = figure.children[figure.first_child_matching_class(nodes.image)]
        if len(image['names']) > 0:
            name = image['names'][0]
            figure['names'] = [name]
            if name in self.state.document.nameids:
                del(self.state.document.nameids[name])
            self.state.document.note_explicit_target(figure)

        # Prepare caption
        caption_pos = figure.first_child_matching_class(nodes.caption)
        if numbered:
            if not caption_pos:
                figure.append(nodes.caption('', ''))
            else:
                caption = figure.children[caption_pos]
                caption.insert(0, nodes.inline('', definitions[self.name]['title-separator'], classes=['separator']))

        return [figure]
示例#2
0
 def run(self):
     placement = self.state.document.settings.jqfigure_placement
     if self.options.has_key('placement'):
         placement = self.options['placement']
     (figure_node,) = Figure.run(self)
     jqfigure_node = jqfigure('',figure_node)
     jqfigure_node['placement'] = placement
     return [jqfigure_node]
示例#3
0
  def run(self):
    """Process a new figure."""
    #farfle = open('/tmp/farfle', 'a')
    env = self.state.document.settings.env
    reference = directives.uri(self.arguments[0])
    if not os.path.isabs(reference):
      # A relative path means we should search for the image
      # Find the builder-specific path-list to search:
      bname = env.app.builder.name
      if bname in sphinx.builders.BUILTIN_BUILDERS:
        bname = sphinx.builders.BUILTIN_BUILDERS[bname][0] # Get a simplified name (htmlhelp->html, etc)

      if bname in env.app.config.findfigure_paths:
        searchdirs = env.app.config.findfigure_paths[bname]
      elif '*' in env.app.config.findfigure_paths:
        searchdirs = env.app.config.findfigure_paths['*']
      else:
        searchdirs = (os.path.abspath('.'),)
      if reference.endswith('.*'):
        # Find the builder-specific list of extensions to try
        base, dummy = os.path.splitext(reference)
        if bname in env.app.config.findfigure_types:
          searchexts = env.app.config.findfigure_types[bname]
        elif '*' in env.app.config.findfigure_types:
          searchexts = env.app.config.findfigure_types['*']
        else:
          searchexts = ('.svg', '.pdf', '.png', '.jpeg', '.jpg', '.tiff', '.tif', '.gif')
      else:
        base = reference
        searchexts = ('',)
      # Now try finding the figure.
      foundit = False
      aref = base
      for ext in searchexts:
        for path in searchdirs:
          try:
            aref = os.path.join(path, base) + ext
            #print '  TRY <%s>' % aref
            status = os.stat(aref) # Could check status bits here.
            foundit = True
            break
          except:
            foundit = False
        if foundit:
          break
      #print >>farfle, "Reference is %s aref %s found %s" % (self.arguments, aref, foundit)
      if not foundit:
        #print 'MISSING FILE %s' % reference
        return []
      #print 'RESOLVED %s to %s' % (reference, aref)
      rewr = os.path.relpath(aref, os.path.join(env.srcdir, os.path.dirname(env.docname)))
      # NB: We must rewrite path relative to source directory
      #     because otherwise the output stage will be unable
      #     to find it.
      #print 'REWROTE %s to %s rel %s' % (aref, rewr, os.path.abspath(os.path.dirname(env.docname)))
      self.arguments[0] = rewr
    #farfle.close()
    return Figure.run(self)
示例#4
0
 def run(self):
     uri = directives.uri(self.arguments[0])
     self.options['target'] = uri
     self.arguments[0] = '.thumbnail'.join(os.path.splitext(uri))
     if self.content:
         (node,) = Figure.run(self)
     else:
         (node,) = Image.run(self)
     return [node]
示例#5
0
 def run(self):
     uri = directives.uri(self.arguments[0])
     self.options['target'] = uri
     self.arguments[0] = '.thumbnail'.join(os.path.splitext(uri))
     if self.content:
         (node,) = Figure.run(self)
     else:
         (node,) = Image.run(self)
     return [node]
示例#6
0
    def run(self):
        """Process a new figure."""
        env = self.state.document.settings.env
        reference = directives.uri(self.arguments[0])
        if not os.path.isabs(reference):
            # A relative path means we should search for the image
            # Find the builder-specific path-list to search:
            bname = rememberedApp.builder.format if rememberedApp != None else env.app.builder.name

            if bname in env.app.config.findfigure_paths:
                searchdirs = env.app.config.findfigure_paths[bname]
            elif '*' in env.app.config.findfigure_paths:
                searchdirs = env.app.config.findfigure_paths['*']
            else:
                searchdirs = (os.path.abspath('.'), )
            if reference.endswith('.*'):
                # Find the builder-specific list of extensions to try
                base, dummy = os.path.splitext(reference)
                if bname in env.app.config.findfigure_types:
                    searchexts = env.app.config.findfigure_types[bname]
                elif '*' in env.app.config.findfigure_types:
                    searchexts = env.app.config.findfigure_types['*']
                else:
                    searchexts = ('.svg', '.pdf', '.png', '.jpeg', '.jpg',
                                  '.tiff', '.tif', '.gif')
            else:
                base = reference
                searchexts = ('', )
            # Now try finding the figure.
            foundit = False
            aref = base
            for ext in searchexts:
                for path in searchdirs:
                    try:
                        aref = os.path.join(path, base) + ext
                        # print '  TRY <%s>' % aref
                        status = os.stat(aref)  # Could check status bits here.
                        foundit = True
                        break
                    except:
                        foundit = False
                if foundit:
                    break
            if not foundit:
                # print 'MISSING FILE %s' % reference
                return []
            # print 'RESOLVED %s to %s' % (reference, aref)
            rewr = os.path.relpath(
                aref, os.path.join(env.srcdir, os.path.dirname(env.docname)))
            # NB: We must rewrite path relative to source directory
            #     because otherwise the output stage will be unable
            #     to find it.
            # print 'REWROTE %s to %s rel %s' % (aref, rewr,
            # os.path.abspath(os.path.dirname(env.docname)))
            self.arguments[0] = rewr
        return Figure.run(self)
示例#7
0
 def run(self):
     """Run the thumbnail directive."""
     uri = directives.uri(self.arguments[0])
     self.options["target"] = uri
     self.arguments[0] = ".thumbnail".join(os.path.splitext(uri))
     if self.content:
         (node,) = Figure.run(self)
     else:
         (node,) = Image.run(self)
     return [node]
示例#8
0
 def run(self):
     my_file = directives.uri(self.arguments[0])
     full_path = posixpath.join(current_app.config['ATTACHMENT_DIR'],
                                my_file)
     if full_path not in current_app.blohg.changectx.files:
         raise self.error('Error in "%s" directive: File not found: %s.' %
                          (self.name, full_path))
     self.arguments[0] = url_for('attachments',
                                 filename=my_file,
                                 _external=True)
     return Figure.run(self)
示例#9
0
 def run(self):
     my_file = directives.uri(self.arguments[0])
     full_path = posixpath.join(current_app.config['ATTACHMENT_DIR'],
                                my_file)
     if full_path not in current_app.blohg.changectx.files:
         raise self.error(
             'Error in "%s" directive: File not found: %s.' % (
                 self.name, full_path
             )
         )
     self.arguments[0] = url_for('attachments', filename=my_file,
                                 _external=True)
     return Figure.run(self)
示例#10
0
    def run(self):
        libreoffice_options = dict([(k,v) for k,v in self.options.items() 
                                       if k in self.own_option_spec])

        (figure_node,) = Figure.run(self)

        if isinstance(figure_node, nodes.system_message):
            return [figure_node]

        figure_node.libreoffice = dict(drawing=self.arguments[0],
                                       options=libreoffice_options)
        
        return [figure_node]
示例#11
0
    def run(self):
        libreoffice_options = dict([(k, v) for k, v in self.options.items()
                                    if k in self.own_option_spec])

        (figure_node, ) = Figure.run(self)

        if isinstance(figure_node, nodes.system_message):
            return [figure_node]

        figure_node.libreoffice = dict(drawing=self.arguments[0],
                                       options=libreoffice_options)

        return [figure_node]
示例#12
0
 def run(self):
     """Run the thumbnail directive."""
     uri = directives.uri(self.arguments[0])
     if uri.endswith('.svg'):
         # the ? at the end makes docutil output an <img> instead of an object for the svg, which lightboxes may require
         self.arguments[0] = '.thumbnail'.join(os.path.splitext(uri)) + '?'
     else:
         self.arguments[0] = '.thumbnail'.join(os.path.splitext(uri))
     self.options['target'] = uri
     if self.content:
         (node, ) = Figure.run(self)
     else:
         (node, ) = Image.run(self)
     return [node]
示例#13
0
 def run(self):
     """Run the thumbnail directive."""
     uri = directives.uri(self.arguments[0])
     if uri.endswith('.svg'):
         # the ? at the end makes docutil output an <img> instead of an object for the svg, which colorbox requires
         self.arguments[0] = '.thumbnail'.join(os.path.splitext(uri)) + '?'
     else:
         self.arguments[0] = '.thumbnail'.join(os.path.splitext(uri))
     self.options['target'] = uri
     if self.content:
         (node,) = Figure.run(self)
     else:
         (node,) = Image.run(self)
     return [node]
示例#14
0
    def run_figure_or_image_with_uri(self, uri, visual_node, caption_node,
                                     legend_node):
        """
        use Figure.run() or Image.run() to fill out these attributes:
            general image attributes: alt, height, width,
            scale (scale for the image - this may require additional processing),
            align (horizontal and vertical alignment),
            name (an [html] name for the node),
            target (node or URI that this image should link to),
            class (any additional [html] classes),
            figwidth (figure specific width),
            figclass (figure specific class)

        Note: If figwidth=='image', PIL will try to open the image.
            PIL will only open the image if it's local, and can be found.

        :param string uri:
        :param visual visual_node: The node to work with.
        :param nodes.caption caption_node:
        :param nodes.legend legend_node:
        """
        # Figure/Image expect the URI to be an argument,
        # then they move it to self.options['uri']
        argument0_backup = self.arguments[0]
        self.arguments[0] = uri

        # Figure/Image will choke on Visual content
        content_backup = self.content
        self.content = StringList()

        if visual_node['is_figure']:
            # The zeroth element is the figure_node
            figure_node = Figure.run(self)[0]
            for node in (caption_node, legend_node):
                if node is not None:
                    figure_node += node
            visual_node += figure_node
        else:
            (image_node, ) = Image.run(self)
            visual_node += image_node

        # Restore the content/arg now that Figure/Image are done processing.
        #   Is this needed?
        self.content = content_backup
        self.arguments[0] = argument0_backup
示例#15
0
    def run(self):
        #if not dotcode.strip():
        #    return [self.state_machine.reporter.warning(
        #        'Ignoring "uml_diagram" directive without content.',
        #        line=self.lineno)]
        data = Figure.run(self)
        img = data[0][0]

        uri = img['uri']
        fin = uri + '.pml'
        fname = os.path.basename(uri) + '.svg'
        _, tdir = self.app.env.relfn2path('')
        fout = os.path.join(tdir, fname)
        
        with open(fin) as f:
            generate(f, fout, 'svg')
            img['uri'] = fname
        return data
示例#16
0
    def run_figure_or_image_with_uri(self, uri, visual_node, caption_node, legend_node):
        """
        use Figure.run() or Image.run() to fill out these attributes:
            general image attributes: alt, height, width,
            scale (scale for the image - this may require additional processing),
            align (horizontal and vertical alignment),
            name (an [html] name for the node),
            target (node or URI that this image should link to),
            class (any additional [html] classes),
            figwidth (figure specific width),
            figclass (figure specific class)

        Note: If figwidth=='image', PIL will try to open the image.
            PIL will only open the image if it's local, and can be found.

        :param string uri:
        :param visual visual_node: The node to work with.
        :param nodes.caption caption_node:
        :param nodes.legend legend_node:
        """
        # Figure/Image expect the URI to be an argument,
        # then they move it to self.options['uri']
        argument0_backup = self.arguments[0]
        self.arguments[0] = uri

        # Figure/Image will choke on Visual content
        content_backup = self.content
        self.content = StringList()

        if visual_node['is_figure']:
            # The zeroth element is the figure_node
            figure_node = Figure.run(self)[0]
            for node in (caption_node, legend_node):
                if node is not None:
                    figure_node += node
            visual_node += figure_node
        else:
            (image_node,) = Image.run(self)
            visual_node += image_node

        # Restore the content/arg now that Figure/Image are done processing.
        #   Is this needed?
        self.content = content_backup
        self.arguments[0] = argument0_backup
示例#17
0
    def run(self):
        # First, let the CSVTable constructor handle all kind of parsing, including errors
        # (e.g., when we disabled the feature to load from file in sphinx, if a :file: has been
        # provided)

        # remove the title, if any: the title is actually the caption of the wrapping figure
        # Need to set to the empty list (See tables.Table directive)
        caption_text = self.arguments[0]
        self.arguments = []

        # parse using superclass
        csvtable_nodes = CSVTable.run(self)  # run super CSV Table to catch potential errors
        # the first node is the table node, then potential messages (see superclass)
        csvtable_node = csvtable_nodes[0]
        csv_messages = csvtable_nodes[1:]

        # Now execute the figure directive
        self.content = None  # the content will be translated as caption. Problem is, if we do not
        # have content we should add the caption anyways. So let's do it manually
        # need to restore the arguments list to a parsable Figure element. Its value is useless,
        # just set it to avoid trhowing errors (see images.Figure directive)
        self.arguments = ['']
        fig_nodes = Figure.run(self)
        # set the caption "manually":
        fig_node = fig_nodes[0]
        fig_messages = fig_nodes[1:]
        caption = None
        if self.arguments and caption_text:
            txt = Text(touni(caption_text))  # Text nodes want unicode
            caption = nodes.caption(caption_text, '', *[txt])
            caption.parent = fig_node  # sphinx complains if we do not set it ...

        fig_node.children = [csvtable_node]
        csvtable_node.parent = fig_node  # set the parent, as in general is good
        # (e.g. it might be used to allow remove the item from its parent)
        if caption:
            fig_node.children.append(caption)

        return [fig_node] + csv_messages + fig_messages
示例#18
0
    def run(self):

        #         print('Here!')
        #         print(self.arguments)

        try:
            filename = directives.uri(self.arguments[0])
        except:
            filename = None
            text = '\n'.join(self.content)
            try:
                self.content[0] = self.options['caption']

                while len(self.content) > 1:
                    self.content.trim_end(len(self.content) - 1)
            except:
                self.content = None

        self.arguments = ['']

        (figure_node, ) = Figure.run(self)
        if isinstance(figure_node, nodes.system_message):
            return [figure_node]

        if filename:

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

            figure_node.bdpfile = filename

        else:
            figure_node.bdpcontent = text


#             print(filename)
#             print(rel_filename)
#
# #             env = app.env
# #             docdir = os.path.dirname(env.doc2path(env.docname, base=None))
# #
# #             if filename.startswith('/'):
# #                 filename = os.path.normpath(filename[1:])
# #             else:
# #                 filename = os.path.normpath(os.path.join(docdir, filename))
# #
# #             env.note_dependency(filename)
# #             filename = os.path.join(env.srcdir, filename)
# #             except:
# #                 continue
#
#
#         self.arguments = ['']
#         text = '\n'.join(self.content)
#
#         try:
#             self.content[0] = self.options['caption']
#
#             while len(self.content) > 1:
#                 self.content.trim_end(len(self.content) - 1)
#         except:
#             self.content = None
#
#         (figure_node,) = Figure.run(self)
#         if isinstance(figure_node, nodes.system_message):
#             return [figure_node]
#
#         figure_node.bdpcontent = text
#         figure_node.bdpfile = text
        return [figure_node]