def on_builder_inited(self): # show deprecated message if self.builder.config.rackdiag_tex_image_format: self.builder.warn( 'rackdiag_tex_image_format is deprecated. Use rackdiag_latex_image_format.' ) # initialize fontmap global fontmap try: fontmappath = self.builder.config.rackdiag_fontmap fontmap = FontMap(fontmappath) except: fontmap = FontMap(None) try: fontpath = self.builder.config.rackdiag_fontpath if isinstance(fontpath, string_types): fontpath = [fontpath] if fontpath: config = namedtuple('Config', 'font')(fontpath) fontpath = detectfont(config) fontmap.set_default_font(fontpath) except: pass
def renderToFile(self, content, imagePath): """ content - текст, описывающий диаграмму imagePath - полный путь до создаваемого файла """ from blockdiag.parser import parse_string from blockdiag.drawer import DiagramDraw from blockdiag.builder import ScreenNodeBuilder from blockdiag.utils.fontmap import FontMap font = os.path.join(os.path.dirname(os.path.abspath(__file__)), u"fonts", self._fontDefault) fontmap = FontMap() fontmap.set_default_font(font) text = u"blockdiag {{ {content} }}".format(content=content) tree = parse_string(text) diagram = ScreenNodeBuilder.build(tree) draw = DiagramDraw("png", diagram, imagePath, fontmap=fontmap, antialias=True) draw.draw() draw.save()
def create_fontmap(options): fontmap = FontMap(options.fontmap) if fontmap.find().path is None or options.font: fontpath = detectfont(options) fontmap.set_default_font(fontpath) return fontmap
def on_builder_inited(self): # show deprecated message if self.builder.config.rackdiag_tex_image_format: self.builder.warn('rackdiag_tex_image_format is deprecated. Use rackdiag_latex_image_format.') # initialize fontmap global fontmap try: fontmappath = self.builder.config.rackdiag_fontmap fontmap = FontMap(fontmappath) except: fontmap = FontMap(None) try: fontpath = self.builder.config.rackdiag_fontpath if isinstance(fontpath, string_types): fontpath = [fontpath] if fontpath: config = namedtuple('Config', 'font')(fontpath) fontpath = detectfont(config) fontmap.set_default_font(fontpath) except: pass
def _create_fontmap(fontmap, font): """ Inspired from :epkg:`blockdiag` source file (*_bootstrap.py*). """ from blockdiag.utils.fontmap import FontMap fontmap = FontMap(fontmap) if fontmap.find().path is None or font: fontpath = _detectfont(font) fontmap.set_default_font(fontpath) return fontmap
def draw_blockdiag(content, filename=None, font_path=None, output_fmt='png'): diag_type, content = content.split(" ", 1) parser, builder, drawer = DIAG_MODULES[diag_type.strip()] tree = parser.parse_string(content) diagram = builder.ScreenNodeBuilder.build(tree) fontmap = FontMap() if font_path: fontmap.set_default_font(font_path) draw = drawer.DiagramDraw(output_fmt, diagram, filename=filename, antialias=True, fontmap=fontmap) draw.draw() return draw.save()
def draw_diag(path): read_file_and_process(path) diagram_definition = convert_to_origin_seqdiag() print('Converted definition : {}'.format(diagram_definition)) tree = parser.parse_string(diagram_definition) diagram = builder.ScreenNodeBuilder.build(tree) fm = FontMap() fm.set_default_font('./malgun.ttf') draw = drawer.DiagramDraw('PNG', diagram, filename='{}.png'.format( path.split('/\\')[-1].split('.')[0]), fontmap=fm) draw.draw() draw.save() pass
def create_fontmap(): fontmap = FontMap(None) fontmap.set_default_font( os.path.join(os.getcwd(), 'dummy_font', 'ipag.ttf')) return fontmap
#sans-bold: dejavu-fonts-ttf-2.33/ttf/DejaVuSans-Bold.ttf #sans-boldoblique: dejavu-fonts-ttf-2.33/ttf/DejaVuSans-BoldOblique.ttf #sans-extralight: dejavu-fonts-ttf-2.33/ttf/DejaVuSans-ExtraLight.ttf #sans-oblique: dejavu-fonts-ttf-2.33/ttf/DejaVuSans-Oblique.ttf #sans-normal: dejavu-fonts-ttf-2.33/ttf/DejaVuSans.ttf""")) ttf_fonts = \ [('sansserif-bold', os.path.abspath( 'dejavu-fonts-ttf-2.33/ttf/DejaVuSans-Bold.ttf')), ('sansserif-oblique', os.path.abspath( 'dejavu-fonts-ttf-2.33/ttf/DejaVuSans-Oblique.ttf')), ('sansserif-normal', os.path.abspath( 'dejavu-fonts-ttf-2.33/ttf/DejaVuSans.ttf'))] fontmap.set_default_fontfamily('sansserif-normal') fontmap.set_default_font(os.path.abspath('dejavu-fonts-ttf-2.33/ttf/DejaVuSans.ttf')) # Add all the fonts to the fontmap. [fontmap.append_font(ttf_font[0], ttf_font[1]) for ttf_font in ttf_fonts] for filename in glob.glob('blockdiag/*'): diagram_definition = open(filename).read() tree = parser.parse_string(diagram_definition) diagram = builder.ScreenNodeBuilder.build(tree) image_path = \ "../docs/images/{0}".format(filename[len('blockdiag/'):-4] + 'png')
def main(args): print("YASM: Starting...") url_paths = [] root = {} with open(args.file) as json_file: data = json.load(json_file) if args.sdsp: data = rewrite_subdomains_as_slash(data) # Split URL paths into elements along / for item in data: split = item['url'].rstrip("/").split('/') url_paths.append(split[2:]) if args.sdsp: url_paths[-1].append({'title': item['title'], 'url': split[-1], 'subdomain': item['subdomain']}) else: url_paths[-1].append({'title': item['title'], 'url': split[-1]}) # Build tree structure from elements for path in url_paths: # Get element if it exists, set to empty if not branch = root.setdefault(path[0], [{}, []]) for i in path[1:-1]: branch = branch[0].setdefault(i, [{}, []]) branch[1].append(path[-1]) # Delete empty elements delete_empty(root) # Output JSON file (Maybe move to util file) output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "output") if not os.path.exists(output_dir): os.makedirs(output_dir) output_file_json = os.path.join(output_dir, os.path.split(args.file)[-1]) with open(output_file_json, 'w') as outfile: json.dump(root, outfile, indent=2, ensure_ascii=False) # To append .gv, .pdf/.png/.svg later output_name = output_file_json[:-len(".json")] if args.depth == 694201337: calc_max_depth = get_max_depth(root) else: calc_max_depth = args.depth # Sitemap via dot or blockdiag if args.engine == "dot": dot = Digraph() dot.graph_attr['rankdir'] = 'TB' dot.graph_attr['splines'] = 'ortho' dot.graph_attr['concentrate'] = 'true' # User formatting options dot.graph_attr['nodesep'] = args.widthpadding dot.graph_attr['ranksep'] = args.heightpadding dot.node_attr['shape'] = 'rect' dot.node_attr['style'] = 'filled' last = create_nodes(root, dot, args.depth, calc_max_depth=calc_max_depth) graphviz_legend(last, dot) # Save to file # GV creates a PDF/SVG and .gv at the same time, need to rename one dot.format = args.type output_file_gv = output_name + ".gv" dot.render(output_name, view=args.instant) os.rename(output_name, output_file_gv) elif args.engine == "blockdiag": dotDiag = Digraph() create_nodes(root, dotDiag, args.depth, blockdiag=True, calc_max_depth=calc_max_depth) source = dotDiag.source source = source.replace("digraph", "blockdiag") # Legend/Key blockdiag_legend = """group { label = "Legend"; color="#808080"; Parent -> Child; } }""" source = source.replace("}", blockdiag_legend) # Colors source = source.replace("subgraph", "group") source = source.replace("fillcolor", ",color") source = source.replace("style=filled", "") # User formatting options source = add_blockdiag_option(source, "orientation", args.orientation) source = add_blockdiag_option(source, "span_width", args.widthpadding) source = add_blockdiag_option(source, "span_height", args.heightpadding) tree = blockdiagParser.parse_string(source) diagram = builder.ScreenNodeBuilder.build(tree) # Font only needed for PDF output # use project specific font file fontname = "DejaVuSans.ttf" fontpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "util", fontname) fontmap = FontMap() fontmap.set_default_font(fontpath) draw = drawer.DiagramDraw(args.type, diagram, filename=output_name + '.' + args.type, fontmap=fontmap) draw.draw() draw.save() print("YASM: Finished.")
class PADImageDraw(SVGImageDraw): def __init__(self, *args, **kwargs): super(PADImageDraw, self).__init__(*args, **kwargs) self.fontmap = FontMap() self.fontmap.set_default_font('/Library/Fonts/Hiragino Sans GB W3.otf') self.font = self.fontmap.find() def if_block(self, x, y, stmt): width, height = self.statement(x + 1, y, stmt.body) textbox = box(x, y, height=height + 0.25).shift(y=NODE_HEIGHT / 3) shape = (textbox.topleft, textbox.topright, textbox.right.shift(x=-32), textbox.bottomright, textbox.bottomleft, textbox.topleft) self.line(shape, fill='black') self.textarea(textbox, "".join(stmt.test), self.font, fill='black') self.link(x, textbox.top.y) if stmt.orelse == []: height += 1 else: w, h = self.statement(x + 1, y + height, stmt.orelse) width = max(width, w) height += h self.link(x, textbox.bottom.y) return (width + 1, height) def while_block(self, x, y, stmt): textbox = box(x, y) self.rectangle(textbox, outline='black', fill='white') self.textarea(textbox, "".join(stmt.test), self.font, fill='black') self.line( (textbox.topleft.shift(x=12), textbox.bottomleft.shift(x=12)), fill='black') self.link(x, textbox.right.y) width, height = self.statement(x + 1, y, stmt.body) return (width + 1, height) def for_block(self, x, y, stmt): textbox = box(x, y) label = "for %s in %s" % ("".join(stmt.target), "".join(stmt.iter)) self.rectangle(textbox, outline='black', fill='white') self.textarea(textbox, label, self.font, fill='black') self.line( (textbox.topleft.shift(x=12), textbox.bottomleft.shift(x=12)), fill='black') self.link(x, textbox.right.y) width, height = self.statement(x + 1, y, stmt.body) return (width + 1, height) def render(self, tree): return self.statement(0, 0, tree.body) def statement(self, x, y, statements): height = 0 width = 0 for stmt in statements: if isinstance(stmt, str): w, h = self.process(x, y + height, stmt) elif isinstance(stmt, ast.If): w, h = self.if_block(x, y + height, stmt) elif isinstance(stmt, ast.While): w, h = self.while_block(x, y + height, stmt) elif isinstance(stmt, ast.For): w, h = self.for_block(x, y + height, stmt) else: w, h = (0, 0) height += h width = max(width, w) self.baseline(x, y, height) return (width, height) def process(self, x, y, text): textbox = box(x, y) self.rectangle(textbox, outline='black', fill='white') self.textarea(textbox, text, self.font, fill='black') return (1, 1) def baseline(self, x, y, height): start = box(x, y).shift(y=-SPAN_HEIGHT / 3) end = box(x, y + height - 1).shift(y=SPAN_HEIGHT / 3) self.line((start.topleft, end.bottomleft), fill='black') def link(self, x, py): start = XY(box(x, 0).right.x, py) end = XY(box(x + 1, 0).left.x, py) self.line((start, end), fill='black')
def create_fontmap(self, font): fontmap = FontMap() fontmap.set_default_font(font) return fontmap