def embed_vimeo(scheme, netloc, path, query, style): parts = filter(None, path.split('/')) path = '/moogaloop.swf?clip_id=%s&server=vimeo.com&'\ 'show_title=1&show_byline=1&'\ 'show_portrait=0&color=&fullscreen=1' % parts[0] url = urlunparse((scheme, netloc, path, '', '', '')) return tag.object( tag.param(name='movie', value=url), tag.param(name='allowfullscreen', value='true'), tag.param(name='allowscriptaccess', value='always'), tag.embed( src=url, type=SWF_MIME_TYPE, allowfullscreen='true', allowscriptaccess='always', width=style['width'], height=style['height'] ), style=xform_style(style) )
def render(self, context, mimetype, content, filename=None, url=None): """ HTML preview mindmaps in svn-browse and attachment views. """ base = url[:url.rfind('/') + 1] tags = [] #add_script(contex.req, 'freemind/js/flashobject.js') #tags.append(tag.script(src=get_absolute_url('htdocs://freemind/js/flashobject.js', base=context.href.base))) #tags.append('<script src="%s"></script>' % get_absolute_url('htdocs://freemind/js/flashobject.js', base=context.href.base)) # #script = ''' # $(document).ready(function() { # $("#flashcontent").mouseover(function() { # document.visorFreeMind.focus(); # }); # # var fo = new FlashObject("%(visor)s", "visorFreeMind", "100%%", "100%%", 6, "#9999ff"); # # fo.addParam("quality","high"); # fo.addParam("bgcolor","#a0a0f0"); # fo.addVariable("openUrl","_blank"); # fo.addVariable("startCollapsedToLevel","3"); # fo.addVariable("maxNodeWidth","200"); # fo.addVariable("mainNodeShape","elipse"); # fo.addVariable("justMap","false"); # fo.addVariable("initLoadFile","%(file)s"); # fo.addVariable("defaultToolTipWordWrap",200); # fo.addVariable("offsetX","left"); # fo.addVariable("offsetY","top"); # fo.addVariable("buttonsPos","top"); # fo.addVariable("min_alpha_buttons",20); # fo.addVariable("max_alpha_buttons",100); # fo.addVariable("scaleTooltips","false"); # fo.addVariable("baseImagePath","%(base)s"); # fo.addVariable("CSSFile","%(css)s"); # //fo.addVariable("toolTipsBgColor","0xa0a0f0"); # //fo.addVariable("genAllShots","true"); # //fo.addVariable("unfoldAll","true"); # fo.write("flashcontent"); # }); #''' % { # 'visor': get_absolute_url('htdocs://freemind/swf/visorFreemind.swf', base=context.href.base), # 'file': url, # 'base': base, # 'css': get_absolute_url('htdocs://freemind/css/flashfreemind.css', base=context.href.base), #} script = '''\ $(document).ready(function() { $("#flashcontent").mouseover(function() { document.visorFreeMind.focus(); }); }); ''' flash_dict = { 'openUrl': '_blank', 'initLoadFile': url, 'startCollapsedToLevel': '3', 'defaultToolTipWordWrap': '200', 'baseImagePath': base, 'min_alpha_buttons': '20', 'max_alpha_buttons': '100' } flash_vars = '&'.join( ['%s=%s' % (k, v) for k, v in flash_dict.items()]) embed = tag.embed(type='application/x-shockwave-flash', src=get_absolute_url( 'htdocs://freemind/swf/visorFreemind.swf', base=context.href.base), id='visorFreeMind', bgcolor='#ffffff', quality='high', flashvars=flash_vars, align='middle', height='100%', width='100%') #tags.append(tag.script(script)) #tags.append(tag.div('Flash plugin or JavaScript are turned off. Activate both and reload to view the mindmap.', # id='flashcontent', # style='border: 1px solid #cccccc; height: 600px; width: 100%;')) tags.append( tag.div( embed, id='flashcontent', style='border: 1px solid #cccccc; height: 600px; width: 100%;') ) return ''.join([str(i) for i in tags])
def expand_macro(self, formatter, name, content): args, kwargs = parse_args(content, strict=True) try: kwargs = string_keys(kwargs) except: raise TracError('Error #3922, content: %s, args: %s, kwargs: %s', (str(content), str(args), kwargs)) if len(args) >= 1: url = args[0] elif len(args) == 0: raise TracError('URL to the mindmap at least required.') embed_count = getattr(formatter, EMBED_COUNT, 0) embed_count += 1 setattr(formatter, EMBED_COUNT, embed_count) if embed_count == 1: add_script(formatter.req, 'freemind/js/flashobject.js') url = get_absolute_url(url, formatter) base = url[:url.rfind('/') + 1] #script = '''\ # $(document).ready(function() { # $("#flashcontent%(count)02d").mouseover(function() { # document.visorFreeMind%(count)02d.focus(); # }); # # var fo = new FlashObject("%(visor)s", "visorFreeMind%(count)02d", "100%%", "100%%", 6, "#9999ff"); # # fo.addParam("quality","high"); # fo.addParam("bgcolor","#a0a0f0"); # fo.addVariable("openUrl","_blank"); # fo.addVariable("startCollapsedToLevel","3"); # fo.addVariable("maxNodeWidth","200"); # fo.addVariable("mainNodeShape","elipse"); # fo.addVariable("justMap","false"); # fo.addVariable("initLoadFile","%(file)s"); # fo.addVariable("defaultToolTipWordWrap",200); # fo.addVariable("offsetX","left"); # fo.addVariable("offsetY","top"); # fo.addVariable("buttonsPos","top"); # fo.addVariable("min_alpha_buttons",20); # fo.addVariable("max_alpha_buttons",100); # fo.addVariable("scaleTooltips","false"); # fo.addVariable("baseImagePath","%(base)s"); # fo.addVariable("CSSFile","%(css)s"); # //fo.addVariable("toolTipsBgColor","0xa0a0f0"); # //fo.addVariable("genAllShots","true"); # //fo.addVariable("unfoldAll","true"); # fo.write("flashcontent%(count)02d"); # }); #''' % { # 'count': embed_count, # 'visor': get_absolute_url('htdocs://freemind/swf/visorFreemind.swf', formatter), # 'file': url, # 'base': base, # 'css': get_absolute_url('htdocs://freemind/css/flashfreemind.css', formatter), #} script = '''\ $(document).ready(function() { $("#flashcontent%(count)02d").mouseover(function() { document.visorFreeMind%(count)02d.focus(); }); }); // url: %(url)s // base: %(base)s ''' % { 'count': embed_count, 'url': url, 'base': base } flash_dict = { 'openUrl': '_blank', 'initLoadFile': url, 'startCollapsedToLevel': '3', 'defaultToolTipWordWrap': '200', 'baseImagePath': base, 'min_alpha_buttons': '20', 'max_alpha_buttons': '100' } flash_vars = '&'.join( ['%s=%s' % (k, v) for k, v in flash_dict.items()]) embed = tag.embed(type='application/x-shockwave-flash', src=get_absolute_url( 'htdocs://freemind/swf/visorFreemind.swf', formatter), id='visorFreeMind%02d' % embed_count, bgcolor='#ffffff', quality='high', flashvars=flash_vars, align='middle', height='100%', width='100%') # Debugging. if 'debug' in args: import os import datetime output = "FreemindMacro Debug Log\n"\ "=======================\n\n"\ "time: %(time)s\n"\ "version: %(version)s\n"\ "content: %(content)s\n"\ "args: %(args)s\n"\ "kwargs: %(kwargs)s\n"\ "formatter.href.base: %(base)s\n"\ "script: \n\n"\ "%(script)s" % { 'time': datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ'), 'version': __version__, 'content': content, 'args': str(args), 'kwargs': str(kwargs), 'base': str(formatter.href.base), 'script': script } return tag.pre( output, style='border: 2px dashed red; padding: 5px; background: #eee;' ) style_dict = xform_style(kwargs.get('style', '')) width = kwargs.pop('width', style_dict.get('width', '800px')) height = kwargs.pop('height', style_dict.get('height', '600px')) style_dict['border'] = style_dict.get('border', '1px solid #cccccc;') style_dict['margin'] = style_dict.get('margin', '0 auto') style_dict['width'] = width style_dict['height'] = height kwargs['style'] = xform_style(style_dict) # You can't touch this... kwargs.pop('id', None) if 'class' in kwargs: kwargs['class_'] = kwargs.pop('class') tags = [] #tags.append(tag.div('Flash plugin or JavaScript are turned off. Activate both and reload to view the mindmap.', # id='flashcontent%02d' % embed_count, **kwargs)) tags.append( tag.div(embed, id='flashcontent%02d' % embed_count, **kwargs)) tags.append(tag.script(script)) return ''.join([str(i) for i in tags])
def expand_macro(self, formatter_or_context, name, content): """Return the HTML output of the macro. :param formatter_or_context: a Formatter when called as a macro, a Context when called by `MetapostPlugin.render` :param name: Wiki macro command that resulted in this method being called. In this case, it should be 'metapost' by an output format, as following: metapost/<format> Valid output formats are: jpg, png, gif, svg and svgz. The default is the value specified in the out_format configuration parameter. If out_format is not specified in the configuration, then the default is png. examples: metapost/png -> png metapost/jpeg -> jpeg metapost/jpg -> jpg metapost -> png metapost/svg -> svg :param content: The text the user entered for the macro to process. """ # check and load the configuration errmsg = self._load_config() if errmsg: return self._error_div(errmsg) out_format = self.out_format # first try with the RegExp engine try: m = re.match('metapost\/?([a-z]*)', name) (out_format) = m.group(1, 2) # or use the string.split method except: (s_sp) = (name.split('/')) if len(s_sp) > 1: out_format = s_sp[1] # assign default values, if instance ones are empty if not out_format: out_format = self.out_format if out_format not in Metapost.Formats: self.log.error('render_macro: requested format (%s) not found.' % out_format) return self._error_div( tag.p( _("Metapost macro processor error: requested format (%(fmt)s) not valid.", fmt=out_format))) encoded_content = content.encode(self.encoding) sha_key = sha.new(encoded_content).hexdigest() mpost_name = '%s.%s' % (sha_key, 'mp') mpost_path = os.path.join(self.cache_dir, mpost_name) img_name = '%s.%s' % (sha_key, out_format) img_path = os.path.join(self.cache_dir, img_name) # Create image if not in cache if not os.path.exists(img_path): self._clean_cache() f = open(mpost_path, 'w+') f.write(encoded_content) f.close() os.system('cd %s ; mpost %s' % (self.cache_dir, mpost_name)) os.system('cd %s ; mptopdf %s.%s' % (self.cache_dir, sha_key, '1')) if errmsg: # there was a warning. Ideally we should be able to use # `add_warning` here, but that's not possible as the warnings # are already emitted at this point in the template processing return self._error_div(errmsg) # Generate HTML output img_url = formatter_or_context.href.metapost(img_name) # for SVG(z) if out_format in Metapost.Vector_Formats: os.system('cd %s ; pdf2svg %s-1.%s %s' % (self.cache_dir, sha_key, 'pdf', img_path)) try: # try to get SVG dimensions f = open(img_path, 'r') svg = f.readlines(1024) # don't read all f.close() svg = "".join(svg).replace('\n', '') w = re.search('width="([0-9]+)(.*?)" ', svg) h = re.search('height="([0-9]+)(.*?)"', svg) (w_val, w_unit) = w.group(1, 2) (h_val, h_unit) = h.group(1, 2) # Graphviz seems to underestimate height/width for SVG images, # so we have to adjust them. # The correction factor seems to be constant. w_val, h_val = [1.35 * float(x) for x in (w_val, h_val)] width = unicode(w_val) + w_unit height = unicode(h_val) + h_unit except ValueError: width = height = '100%' # insert SVG, IE compatibility return tag.object(tag.embed(src=img_url, type="image/svg+xml", width=width, height=height), data=img_url, type="image/svg+xml", width=width, height=height) else: os.system('cd %s ; pdftoppm %s-1.%s %s' % (self.cache_dir, sha_key, 'pdf', sha_key)) os.system('cd %s ; convert %s-1.%s %s' % (self.cache_dir, sha_key, 'ppm', img_name)) return tag.img(src=img_url, alt=_("MetaPost image"))
def expand_macro(self, formatter_or_context, name, content): """Return the HTML output of the macro. :param formatter_or_context: a Formatter when called as a macro, a Context when called by `GraphvizPlugin.render` :param name: Wiki macro command that resulted in this method being called. In this case, it should be 'graphviz', followed (or not) by the processor name, then by an output format, as following: graphviz.<processor>/<format> Valid processor names are: dot, neato, twopi, circo, and fdp. The default is dot. Valid output formats are: jpg, png, gif, svg and svgz. The default is the value specified in the out_format configuration parameter. If out_format is not specified in the configuration, then the default is png. examples: graphviz.dot/png -> dot png graphviz.neato/jpg -> neato jpg graphviz.circo -> circo png graphviz/svg -> dot svg :param content: The text the user entered for the macro to process. """ # check and load the configuration errmsg = self._load_config() if errmsg: return self._error_div(errmsg) ## Extract processor and format from name processor = out_format = None # first try with the RegExp engine try: m = re.match('graphviz\.?([a-z]*)\/?([a-z]*)', name) (processor, out_format) = m.group(1, 2) # or use the string.split method except: (d_sp, s_sp) = (name.split('.'), name.split('/')) if len(d_sp) > 1: s_sp = d_sp[1].split('/') if len(s_sp) > 1: out_format = s_sp[1] processor = s_sp[0] elif len(s_sp) > 1: out_format = s_sp[1] # assign default values, if instance ones are empty if not out_format: out_format = self.out_format if not processor: processor = self.processor if processor in Graphviz.Processors: proc_cmd = self.cmds[processor] else: self.log.error('render_macro: requested processor (%s) not found.' % processor) return self._error_div('requested processor (%s) not found.' % processor) if out_format not in Graphviz.Formats: self.log.error('render_macro: requested format (%s) not found.' % out_format) return self._error_div( tag.p(_("Graphviz macro processor error: " "requested format (%(fmt)s) not valid.", fmt=out_format))) encoded_cmd = (processor + unicode(self.processor_options)) \ .encode(self.encoding) encoded_content = content.encode(self.encoding) sha_key = sha1(encoded_cmd + encoded_content).hexdigest() img_name = '%s.%s.%s' % (sha_key, processor, out_format) # cache: hash.<dot>.<png> img_path = os.path.join(self.cache_dir, img_name) map_name = '%s.%s.map' % (sha_key, processor) # cache: hash.<dot>.map map_path = os.path.join(self.cache_dir, map_name) # Check for URL="" presence in graph code URL_in_graph = 'URL=' in content # Create image if not in cache if not os.path.exists(img_path): self._clean_cache() if URL_in_graph: # translate wiki TracLinks in URL if isinstance(formatter_or_context, Context): context = formatter_or_context else: context = formatter_or_context.context content = self._expand_wiki_links(context, out_format, content) encoded_content = content.encode(self.encoding) # Antialias PNGs with rsvg, if requested if out_format == 'png' and self.png_anti_alias == True: # 1. SVG output failure, errmsg = self._launch( encoded_content, proc_cmd, '-Tsvg', '-o%s.svg' % img_path, *self.processor_options) if failure: return self._error_div(errmsg) # 2. SVG to PNG rasterization failure, errmsg = self._launch( None, self.rsvg_path, '--dpi-x=%d' % self.dpi, '--dpi-y=%d' % self.dpi, '%s.svg' % img_path, img_path) if failure: return self._error_div(errmsg) else: # Render other image formats failure, errmsg = self._launch( encoded_content, proc_cmd, '-T%s' % out_format, '-o%s' % img_path, *self.processor_options) if failure: return self._error_div(errmsg) # Generate a map file for binary formats if URL_in_graph and out_format in Graphviz.Bitmap_Formats: # Create the map if not in cache if not os.path.exists(map_path): failure, errmsg = self._launch( encoded_content, proc_cmd, '-Tcmap', '-o%s' % map_path, *self.processor_options) if failure: return self._error_div(errmsg) if errmsg: # there was a warning. Ideally we should be able to use # `add_warning` here, but that's not possible as the warnings # are already emitted at this point in the template processing return self._error_div(errmsg) # Generate HTML output img_url = formatter_or_context.href.graphviz(img_name) # for SVG(z) if out_format in Graphviz.Vector_Formats: try: # try to get SVG dimensions f = open(img_path, 'r') svg = f.readlines(1024) # don't read all f.close() svg = "".join(svg).replace('\n', '') w = re.search('width="([0-9]+)(.*?)" ', svg) h = re.search('height="([0-9]+)(.*?)"', svg) (w_val, w_unit) = w.group(1,2) (h_val, h_unit) = h.group(1,2) # Graphviz seems to underestimate height/width for SVG images, # so we have to adjust them. # The correction factor seems to be constant. w_val, h_val = [1.35 * float(x) for x in (w_val, h_val)] width = unicode(w_val) + w_unit height = unicode(h_val) + h_unit except ValueError: width = height = '100%' # insert SVG, IE compatibility return tag.object( tag.embed(src=img_url, type="image/svg+xml", width=width, height=height), data=img_url, type="image/svg+xml", width=width, height=height) # for binary formats, add map elif URL_in_graph and os.path.exists(map_path): f = open(map_path, 'r') map = f.readlines() f.close() map = "".join(map).replace('\n', '') return tag(tag.map(Markup(map), id='G'+sha_key, name='G'+sha_key), tag.img(src=img_url, usemap="#G"+sha_key, alt=_("GraphViz image"))) else: return tag.img(src=img_url, alt=_("GraphViz image"))
def render(self, context, mimetype, content, filename=None, url=None): """ HTML preview mindmaps in svn-browse and attachment views. """ base = url[:url.rfind('/')+1] tags = [] #add_script(contex.req, 'freemind/js/flashobject.js') #tags.append(tag.script(src=get_absolute_url('htdocs://freemind/js/flashobject.js', base=context.href.base))) #tags.append('<script src="%s"></script>' % get_absolute_url('htdocs://freemind/js/flashobject.js', base=context.href.base)) # #script = ''' # $(document).ready(function() { # $("#flashcontent").mouseover(function() { # document.visorFreeMind.focus(); # }); # # var fo = new FlashObject("%(visor)s", "visorFreeMind", "100%%", "100%%", 6, "#9999ff"); # # fo.addParam("quality","high"); # fo.addParam("bgcolor","#a0a0f0"); # fo.addVariable("openUrl","_blank"); # fo.addVariable("startCollapsedToLevel","3"); # fo.addVariable("maxNodeWidth","200"); # fo.addVariable("mainNodeShape","elipse"); # fo.addVariable("justMap","false"); # fo.addVariable("initLoadFile","%(file)s"); # fo.addVariable("defaultToolTipWordWrap",200); # fo.addVariable("offsetX","left"); # fo.addVariable("offsetY","top"); # fo.addVariable("buttonsPos","top"); # fo.addVariable("min_alpha_buttons",20); # fo.addVariable("max_alpha_buttons",100); # fo.addVariable("scaleTooltips","false"); # fo.addVariable("baseImagePath","%(base)s"); # fo.addVariable("CSSFile","%(css)s"); # //fo.addVariable("toolTipsBgColor","0xa0a0f0"); # //fo.addVariable("genAllShots","true"); # //fo.addVariable("unfoldAll","true"); # fo.write("flashcontent"); # }); #''' % { # 'visor': get_absolute_url('htdocs://freemind/swf/visorFreemind.swf', base=context.href.base), # 'file': url, # 'base': base, # 'css': get_absolute_url('htdocs://freemind/css/flashfreemind.css', base=context.href.base), #} script = '''\ $(document).ready(function() { $("#flashcontent").mouseover(function() { document.visorFreeMind.focus(); }); }); ''' flash_dict = { 'openUrl': '_blank', 'initLoadFile': url, 'startCollapsedToLevel': '3', 'defaultToolTipWordWrap': '200', 'baseImagePath': base, 'min_alpha_buttons': '20', 'max_alpha_buttons': '100' } flash_vars = '&'.join(['%s=%s' % (k, v) for k, v in flash_dict.items()]) embed = tag.embed(type='application/x-shockwave-flash', src=get_absolute_url('htdocs://freemind/swf/visorFreemind.swf', base=context.href.base), id='visorFreeMind', bgcolor='#ffffff', quality='high', flashvars=flash_vars, align='middle', height='100%', width='100%') #tags.append(tag.script(script)) #tags.append(tag.div('Flash plugin or JavaScript are turned off. Activate both and reload to view the mindmap.', # id='flashcontent', # style='border: 1px solid #cccccc; height: 600px; width: 100%;')) tags.append(tag.div(embed, id='flashcontent', style='border: 1px solid #cccccc; height: 600px; width: 100%;')) return ''.join([str(i) for i in tags])
def expand_macro(self, formatter, name, content): args, kwargs = parse_args(content, strict=True) try: kwargs = string_keys(kwargs) except: raise TracError('Error #3922, content: %s, args: %s, kwargs: %s', (str(content), str(args), kwargs)) if len(args) >= 1: url = args[0] elif len(args) == 0: raise TracError('URL to the mindmap at least required.') embed_count = getattr(formatter, EMBED_COUNT, 0) embed_count += 1 setattr(formatter, EMBED_COUNT, embed_count) if embed_count == 1: add_script(formatter.req, 'freemind/js/flashobject.js') url = get_absolute_url(url, formatter) base = url[:url.rfind('/')+1] #script = '''\ # $(document).ready(function() { # $("#flashcontent%(count)02d").mouseover(function() { # document.visorFreeMind%(count)02d.focus(); # }); # # var fo = new FlashObject("%(visor)s", "visorFreeMind%(count)02d", "100%%", "100%%", 6, "#9999ff"); # # fo.addParam("quality","high"); # fo.addParam("bgcolor","#a0a0f0"); # fo.addVariable("openUrl","_blank"); # fo.addVariable("startCollapsedToLevel","3"); # fo.addVariable("maxNodeWidth","200"); # fo.addVariable("mainNodeShape","elipse"); # fo.addVariable("justMap","false"); # fo.addVariable("initLoadFile","%(file)s"); # fo.addVariable("defaultToolTipWordWrap",200); # fo.addVariable("offsetX","left"); # fo.addVariable("offsetY","top"); # fo.addVariable("buttonsPos","top"); # fo.addVariable("min_alpha_buttons",20); # fo.addVariable("max_alpha_buttons",100); # fo.addVariable("scaleTooltips","false"); # fo.addVariable("baseImagePath","%(base)s"); # fo.addVariable("CSSFile","%(css)s"); # //fo.addVariable("toolTipsBgColor","0xa0a0f0"); # //fo.addVariable("genAllShots","true"); # //fo.addVariable("unfoldAll","true"); # fo.write("flashcontent%(count)02d"); # }); #''' % { # 'count': embed_count, # 'visor': get_absolute_url('htdocs://freemind/swf/visorFreemind.swf', formatter), # 'file': url, # 'base': base, # 'css': get_absolute_url('htdocs://freemind/css/flashfreemind.css', formatter), #} script = '''\ $(document).ready(function() { $("#flashcontent%(count)02d").mouseover(function() { document.visorFreeMind%(count)02d.focus(); }); }); // url: %(url)s // base: %(base)s ''' % {'count': embed_count, 'url': url, 'base': base} flash_dict = { 'openUrl': '_blank', 'initLoadFile': url, 'startCollapsedToLevel': '3', 'defaultToolTipWordWrap': '200', 'baseImagePath': base, 'min_alpha_buttons': '20', 'max_alpha_buttons': '100' } flash_vars = '&'.join(['%s=%s' % (k, v) for k, v in flash_dict.items()]) embed = tag.embed(type='application/x-shockwave-flash', src=get_absolute_url('htdocs://freemind/swf/visorFreemind.swf', formatter), id='visorFreeMind%02d' % embed_count, bgcolor='#ffffff', quality='high', flashvars=flash_vars, align='middle', height='100%', width='100%') # Debugging. if 'debug' in args: import os import datetime output = "FreemindMacro Debug Log\n"\ "=======================\n\n"\ "time: %(time)s\n"\ "version: %(version)s\n"\ "content: %(content)s\n"\ "args: %(args)s\n"\ "kwargs: %(kwargs)s\n"\ "formatter.href.base: %(base)s\n"\ "script: \n\n"\ "%(script)s" % { 'time': datetime.datetime.utcnow().strftime('%Y%m%dT%H%M%SZ'), 'version': __version__, 'content': content, 'args': str(args), 'kwargs': str(kwargs), 'base': str(formatter.href.base), 'script': script } return tag.pre(output, style='border: 2px dashed red; padding: 5px; background: #eee;') style_dict = xform_style(kwargs.get('style', '')) width = kwargs.pop('width', style_dict.get('width', '800px')) height = kwargs.pop('height', style_dict.get('height', '600px')) style_dict['border'] = style_dict.get('border', '1px solid #cccccc;') style_dict['margin'] = style_dict.get('margin', '0 auto') style_dict['width'] = width style_dict['height'] = height kwargs['style'] = xform_style(style_dict) # You can't touch this... kwargs.pop('id', None) if 'class' in kwargs: kwargs['class_'] = kwargs.pop('class') tags = [] #tags.append(tag.div('Flash plugin or JavaScript are turned off. Activate both and reload to view the mindmap.', # id='flashcontent%02d' % embed_count, **kwargs)) tags.append(tag.div(embed, id='flashcontent%02d' % embed_count, **kwargs)) tags.append(tag.script(script)) return ''.join([str(i) for i in tags])
def expand_macro(self, formatter_or_context, name, content): """Return the HTML output of the macro. :param formatter_or_context: a Formatter when called as a macro, a Context when called by `MetapostPlugin.render` :param name: Wiki macro command that resulted in this method being called. In this case, it should be 'metapost' by an output format, as following: metapost/<format> Valid output formats are: jpg, png, gif, svg and svgz. The default is the value specified in the out_format configuration parameter. If out_format is not specified in the configuration, then the default is png. examples: metapost/png -> png metapost/jpeg -> jpeg metapost/jpg -> jpg metapost -> png metapost/svg -> svg :param content: The text the user entered for the macro to process. """ # check and load the configuration errmsg = self._load_config() if errmsg: return self._error_div(errmsg) out_format = self.out_format # first try with the RegExp engine try: m = re.match('metapost\/?([a-z]*)', name) (out_format) = m.group(1, 2) # or use the string.split method except: (s_sp) = (name.split('/')) if len(s_sp) > 1: out_format = s_sp[1] # assign default values, if instance ones are empty if not out_format: out_format = self.out_format if out_format not in Metapost.Formats: self.log.error('render_macro: requested format (%s) not found.' % out_format) return self._error_div( tag.p(_("Metapost macro processor error: requested format (%(fmt)s) not valid.", fmt=out_format))) encoded_content = content.encode(self.encoding) sha_key = sha.new(encoded_content).hexdigest() mpost_name = '%s.%s' % (sha_key, 'mp') mpost_path = os.path.join(self.cache_dir, mpost_name) img_name = '%s.%s' % (sha_key, out_format) img_path = os.path.join(self.cache_dir, img_name) # Create image if not in cache if not os.path.exists(img_path): self._clean_cache() f = open(mpost_path, 'w+') f.write(encoded_content) f.close() os.system('cd %s ; mpost %s' % (self.cache_dir, mpost_name)) os.system('cd %s ; mptopdf %s.%s' % (self.cache_dir, sha_key, '1')) if errmsg: # there was a warning. Ideally we should be able to use # `add_warning` here, but that's not possible as the warnings # are already emitted at this point in the template processing return self._error_div(errmsg) # Generate HTML output img_url = formatter_or_context.href.metapost(img_name) # for SVG(z) if out_format in Metapost.Vector_Formats: os.system('cd %s ; pdf2svg %s-1.%s %s' % (self.cache_dir, sha_key, 'pdf', img_path)) try: # try to get SVG dimensions f = open(img_path, 'r') svg = f.readlines(1024) # don't read all f.close() svg = "".join(svg).replace('\n', '') w = re.search('width="([0-9]+)(.*?)" ', svg) h = re.search('height="([0-9]+)(.*?)"', svg) (w_val, w_unit) = w.group(1,2) (h_val, h_unit) = h.group(1,2) # Graphviz seems to underestimate height/width for SVG images, # so we have to adjust them. # The correction factor seems to be constant. w_val, h_val = [1.35 * float(x) for x in (w_val, h_val)] width = unicode(w_val) + w_unit height = unicode(h_val) + h_unit except ValueError: width = height = '100%' # insert SVG, IE compatibility return tag.object( tag.embed(src=img_url, type="image/svg+xml", width=width, height=height), data=img_url, type="image/svg+xml", width=width, height=height) else: os.system('cd %s ; pdftoppm %s-1.%s %s' % (self.cache_dir, sha_key, 'pdf', sha_key)) os.system('cd %s ; convert %s-1.%s %s' % (self.cache_dir, sha_key, 'ppm', img_name)) return tag.img(src=img_url, alt=_("MetaPost image"))
def expand_macro(self, formatter, name, content): """Return the HTML output of the macro.""" req = formatter.req # check and load the configuration errmsg = self._load_config() if errmsg: return self._error_div(errmsg) ## Extract processor and format from name processor = out_format = None # first try with the RegExp engine try: m = re.match('graphviz\.?([a-z]*)\/?([a-z]*)', name) (processor, out_format) = m.group(1, 2) # or use the string.split method except: (d_sp, s_sp) = (name.split('.'), name.split('/')) if len(d_sp) > 1: s_sp = d_sp[1].split('/') if len(s_sp) > 1: out_format = s_sp[1] processor = s_sp[0] elif len(s_sp) > 1: out_format = s_sp[1] # assign default values, if instance ones are empty if not out_format: out_format = self.out_format if not processor: processor = self.processor if processor in Graphviz.Processors: proc_cmd = self.cmds[processor] else: self.log.error('render_macro: requested processor (%s) not found.' % processor) return self._error_div('requested processor (%s) not found.' % processor) if out_format not in Graphviz.Formats: self.log.error('render_macro: requested format (%s) not found.' % out_format) return self._error_div( tag.p(_("Graphviz macro processor error: " "requested format (%(fmt)s) not valid.", fmt=out_format))) encoded_cmd = (processor + unicode(self.processor_options)) \ .encode(self.encoding) encoded_content = content.encode(self.encoding) sha_key = sha.new(encoded_cmd + encoded_content).hexdigest() img_name = '%s.%s.%s' % (sha_key, processor, out_format) # cache: hash.<dot>.<png> img_path = os.path.join(self.cache_dir, img_name) map_name = '%s.%s.map' % (sha_key, processor) # cache: hash.<dot>.map map_path = os.path.join(self.cache_dir, map_name) # Check for URL="" presence in graph code URL_in_graph = 'URL=' in content # Create image if not in cache if not os.path.exists(img_path): self._clean_cache() if URL_in_graph: # translate wiki TracLinks in URL content = self._expand_wiki_links(formatter, out_format, content) encoded_content = content.encode(self.encoding) # Antialias PNGs with rsvg, if requested if out_format == 'png' and self.png_anti_alias == True: # 1. SVG output errmsg = self._launch(encoded_content, proc_cmd, '-Tsvg', '-o%s.svg' % img_path, *self.processor_options) if errmsg: return self._error_div(errmsg) # 2. SVG to PNG rasterization errmsg = self._launch(None, self.rsvg_path, '--dpi-x=%d' % self.dpi, '--dpi-y=%d' % self.dpi, '%s.svg' % img_path, img_path) if errmsg: return self._error_div(errmsg) else: # Render other image formats errmsg = self._launch(encoded_content, proc_cmd, '-T%s' % out_format, '-o%s' % img_path, *self.processor_options) if errmsg: return self._error_div(errmsg) # Generate a map file for binary formats if URL_in_graph and out_format in Graphviz.Bitmap_Formats: # Create the map if not in cache if not os.path.exists(map_path): errmsg = self._launch(encoded_content, proc_cmd, '-Tcmap', '-o%s' % map_path, *self.processor_options) if errmsg: return self._error_div(errmsg) # Generate HTML output img_url = formatter.href.graphviz(img_name) # for SVG(z) if out_format in Graphviz.Vector_Formats: try: # try to get SVG dimensions f = open(img_path, 'r') svg = f.readlines(1024) # don't read all f.close() svg = "".join(svg).replace('\n', '') w = re.search('width="([0-9]+)(.*?)" ', svg) h = re.search('height="([0-9]+)(.*?)"', svg) (w_val, w_unit) = w.group(1,2) (h_val, h_unit) = h.group(1,2) # Graphviz seems to underestimate height/width for SVG images, # so we have to adjust them. # The correction factor seems to be constant. w_val, h_val = [1.35 * float(x) for x in (w_val, h_val)] width = unicode(w_val) + w_unit height = unicode(h_val) + h_unit except ValueError: width = height = '100%' # insert SVG, IE compatibility return tag.object( tag.embed(src=img_url, type="image/svg+xml", width=width, height=height), data=img_url, type="image/svg+xml", width=width, height=height) # for binary formats, add map elif URL_in_graph and os.path.exists(map_path): f = open(map_path, 'r') map = f.readlines() f.close() map = "".join(map).replace('\n', '') return tag(tag.map(Markup(map), id='G'+sha_key, name='G'+sha_key), tag.img(src=img_url, usemap="#G"+sha_key, alt=_("GraphViz image"))) else: return tag.img(src=img_url, alt=_("GraphViz image"))
def expand_macro(self, formatter_or_context, name, content): """Return the HTML output of the macro. :param formatter_or_context: a Formatter when called as a macro, a Context when called by `GraphvizPlugin.render` :param name: Wiki macro command that resulted in this method being called. In this case, it should be 'graphviz', followed (or not) by the processor name, then by an output format, as following: graphviz.<processor>/<format> Valid processor names are: dot, neato, twopi, circo, and fdp. The default is dot. Valid output formats are: jpg, png, gif, svg and svgz. The default is the value specified in the out_format configuration parameter. If out_format is not specified in the configuration, then the default is png. examples: graphviz.dot/png -> dot png graphviz.neato/jpg -> neato jpg graphviz.circo -> circo png graphviz/svg -> dot svg :param content: The text the user entered for the macro to process. """ # check and load the configuration errmsg = self._load_config() if errmsg: return self._error_div(errmsg) ## Extract processor and format from name processor = out_format = None # first try with the RegExp engine try: m = re.match('graphviz\.?([a-z]*)\/?([a-z]*)', name) (processor, out_format) = m.group(1, 2) # or use the string.split method except: (d_sp, s_sp) = (name.split('.'), name.split('/')) if len(d_sp) > 1: s_sp = d_sp[1].split('/') if len(s_sp) > 1: out_format = s_sp[1] processor = s_sp[0] elif len(s_sp) > 1: out_format = s_sp[1] # assign default values, if instance ones are empty if not out_format: out_format = self.out_format if not processor: processor = self.processor if processor in Graphviz.Processors: proc_cmd = self.cmds[processor] else: self.log.error( 'render_macro: requested processor (%s) not found.' % processor) return self._error_div('requested processor (%s) not found.' % processor) if out_format not in Graphviz.Formats: self.log.error('render_macro: requested format (%s) not found.' % out_format) return self._error_div( tag.p( _( "Graphviz macro processor error: " "requested format (%(fmt)s) not valid.", fmt=out_format))) encoded_cmd = (processor + unicode(self.processor_options)) \ .encode(self.encoding) encoded_content = content.encode(self.encoding) sha_key = sha1(encoded_cmd + encoded_content).hexdigest() img_name = '%s.%s.%s' % (sha_key, processor, out_format) # cache: hash.<dot>.<png> img_path = os.path.join(self.cache_dir, img_name) map_name = '%s.%s.map' % (sha_key, processor) # cache: hash.<dot>.map map_path = os.path.join(self.cache_dir, map_name) # Check for URL="" presence in graph code URL_in_graph = 'URL=' in content # Create image if not in cache if not os.path.exists(img_path): self._clean_cache() if URL_in_graph: # translate wiki TracLinks in URL if isinstance(formatter_or_context, Context): context = formatter_or_context else: context = formatter_or_context.context content = self._expand_wiki_links(context, out_format, content) encoded_content = content.encode(self.encoding) # Antialias PNGs with rsvg, if requested if out_format == 'png' and self.png_anti_alias == True: # 1. SVG output failure, errmsg = self._launch(encoded_content, proc_cmd, '-Tsvg', '-o%s.svg' % img_path, *self.processor_options) if failure: return self._error_div(errmsg) # 2. SVG to PNG rasterization failure, errmsg = self._launch(None, self.rsvg_path, '--dpi-x=%d' % self.dpi, '--dpi-y=%d' % self.dpi, '%s.svg' % img_path, img_path) if failure: return self._error_div(errmsg) else: # Render other image formats failure, errmsg = self._launch(encoded_content, proc_cmd, '-T%s' % out_format, '-o%s' % img_path, *self.processor_options) if failure: return self._error_div(errmsg) # Generate a map file for binary formats if URL_in_graph and out_format in Graphviz.Bitmap_Formats: # Create the map if not in cache if not os.path.exists(map_path): failure, errmsg = self._launch(encoded_content, proc_cmd, '-Tcmap', '-o%s' % map_path, *self.processor_options) if failure: return self._error_div(errmsg) if errmsg: # there was a warning. Ideally we should be able to use # `add_warning` here, but that's not possible as the warnings # are already emitted at this point in the template processing return self._error_div(errmsg) # Generate HTML output img_url = formatter_or_context.href.graphviz(img_name) # for SVG(z) if out_format in Graphviz.Vector_Formats: try: # try to get SVG dimensions f = open(img_path, 'r') svg = f.readlines(1024) # don't read all f.close() svg = "".join(svg).replace('\n', '') w = re.search('width="([0-9]+)(.*?)" ', svg) h = re.search('height="([0-9]+)(.*?)"', svg) (w_val, w_unit) = w.group(1, 2) (h_val, h_unit) = h.group(1, 2) # Graphviz seems to underestimate height/width for SVG images, # so we have to adjust them. # The correction factor seems to be constant. w_val, h_val = [1.35 * float(x) for x in (w_val, h_val)] width = unicode(w_val) + w_unit height = unicode(h_val) + h_unit except ValueError: width = height = '100%' # insert SVG, IE compatibility return tag.object(tag.embed(src=img_url, type="image/svg+xml", width=width, height=height), data=img_url, type="image/svg+xml", width=width, height=height) # for binary formats, add map elif URL_in_graph and os.path.exists(map_path): f = open(map_path, 'r') map = f.readlines() f.close() map = "".join(map).replace('\n', '') return tag( tag.map(Markup(map), id='G' + sha_key, name='G' + sha_key), tag.img(src=img_url, usemap="#G" + sha_key, alt=_("GraphViz image"))) else: return tag.img(src=img_url, alt=_("GraphViz image"))
def expand_macro(self, formatter, name, content): args, kwargs = parse_args(content, strict=True) kwargs = string_keys(kwargs) if len(args) >= 1: url = args[0] elif len(args) == 0: raise TracError('URL to a movie at least required.') embed_count = getattr(formatter, EMBED_COUNT, 0) embed_count += 1 setattr(formatter, EMBED_COUNT, embed_count) flowplayer_embedded = getattr(formatter, FLOWPLAYER_EMBEDDED, False) url = get_absolute_url(formatter.href.base, url) src = get_absolute_url(formatter.href.base, kwargs.pop('splash','htdocs://movie/movie/img/black.jpg')) scheme, netloc, path, params, query, fragment = urlparse(url) try: style_dict = xform_style(kwargs.get('style', '')) except: raise TracError('Double check the `style` argument.') style = { 'display': 'block', 'border': style_dict.get('border', 'none'), 'margin': style_dict.get('margin', '0 auto'), 'clear': 'both' } if netloc == 'www.youtube.com' or netloc == 'www.youtube-nocookie.com': query_dict = xform_query(query) video = query_dict.get('v') url = urlunparse((scheme, netloc, '/v/%s' % video, '', '', '')) width = kwargs.pop('width', style_dict.get('width', '425px')) height = kwargs.pop('height', style_dict.get('height', '344px')) style.update({ 'width': width, 'height': height, }) return tag.object(tag.param(name='movie', value=url), tag.param(name='allowFullScreen', value='true'), tag.embed(src=url, type='application/x-shockwave-flash', allowfullscreen='true', width=width, height=height), style=xform_style(style)) if netloc == 'video.google.com': query_dict = xform_query(query) query_dict['hl'] = 'en' query_dict['fs'] = 'true' query = xform_query(query_dict) url = urlunparse((scheme, netloc, '/googleplayer.swf', '', query, '')) width = kwargs.pop('width', style_dict.get('width', '400px')) height = kwargs.pop('height', style_dict.get('height', '326px')) style.update({ 'width': width, 'height': height, }) return tag.embed(src=url, allowFullScreen='true', allowScriptAccess='always', type='application/x-shockwave-flash', style=xform_style(style)) if netloc == 'www.metacafe.com': parts = path.split('/') try: path = '/fplayer/%s/%s.swf' % (parts[2], parts[3]) except: raise TracError("Non-standard URL, don't know how to process it, file a ticket please.") url = urlunparse((scheme, netloc, path, '', '', '')) width = kwargs.pop('width', style_dict.get('width', '400px')) height = kwargs.pop('height', style_dict.get('height', '345px')) style.update({ 'width': width, 'height': height, }) return tag.embed(src=url, wmode='transparent', pluginspage='http://www.macromedia.com/go/getflashplayer', type='application/x-shockwave-flash', style=xform_style(style)) # Requested by Zach, #4188. if netloc in ('vimeo.com', 'www.vimeo.com'): parts = path.split('/') while '' in parts: parts.remove('') path = '/moogaloop.swf?clip_id=%s&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1' % parts[0] url = urlunparse((scheme, netloc, path, '', '', '')) width = kwargs.pop('width', style_dict.get('width', '640px')) height = kwargs.pop('height', style_dict.get('height', '401px')) style.update({ 'width': width, 'height': height, }) return tag.object(tag.param(name='movie', value=url), tag.param(name='allowfullscreen', value='true'), tag.param(name='allowscriptaccess', value='always'), tag.embed(src=url, type='application/x-shockwave-flash', allowfullscreen='true', allowscriptaccess='always', width=width, height=height), style=xform_style(style)) # Local movies. tags = [] if not flowplayer_embedded: add_script(formatter.req, 'movie/js/flowplayer.min.js') add_script(formatter.req, 'movie/js/flowplayer.embed.min.js') add_script(formatter.req, 'movie/js/flashembed.min.js') script = ''' $(function() { $f("a.flowplayer","%s"); }); ''' % get_absolute_url(formatter.href.base, 'htdocs://movie/movie/swf/flowplayer.swf') tags.append(tag.script(script)) setattr(formatter, FLOWPLAYER_EMBEDDED, True) width = kwargs.pop('width', style_dict.get('width', '320px')) height = kwargs.pop('height', style_dict.get('height', '320px')) style.update({ 'width': width, 'height': height, }) if kwargs.pop('clear', None) == 'none': style.pop('clear') kwargs = {'style': xform_style(style)} tags.append(tag.a(tag.img(src=src, **kwargs), class_='flowplayer', href=url, **kwargs)) return ''.join([str(i) for i in tags])
def expand_macro(self, formatter, name, content): args, kwargs = parse_args(content, strict=True) kwargs = string_keys(kwargs) if len(args) >= 1: url = args[0] elif len(args) == 0: raise TracError('URL to a movie at least required.') embed_count = getattr(formatter, EMBED_COUNT, 0) embed_count += 1 setattr(formatter, EMBED_COUNT, embed_count) flowplayer_embedded = getattr(formatter, FLOWPLAYER_EMBEDDED, False) url = self._get_absolute_url(formatter.req, url) src = self._get_absolute_url( formatter.req, kwargs.pop('splash', 'htdocs://movie/img/black.jpg')) scheme, netloc, path, params, query, fragment = urlparse(url) try: style_dict = xform_style(kwargs.get('style', '')) except: raise TracError('Double check the `style` argument.') style = { 'display': 'block', 'border': style_dict.get('border', 'none'), 'margin': style_dict.get('margin', '0 auto'), 'clear': 'both' } if netloc == 'www.youtube.com' or netloc == 'www.youtube-nocookie.com': query_dict = xform_query(query) video = query_dict.get('v') url = urlunparse((scheme, netloc, '/v/%s' % video, '', '', '')) width = kwargs.pop('width', style_dict.get('width', '425px')) height = kwargs.pop('height', style_dict.get('height', '344px')) style.update({ 'width': width, 'height': height, }) return tag.object(tag.param(name='movie', value=url), tag.param(name='allowFullScreen', value='true'), tag.embed(src=url, type='application/x-shockwave-flash', allowfullscreen='true', width=width, height=height), style=xform_style(style)) if netloc == 'video.google.com': query_dict = xform_query(query) query_dict['hl'] = 'en' query_dict['fs'] = 'true' query = xform_query(query_dict) url = urlunparse( (scheme, netloc, '/googleplayer.swf', '', query, '')) width = kwargs.pop('width', style_dict.get('width', '400px')) height = kwargs.pop('height', style_dict.get('height', '326px')) style.update({ 'width': width, 'height': height, }) return tag.embed(src=url, allowFullScreen='true', allowScriptAccess='always', type='application/x-shockwave-flash', style=xform_style(style)) if netloc == 'www.metacafe.com': parts = path.split('/') try: path = '/fplayer/%s/%s.swf' % (parts[2], parts[3]) except: raise TracError( "Non-standard URL, don't know how to process it, file a ticket please." ) url = urlunparse((scheme, netloc, path, '', '', '')) width = kwargs.pop('width', style_dict.get('width', '400px')) height = kwargs.pop('height', style_dict.get('height', '345px')) style.update({ 'width': width, 'height': height, }) return tag.embed( src=url, wmode='transparent', pluginspage='http://www.macromedia.com/go/getflashplayer', type='application/x-shockwave-flash', style=xform_style(style)) # Requested by Zach, #4188. if netloc in ('vimeo.com', 'www.vimeo.com'): parts = path.split('/') while '' in parts: parts.remove('') path = '/moogaloop.swf?clip_id=%s&server=vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1' % parts[ 0] url = urlunparse((scheme, netloc, path, '', '', '')) width = kwargs.pop('width', style_dict.get('width', '640px')) height = kwargs.pop('height', style_dict.get('height', '401px')) style.update({ 'width': width, 'height': height, }) return tag.object(tag.param(name='movie', value=url), tag.param(name='allowfullscreen', value='true'), tag.param(name='allowscriptaccess', value='always'), tag.embed(src=url, type='application/x-shockwave-flash', allowfullscreen='true', allowscriptaccess='always', width=width, height=height), style=xform_style(style)) # Local movies. tags = [] if not flowplayer_embedded: add_script(formatter.req, 'movie/js/flashembed.min.js') add_script(formatter.req, 'movie/js/flow.embed.js') script = ''' $(function() { $("a.flowplayer").flowembed("%s", {initialScale:'scale'}); }); ''' % self._get_absolute_url( formatter.req, 'htdocs://movie/swf/FlowPlayerDark.swf') tags.append(tag.script(script)) setattr(formatter, FLOWPLAYER_EMBEDDED, True) width = kwargs.pop('width', style_dict.get('width', '320px')) height = kwargs.pop('height', style_dict.get('height', '320px')) style.update({ 'width': width, 'height': height, }) if kwargs.pop('clear', None) == 'none': style.pop('clear') kwargs = {'style': xform_style(style)} tags.append( tag.a(tag.img(src=src, **kwargs), class_='flowplayer', href=url, **kwargs)) return ''.join([str(i) for i in tags])