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 with Image2.open('.' + uri) as im: ow, oh = im.size attrs = {'data-orig-width': str(ow), 'data-orig-height': str(oh), 'data-target': uri} (orig_node,) = Image.run(self) html_doc = docutils.utils.new_document("") html_doc.append(orig_node) html_root = parseString(docutils.core.publish_from_doctree(html_doc, writer_name='html').decode()) html_node = html_root.getElementsByTagName("img")[0] for key, val in attrs.items(): html_node.setAttribute(key, val) html_node.setAttribute('class', "{0} simpic".format(html_node.getAttribute('class'))) raw_html = html_node.toxml() node = docutils.nodes.raw('', raw_html, format='html') return [node]
def run(self): """ Image.run() handles most of the """ result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options['uri'] = data_uri(reference)[0] return result
def run(self): """ Image.run() handles most of the """ result = Image.run(self) reference = directives.uri(self.arguments[0]) self.options["uri"] = data_uri_from_file(reference) return result
def run(self): self.assert_has_content() if not 'align' in self.options: self.options['align'] = 'center' tmp = pathname2url(' '.join([(i == '' and '\\\\' or i.strip()) \ for i in self.content])) self.arguments.append('%s%s' % (GOOGLETEX_URL, tmp)) return Image.run(self)
def run(self): """Process a new image.""" #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' % (aref, rewr) self.arguments[0] = rewr #farfle.close() return Image.run(self)
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]
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]
def run(self): """Process a new image.""" 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' % (aref, rewr) self.arguments[0] = rewr return Image.run(self)
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 Image.run(self)
def run(self): if self.arguments: # Read code from file document = self.state.document if self.content: return [document.reporter.warning( __('wavedrom directive cannot have both content and ' 'a filename argument'), line=self.lineno)] argument = search_image_for_language(self.arguments[0], self.env) rel_filename, filename = self.env.relfn2path(argument) self.env.note_dependency(rel_filename) try: with open(filename, 'r') as fp: # type: ignore code = fp.read() except (IOError, OSError): return [document.reporter.warning( __('External wavedrom json file %r not found or reading ' 'it failed') % filename, line=self.lineno)] else: # Read code from given content code = "\n".join(self.content) if not code.strip(): return [self.state_machine.reporter.warning( __('Ignoring "wavedrom" directive without content.'), line=self.lineno)] # For html output with inline JS enabled, just return plain HTML if (self.env.app.builder.name in ('html', 'dirhtml', 'singlehtml') and self.config.wavedrom_html_jsinline): text = WAVEDROM_HTML.format(content=code) content = nodes.raw(text=text, format='html') return [content] # Store code in a special docutils node and pick up at rendering node = wavedromnode() node['code'] = code wd_node = node # point to the actual wavedrom node # A caption option turns this image into a Figure caption = self.options.get('caption') if caption: node = figure_wrapper(self, wd_node, caption) self.add_name(node) # Run image directive processing for the options, supply dummy argument, otherwise will fail. # We don't actually replace this node by the image_node and will also not make it a child, # because intermediate steps, like converters, depend on the file being in sources. We don't # want to generate any files in the user sources. Store the image_node private to this node # and not in the docutils tree and use it later. Revisit this when the situation changes. self.arguments = ["dummy"] (wd_node['image_node'],) = Image.run(self) return [node]
def _make_image_node(self): """Make an image node by safely calling Image.run (i.e. ensure the file exists).""" self.arguments.append(os.path.join("/", SS_DUMP_DIR, self.filename+".png")) screenshot_file = os.path.join(OUTPUT_PATH, self.filename) + ".png" if not os.path.isfile(screenshot_file): # Ensure empty file open(screenshot_file, 'w').close() (image_node,) = Image.run(self) return image_node
def run(self): imagesvg_options = dict([(k,v) for k,v in self.options.items() if k in self.own_option_spec]) (image_node,) = Image.run(self) if isinstance(image_node, nodes.system_message): return [image_node] imagesvg_node = imagesvg(image_node) imagesvg_node['tagtype'] = get_tagtype(imagesvg_options, 'tagtype') return [imagesvg_node]
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 Image.run(self)
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]
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]
def run(self): def raw(text): return docutils.nodes.raw('', text, format='latex') nodes = Image.run(self) img = nodes[0] if not isinstance(img, docutils.nodes.image): return nodes # not an image, WTF? newnodes = [] pattern = img.attributes['uri'] filenames = sorted(glob(pattern)) for i, filename in enumerate(filenames): newimg = copy.deepcopy(img) newimg.attributes['uri'] = filename newnodes += [raw(r'\only<%d>{' % (i + 1)), newimg, raw('}')] return newnodes
def run(self): figwidth = self.options.pop('figwidth', None) figclasses = self.options.pop('figclass', None) align = self.options.pop('align', None) capalign = self.options.pop('capalign', None) (image_node, ) = Image.run(self) if isinstance(image_node, nodes.system_message): return [image_node] figure_node = nodes.figure('', image_node) if figwidth == 'image': if PIL and self.state.document.settings.file_insertion_enabled: imagepath = urllib.url2pathname(image_node['uri']) try: img = PIL.Image.open( imagepath.encode(sys.getfilesystemencoding())) except (IOError, UnicodeEncodeError): pass # TODO: warn? else: self.state.document.settings.record_dependencies.add( imagepath.replace('\\', '/')) figure_node['width'] = img.size[0] del img elif figwidth is not None: figure_node['width'] = figwidth if figclasses: figure_node['classes'] += figclasses if align: figure_node['align'] = align if self.content: node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) first_node = node[0] if isinstance(first_node, nodes.paragraph): caption = nodes.caption(first_node.rawsource, '', *first_node.children) caption['align'] = capalign figure_node += caption elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0): error = self.state_machine.reporter.error( 'Figure caption must be a paragraph or empty comment.', nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [figure_node, error] if len(node) > 1: figure_node += nodes.legend('', *node[1:]) return [figure_node]
def run(self): figwidth = self.options.pop('figwidth', None) figclasses = self.options.pop('figclass', None) align = self.options.pop('align', None) capalign = self.options.pop('capalign', None) (image_node,) = Image.run(self) if isinstance(image_node, nodes.system_message): return [image_node] figure_node = nodes.figure('', image_node) if figwidth == 'image': if PIL and self.state.document.settings.file_insertion_enabled: imagepath = urllib.url2pathname(image_node['uri']) try: img = PIL.Image.open( imagepath.encode(sys.getfilesystemencoding())) except (IOError, UnicodeEncodeError): pass # TODO: warn? else: self.state.document.settings.record_dependencies.add( imagepath.replace('\\', '/')) figure_node['width'] = img.size[0] del img elif figwidth is not None: figure_node['width'] = figwidth if figclasses: figure_node['classes'] += figclasses if align: figure_node['align'] = align if self.content: node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) first_node = node[0] if isinstance(first_node, nodes.paragraph): caption = nodes.caption(first_node.rawsource, '', *first_node.children) caption['align']= capalign figure_node += caption elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0): error = self.state_machine.reporter.error( 'Figure caption must be a paragraph or empty comment.', nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [figure_node, error] if len(node) > 1: figure_node += nodes.legend('', *node[1:]) return [figure_node]
def run(self): self.options['width'] = '95%' label = self.options.get('label', None) (image_node, ) = Image.run(self) if isinstance(image_node, nodes.system_message): return [image_node] figure_node = nodes.figure('', image_node, ids=[label] if label is not None else []) figure_node['align'] = 'center' if self.content: node = nodes.Element() # anonymous container for parsing self.state.nested_parse(self.content, self.content_offset, node) first_node = node[0] if isinstance(first_node, nodes.paragraph): caption_node = nodes.caption(first_node.rawsource, '', *first_node.children) caption_node.source = first_node.source caption_node.line = first_node.line figure_node += caption_node elif not (isinstance(first_node, nodes.comment) and len(first_node) == 0): error = self.state_machine.reporter.error( 'Subfigure caption must be a paragraph or empty comment.', nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [figure_node, error] if len(node) > 1: figure_node += nodes.legend('', *node[1:]) else: rst = ViewList() rst.append(self.options['caption'], "", 0) parsed_node = nodes.section() parsed_node.document = self.state.document nested_parse_with_titles(self.state, rst, parsed_node) node = parsed_node[0] caption_node = nodes.caption(node.rawsource, '', *node.children) caption_node.source = node.source caption_node.line = node.line figure_node += caption_node return [figure_node]
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
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
def run(self): path = self.arguments[0] try: genimg_path = self.arguments[1] or '_build/genimg' except IndexError: genimg_path = '_build/genimg' document = self.state.document basename = os.path.basename(path) node = nodes.image(uri='%s/%s.*' % (genimg_path, basename), figwidth='95%', width='95%', align='center') try: os.makedirs(genimg_path) except FileExistsError: pass comments = prettyplot.sv_prettyplot(path, '%s/%s' % (genimg_path, basename)) parser = docutils.parsers.rst.Parser() try: text = docutils.utils.new_document("", settings=document.settings) parser.parse("\n\n".join(comments[0]), text) paragraphs = [] for p in text: paragraphs.append(p) except IndexError: pass self.arguments = ["dummy"] (node['image_node'], ) = Image.run(self) if text is not None: return [node, *paragraphs] else: return [ node, ]
def run(self): """ Returns list of nodes to appended as screenshot. Language xx can be set in conf.py or by: make SPHINXOPTS="-D language=xx" html Build language can be accessed from the BuildEnvironment. """ # sphinx.environment.BuildEnvironment env = self.state.document.settings.env language = env.config.language return_nodes = [] if len(self.arguments) == 1: (image_node,) = Image.run(self) return_nodes.append(image_node) return_nodes.append(nodes.Text("Language code is '%s'. " % language)) if 'focus' in self.options: return_nodes.append(nodes.Text("DOM id is '%s' and annotation is '%s'. " % (self.options['focus']['id'], self.options['focus']['annotation']))) if 'user-role' in self.options: # Assign something to an instance variable so it can be used in other methods... pass else: # ...and have a default user pass if 'url' in self.options: # Assign something to an instance variable so it can be used in other methods pass if 'url' in self.options and 'navigation-steps' in self.options: runhandler = self.options['navigation-steps']['runhandler'] args = self.options['navigation-steps']['args'] return_nodes.append(getattr(self, runhandler)(**args)) return return_nodes
def run(self): fname= "uml/%06d" % self.lineno #A: default if (len(self.arguments)>0): fname= self.arguments[0] #A: path contains the path for the txt and image without extension (fnameOutDir, fnameBase)= os.path.split(fname) txtFname= fname+".txt" imgFname= fname+".png" if self.content: os.path.isdir(fnameOutDir) or os.mkdir(fnameOutDir) #A: fnameOutDir exists, BUT only ONE level will be created fo= open(txtFname,"wb") fo.write("@startuml\n") try: fo.write(self.state_machine.document.settings.plantuml_hdr+"\n") except AttributeError: pass fo.write('\n'.join(self.content)) fo.write("\n@enduml\n") fo.close() #A: txt file OVERWRITEN! if (not self.state.document.settings.file_insertion_enabled): warning = self.state_machine.reporter.warning( 'File and URL access deactivated; ignoring "%s" ' 'directive.' % self.name, nodes.literal_block( self.block_text, self.block_text), line=self.lineno) return [warning] plantumlCmd= "plantuml %s" try: plantumlCmd= self.state_machine.document.settings.plantuml_cmd except AttributeError: pass os.system(plantumlCmd % txtFname) self.arguments= [imgFname] return Image.run(self)
def _login_handler(self, username, password, submit): from_str_arg = { "users": ["guest"], "slug": "", "start_url": "/securesync/login", "inputs": [{"#id_username":username}, {"#id_password":password}, ], "pages": [], "notes": [], } if submit: from_str_arg["inputs"].append({"<submit>":""}) filename = uuid.uuid4().__str__() from_str_arg["inputs"].append({"<slug>":filename}) # This assignment is necessary because of the format the screenshots management command expects from_str_arg = [from_str_arg] output_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)),"_build","html","_images")) # Trying to import django.core.management.call_command gets you into some sort of import hell # Apparently due to a circular import, according to Ben Bach. cmd_str = SCREENSHOT_COMMAND + " --no-del -v 0 --from-str '%s' --output-dir %s" % (json.dumps(from_str_arg), output_path) os.system(cmd_str) self.arguments.append(os.path.join("_images", filename+".png")) (image_node,) = Image.run(self) return image_node
def _make_image_node(self): """Make an image node by safely calling Image.run (i.e. ensure the file exists).""" self.arguments.append(os.path.join("/", SS_DUMP_DIR, self.filename+".png")) open(os.path.join(OUTPUT_PATH, self.filename+".png"), 'w').close() (image_node,) = Image.run(self) return image_node
def run(self): # Check if file insertion is enabled if not self.state.document.settings.file_insertion_enabled: msg = ( 'File and URL access deactivated. ' 'Ignoring directive "{}".'.format(self.name) ) warning = nodes.warning( '', self.state_machine.reporter.warning( '', nodes.literal_block('', msg), line=self.lineno ) ) return [warning] # Define plantuml file name if len(self.arguments) > 0: fname = self.arguments[0] else: fname = '{:06d}'.format(self.lineno) fname = join(self.uml_out_dir, fname) # Create images output folder mkpath(abspath(dirname(fname))) # Write plantuml content uml_file = fname + '.uml' if self.content: with open(uml_file, 'wb') as fd: fd.write('@startuml\n') try: fd.write( self.state_machine.document.settings.plantuml_hdr ) fd.write('\n') except AttributeError: pass fd.write('\n'.join(self.content)) fd.write('\n@enduml\n') # Execute plantuml call # Commented because plantuml doesn't have and output flag # image_file = fname + self.uml_out_ext plantuml_cmd = 'plantuml' try: plantuml_cmd = self.state_machine.document.settings.plantuml_cmd except AttributeError: pass try: code = call(shsplit( '{} {} "{}"'.format(plantuml_cmd, self.uml_cmd_args, uml_file) )) if code != 0: raise Exception('plantuml call returned {}.'.format(code)) except: msg = format_exc() error = nodes.error( '', self.state_machine.reporter.error( '', nodes.literal_block('', msg), line=self.lineno ) ) return [error] # Default to align center if not 'align' in self.options: self.options['align'] = 'center' # Run Image directive self.arguments = [fname + self.uml_emb_ext] return Image.run(self)
def run(self): old_image_node = nodes.image nodes.image = video node = Image.run(self) nodes.image = old_image_node return node
def run(self): uri = directives.uri(self.arguments[0]) if uri.split('.')[-1] in ['ogg', 'mpg', 'mp4', 'avi', 'mpeg']: return Video.run(self) else: return Image.run(self)
def run(self): self.options['figwidth'] = 'image' self.content = [] # Create an image filename from arguments return Image.run(self)
def run(self): if self.content: error = self.state_machine.reporter.error( """The SQLAlchemyViz directive does not know what to do with provided content""", nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [error] env = self.state.document.settings.env # sphinx.environment.BuildEnvironment config = env.config # sphinx.config.Config output_folder = os.path.abspath( os.path.join(env.srcdir, config["html_static_path"][0])) # Get the path to the object containing the metadata metadatapath = self.options.get('metadataobject', None) if metadatapath is None: error = self.state_machine.reporter.error( "SQLAlchemyViz needs to be given the object" "containing the SQLAlchemy metadata as the :metadataobject: " "parameter", nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [error] output_path = os.path.join(output_folder, metadatapath + '.png') metadata = ':'.join(metadatapath.rsplit('.', 1)) sqlaviz_cmd = [ 'sqlaviz', '-p neato', # workaround newtrap bug. '--unique-relations', #'--show-constraints', # workaround neato bug(?) metadata, '-f out.dot' ] devnull = open(os.devnull) sqlaviz_sp = subprocess.Popen(sqlaviz_cmd, stdout=devnull, stderr=devnull) sqlaviz_sp.communicate() render_cmd = 'ccomps -x out.dot | dot | gvpack -array3 ' \ '| neato -Tpng -n2 -o out.png' render_sp = subprocess.Popen(render_cmd, stdout=devnull, stderr=devnull, shell=True) render_sp.communicate() devnull.close() try: shutil.move('out.png', output_path) os.remove('out.dot') relpath = os.path.relpath(output_path, env.srcdir) # I'm exhausted. self.arguments.insert(0, '/' + relpath) except IOError: error = self.state_machine.reporter.error( "sqlaviz was unable to generate the output image!", nodes.literal_block(self.block_text, self.block_text), line=self.lineno) return [error] return Image.run(self)
def run(self): if self.content: error = self.state_machine.reporter.error( """The SQLAlchemyViz directive does not know what to do with provided content""", nodes.literal_block(self.block_text, self.block_text), line=self.lineno ) return [error] env = self.state.document.settings.env # sphinx.environment.BuildEnvironment config = env.config # sphinx.config.Config output_folder = os.path.abspath( os.path.join(env.srcdir, config["html_static_path"][0]) ) # Get the path to the object containing the metadata metadatapath = self.options.get('metadataobject', None) if metadatapath is None: error = self.state_machine.reporter.error( "SQLAlchemyViz needs to be given the object" "containing the SQLAlchemy metadata as the :metadataobject: " "parameter", nodes.literal_block(self.block_text, self.block_text), line=self.lineno ) return [error] output_path = os.path.join(output_folder, metadatapath + '.png') metadata = ':'.join(metadatapath.rsplit('.', 1)) sqlaviz_cmd = ['sqlaviz', '-p neato', # workaround newtrap bug. '--unique-relations', #'--show-constraints', # workaround neato bug(?) metadata, '-f out.dot'] devnull = open(os.devnull) sqlaviz_sp = subprocess.Popen(' '.join(sqlaviz_cmd), stdout=devnull, stderr=devnull, shell=True) sqlaviz_sp.communicate() render_cmd = 'ccomps -x out.dot | dot | gvpack -array3 ' \ '| neato -Tpng -n2 -o out.png' render_sp = subprocess.Popen(render_cmd, stdout=devnull, stderr=devnull, shell=True) render_sp.communicate() devnull.close() try: shutil.move('out.png', output_path) os.remove('out.dot') relpath = os.path.relpath(output_path, env.srcdir) # I'm exhausted. self.arguments.insert(0, '/' + relpath) except IOError: raise error = self.state_machine.reporter.error( "sqlaviz was unable to generate the output image!", nodes.literal_block(self.block_text, self.block_text), line=self.lineno ) return [error] return Image.run(self)
def run(self): # Execute sanity checks warnings = self._directive_checks() if warnings: return warnings # Fetch builder and environment objects env = self.state_machine.document.settings.env builder = env.app.builder # Determine document directory document_dir = realpath(dirname(env.doc2path(env.docname))) # Load content to render if not self.arguments: content = '\n'.join(self.content) else: # Source file should be relative to document, or absolute to # configuration directory. srcfile = self.arguments[0] if isabs(srcfile): srcpath = join(env.app.confdir, relpath(srcfile, start='/')) else: srcpath = join(document_dir, srcfile) if not isfile(srcpath): warning = self.state_machine.reporter.warning( '{} directive cannot find file {}'.format( self._get_directive_name(), srcfile), line=self.lineno) return [warning] with open(srcpath, 'rb') as fd: content = fd.read().decode('utf-8') # Execute plantweb call try: output, frmt, engine, sha = render(content, engine=self._get_engine_name()) except Exception: msg = format_exc() error = nodes.error( '', self.state_machine.reporter.error('', nodes.literal_block('', msg), line=self.lineno)) return [error] # Determine filename filename = '{}.{}'.format(sha, frmt) imgpath = join(builder.outdir, builder.imagedir, 'plantweb') # Create images output folder log.debug('imgpath set to {}'.format(imgpath)) mkpath(imgpath) # Write content filepath = join(imgpath, filename) with open(filepath, 'wb') as fd: fd.write(output) log.debug('Wrote image file {}'.format(filepath)) # Default to align center if 'align' not in self.options: self.options['align'] = 'center' # Determine relative path to image from source document directory filepath_relative = relpath(filepath, document_dir) # Windows compatibility: # Sphinx Image directive expects paths in POSIX, Python's form. # Replace backslash with slash, otherwise they are removed. filepath_relative = filepath_relative.replace('\\', '/') log.debug('Image relative path {}'.format(filepath_relative)) # Run Image directive self.arguments = [filepath_relative] return Image.run(self)
def run(self): if self.arguments: # Read code from file document = self.state.document if self.content: return [ document.reporter.warning(__( 'wavedrom directive cannot have both content and ' 'a filename argument'), line=self.lineno) ] argument = search_image_for_language(self.arguments[0], self.env) rel_filename, filename = self.env.relfn2path(argument) self.env.note_dependency(rel_filename) try: with open(filename, 'r') as fp: # type: ignore code = fp.read() except (IOError, OSError): return [ document.reporter.warning(__( 'External wavedrom json file %r not found or reading ' 'it failed') % filename, line=self.lineno) ] else: # Read code from given content code = "\n".join(self.content) if not code.strip(): return [ self.state_machine.reporter.warning( __('Ignoring "wavedrom" directive without content.'), line=self.lineno) ] # For html output with inline JS enabled, just return plain HTML if (self.env.app.builder.name in ('html', 'dirhtml', 'singlehtml') and self.config.wavedrom_html_jsinline): text = WAVEDROM_HTML.format(content=code) content = nodes.raw(text=text, format='html') return [content] # Store code in a special docutils node and pick up at rendering node = wavedromnode() node['code'] = code wd_node = node # point to the actual wavedrom node # A caption option turns this image into a Figure caption = self.options.get('caption') if caption: node = figure_wrapper(self, wd_node, caption) self.add_name(node) # Run image directive processing for the options, supply dummy argument, otherwise will fail. # We don't actually replace this node by the image_node and will also not make it a child, # because intermediate steps, like converters, depend on the file being in sources. We don't # want to generate any files in the user sources. Store the image_node private to this node # and not in the docutils tree and use it later. Revisit this when the situation changes. self.arguments = ["dummy"] (wd_node['image_node'], ) = Image.run(self) return [node]
def run(self): # Execute sanity checks warnings = self._directive_checks() if warnings: return warnings # Fetch builder and environment objects env = self.state_machine.document.settings.env builder = env.app.builder # Determine document directory document_dir = dirname(env.doc2path(env.docname)) # Load content to render if not self.arguments: content = '\n'.join(self.content) else: # Source file should be relative to document, or absolute to # configuration directory. srcfile = self.arguments[0] if isabs(srcfile): srcpath = join(env.app.confdir, relpath(srcfile, start='/')) else: srcpath = join(document_dir, srcfile) if not isfile(srcpath): warning = self.state_machine.reporter.warning( '{} directive cannot find file {}'.format( self._get_directive_name(), srcfile ), line=self.lineno ) return [warning] with open(srcpath, 'rb') as fd: content = fd.read().decode('utf-8') # Execute plantweb call try: output, frmt, engine, sha = render( content, engine=self._get_engine_name() ) except Exception: msg = format_exc() error = nodes.error( '', self.state_machine.reporter.error( '', nodes.literal_block('', msg), line=self.lineno ) ) return [error] # Determine filename filename = '{}.{}'.format(sha, frmt) imgpath = join(builder.outdir, builder.imagedir, 'plantweb') # Create images output folder log.debug('imgpath set to {}'.format(imgpath)) mkpath(imgpath) # Write content filepath = join(imgpath, filename) with open(filepath, 'wb') as fd: fd.write(output) log.debug('Wrote image file {}'.format(filepath)) # Default to align center if 'align' not in self.options: self.options['align'] = 'center' # Determine relative path to image from source document directory filepath_relative = relpath(filepath, document_dir) log.debug('Image relative path {}'.format(filepath_relative)) # Run Image directive self.arguments = [filepath_relative] return Image.run(self)