Beispiel #1
0
    def render_voter(self, req):
        resource = self.normalise_resource(req.path_info)

        count = self.get_vote_counts(resource)

        add_stylesheet(req, 'fivestarvote/css/fivestarvote.css')

        names = ['', 'one', 'two', 'three', 'four', 'five']
        els = []
        percent = 0
        if count[2] > 0:
            percent = count[2] * 20

        str = "Currently %s/5 stars." % count[2]
        sign = '%'
        style = "width: %s%s" % (percent, sign)
        li = tag.li(str, class_='current-rating', style=style)
        els.append(li)
        for i in range(1, 6):
            className = "item %s-star" % names[i]
            href = "#"
            if 'VOTE_MODIFY' in req.perm and get_reporter_id(req) != 'anonymous':
                href = req.href.fivestarvote(i, resource)
                add_script(req, 'fivestarvote/js/fivestarvote.js', mimetype='text/javascript')
            a = tag.a(i, href=href, class_=className)
            li = tag.li(a)
            els.append(li)
        
        ul = tag.ul(els, class_='star-rating')
        className = ''
        if 'VOTE_MODIFY' in req.perm and get_reporter_id(req) != 'anonymous':
            className = 'active'
        title = "Current Vote: %s users voted for a total of %s" % (count[1], count[0]) 
        add_ctxtnav(req, tag.span(tag.object(ul), id='fivestarvotes', title=title, class_=className))
Beispiel #2
0
    def render_reviewlink(self, req):
        #add_stylesheet(req, 'icucodetools/css/icuxtn.css')

        els = []

        ticket_mgr = TicketManager(self.compmgr)

        db = self.env.get_db_cnx()
        repos = self.env.get_repository()
        if not repos:
            raise TracError("Could not get repository for %s" % (req.authname))

        revs = ticket_mgr.tkt2revs(self.log, db, repos, req, req.args['ticket'])

        if not revs:
            str = 'No commits.'
            li = tag.li(str)
            els.append(li)
        else:
            str = ' %d commits.' % len(revs)
            href = req.href.review(req.args['ticket'])
            a = tag.a('Review', href=href)
            li = tag.li(a + str)
            els.append(li)            
        
        ul = tag.ul(els, class_='review')
        className = ''
        title = "Reviews"
        add_ctxtnav(req, tag.span(tag.object(ul), id='icureview', title=title, class_=className))
Beispiel #3
0
    def render_reviewlink(self, req):
        #add_stylesheet(req, 'icucodetools/css/icuxtn.css')

        els = []

        ticket_mgr = TicketManager(self.compmgr)

        db = self.env.get_db_cnx()
        repos = self.env.get_repository()
        if not repos:
            raise TracError("Could not get repository for %s" % (req.authname))

        revs = ticket_mgr.tkt2revs(self.log, db, repos, req,
                                   req.args['ticket'])

        if not revs:
            str = 'No commits.'
            li = tag.li(str)
            els.append(li)
        else:
            str = ' %d commits.' % len(revs)
            href = req.href.review(req.args['ticket'])
            a = tag.a('Review', href=href)
            li = tag.li(a + str)
            els.append(li)

        ul = tag.ul(els, class_='review')
        className = ''
        title = "Reviews"
        add_ctxtnav(
            req,
            tag.span(tag.object(ul),
                     id='icureview',
                     title=title,
                     class_=className))
Beispiel #4
0
    def produce_html(self, context, url, kwargs={}):
        attr = dict()
        attr['data'] = context.href.chrome('mindmap', 'visorFreemind.swf')
        attr['width'] = kwargs.pop('width', self.default_width)
        attr['height'] = kwargs.pop('height', self.default_height)
        try:
            int(attr['height'])
        except:
            pass
        else:
            attr['height'] += "px"
        try:
            int(attr['width'])
        except:
            pass
        else:
            attr['width'] += "px"

        flashvars = dict(
            [[k.strip(), v.strip()]
             for k, v in [kv.split('=') for kv in self.default_flashvars]])
        try:
            flashvars.update([[k.strip(), v.strip()] for k, v in [
                kv.split('=')
                for kv in kwargs['flashvars'].strip("\"'").split('|')
            ]])
        except:
            pass
        flashvars['initLoadFile'] = url

        css = ''
        if 'border' in kwargs:
            border = kwargs['border'].strip("\"'").replace(';', '')
            if border == "1":
                border = "solid"
            elif border == "0":
                border = "none"
            css = 'border: ' + border

        if self.resizable and (
            ('resizable' not in kwargs and self.default_resizable)
                or kwargs.get('resizable', 'false').lower() == "true"):
            class_ = "resizablemindmap mindmap"
        else:
            class_ = "mindmap"

        return tag.div(
            tag.object(tag.param(name="quality", value="high"),
                       tag.param(name="bgcolor", value="#ffffff"),
                       tag.param(name="flashvars",
                                 value=Markup("&".join([
                                     "=".join([k, unicode(v)])
                                     for k, v in flashvars.iteritems()
                                 ]))),
                       type="application/x-shockwave-flash",
                       **attr),
            class_=class_,
            style=Markup(css),
        )
Beispiel #5
0
    def produce_html(self, context, url, kwargs={}):
        attr = dict()
        attr['data']   = context.href.chrome('mindmap','visorFreemind.swf')
        attr['width']  = kwargs.pop('width',self.default_width)
        attr['height'] = kwargs.pop('height',self.default_height)
        try:
          int( attr['height'] )
        except:
          pass
        else:
          attr['height'] += "px"
        try:
          int( attr['width'] )
        except:
          pass
        else:
          attr['width'] += "px"

        flashvars = dict([ [k.strip(),v.strip()] for k,v in [ kv.split('=') for kv in self.default_flashvars]])
        try:
          flashvars.update([ [k.strip(),v.strip()] for k,v in [kv.split('=') for kv in kwargs['flashvars'].strip("\"'").split('|') ] ])
        except:
          pass
        flashvars['initLoadFile'] = url

        css  = ''
        if 'border' in kwargs:
          border = kwargs['border'].strip("\"'").replace(';','')
          if border == "1":
            border = "solid"
          elif border == "0":
            border = "none"
          css = 'border: ' + border

        if self.resizable and ( ('resizable' not in kwargs and self.default_resizable) or kwargs.get('resizable','false').lower() == "true" ):
          class_ = "resizablemindmap mindmap"
        else:
          class_ = "mindmap"

        return tag.div(
            tag.object(
                tag.param( name="quality", value="high" ),
                tag.param( name="bgcolor", value="#ffffff" ),
                tag.param( name="flashvars", value= Markup("&".join([ "=".join([k,unicode(v)]) for k,v in flashvars.iteritems() ]) )),
                type   = "application/x-shockwave-flash",
                **attr
            ),
            class_=class_,
            style=Markup(css),
        )
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)
    )
Beispiel #7
0
 def convert(self, data, dataSettings):
     if data is not None:
         if 'format' in dataSettings:
             format = dataSettings['format']
         else:
             format = 'png'
         color = dataSettings.get('color', True)
         imageSrc = '../moldb/showMol?margin=0&molId=%s&uid=%s&format=%s&color=%s' % (data['molId'],data['uid'], format, color)
         style = None
         if 'size' in dataSettings:
             style = "width:%spx;" % dataSettings['size']
         if format == 'svg':
             return tag.object(data=imageSrc,type="image/svg+xml", style=style)
         elif format == 'emf':
             # For IE copy/paste reasons, we will pass a width query parameter
             # rather than using a style setting.  That way the copy from IE to
             # MS Office products will faithfully preserve the image size in the
             # table.
             if 'size' in dataSettings:
                 dim=dataSettings['size']
                 imageSrc='%s&width=%s&height=%s' % (imageSrc, str(int(2*dim)), dim)
             return tag.img(src=imageSrc)
     else:
         return ""
Beispiel #8
0
    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"))
Beispiel #9
0
    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"))
Beispiel #10
0
	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"))
Beispiel #11
0
    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"))
Beispiel #12
0
    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"))
Beispiel #13
0
 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&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;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])
Beispiel #14
0
    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&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;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])