Esempio n. 1
0
    def filter_stream(self, req, method, filename, stream, data):
        crumbs = self._get_crumbs(req.session)
        if not crumbs:
            return stream

        add_stylesheet(req, 'breadcrumbs/css/breadcrumbs.css')
        ul = []

        href = req.href(req.base_path)

        for crumb in crumbs:
            realm, resource = crumb.split('/', 1)
            name = resource.replace('_', ' ')

            if realm == "ticket":
                name = "#" + resource
            elif realm != "wiki":
                name = "%s:%s" % (realm, name)

            link = req.href(realm, resource)

            first = ul == []
            li = tag.li(tag.a(title=name, href=link)(name))
            if first:
                li(class_="first")
            ul.append(li)

        last = ul.pop()
        ul.append(last(class_="last"))
        insert = tag.ul(class_="nav", id="breadcrumbs"
                     )(tag.li(self.label and self.label or \
                              "Breadcrumbs:"), ul)

        return stream | Transformer('//div[@id="metanav"]/ul').after(insert)
Esempio n. 2
0
  def expand_macro(self,formatter,name,content):
    citelist = getattr(formatter, CITELIST,[])
    columns = ['itemTypeID','firstCreator','year', 'publicationTitle','volume','issue','pages','title','url']
    model = ZoteroModelProvider(self.env)
    item_ids = model.get_items_ids_by_keys( citelist )
    item_data = model.get_item_columns_by_iids(item_ids,columns)
    refs = []

    for itemID, itemTypeID, firstCreator, year, publicationTitle, volume, issue, pages, title, url in item_data:
        prefix = ''
        if firstCreator and firstCreator != 'None':
            prefix += firstCreator
        if year and year != 'None':
            prefix += ' ' + year + '. '
        titlehref = ''
        if title and title != 'None':
            titlehref = tag.a(title, href = formatter.req.href.zotero('item/' + str(itemID)))
        suffix = ''
        if publicationTitle and publicationTitle != 'None':
            suffix += '. ' + publicationTitle
        if volume and volume != 'None':
            suffix += ', ' + str(volume)
        if pages and pages != 'None':
            suffix += ': ' + pages + '.'
        ref = []
        if url and url != 'None':
            ref = tag.li( tag.span( prefix ), tag.span(titlehref), tag.span(suffix),
                    tag.br(),tag.span(tag.a(url, href=url ),style = 'font-size:x-small;') )
        else: 
            ref = tag.li( tag.span( prefix ), tag.span(titlehref), tag.span(suffix) )
    
        refs.append(ref)

    return tag.div(tag.ol(refs),id='References')
Esempio n. 3
0
    def get_html(self, total, horas_semanas):
        valor_hora = self.data['valor_hora']
        text = ['Horas trabajadas: %.2f' % total,
                'Precio en dolares (U$S%s): %.2f' % (valor_hora, total * valor_hora)]
        text.extend(['Horas semana %s: %.2f' % (nro+1, horas) for nro, horas in horas_semanas.items()])
        div = tag.div()
        ul = tag.ul()
        for li in text:
            ul.append(tag.li(li))

        if 'date' in self.data:
            link = tag.a('@netlandish: Grinch report',
                         href=self._get_grinch_report_url())
            ul.append(link)
        div.append(ul)

        img = tag.img(src=self._get_google_chart(horas_semanas))
        div.append(img)

        ul = tag.ul()
        for project, hours in self.hours.iteritems():
            ul.append(tag.li('{0}: {1}'.format(project.title(), hours)))
        div.append(ul)

        return div
Esempio n. 4
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))
Esempio n. 5
0
    def filter_stream(self, req, method, filename, stream, data):
        project_id = self.env.config.get('por-dashboard', 'project-id')
        if project_id:
            project = DBSession().query(Project).get(project_id)
            # XXX se project is None, 404

            stream |= Transformer(".//div[@id='trac-before-subnav']").prepend(tag.ul(
                    tag.li(tag.a("Home", href="/")),
                    tag.li(
                            tag.span(" / ", class_="divider"),
                            tag.a(project.customer.name, href="/admin/Customer/%s" % project.customer.id)
                        ),
                    tag.li(
                            tag.span(" / ", class_="divider"),
                            tag.a(project.name, href="/admin/Project/%s" % project.id)
                        ),
                    tag.li(
                            tag.span(" / ", class_="divider"),
                            tag.a('Trac', href="/trac/%s" % project.id),
                            class_='active'
                        ),
                    class_="breadcrumb noprint",
                ))

        return stream
Esempio n. 6
0
    def expand_macro(self, formatter, name, content):
        env = formatter.env
        req = formatter.req
        if not 'VOTE_VIEW' in req.perm:
            return
        # Simplify function calls.
        format_author = partial(Chrome(self.env).format_author, req)
        if not content:
            args = []
            compact = None
            kw = {}
            top = 5
        else:
            args, kw = parse_args(content)
            compact = 'compact' in args and True
            top = as_int(kw.get('top'), 5, min=0)

        if name == 'LastVoted':
            lst = tag.ul()
            for i in self.get_votes(req, top=top):
                resource = Resource(i[0], i[1])
                # Anotate who and when.
                voted = ('by %s at %s'
                         % (format_author(i[3]),
                            format_datetime(to_datetime(i[4]))))
                lst(tag.li(tag.a(
                    get_resource_description(env, resource, compact and
                                             'compact' or 'default'),
                    href=get_resource_url(env, resource, formatter.href),
                    title=(compact and '%+i %s' % (i[2], voted) or None)),
                    (not compact and Markup(' %s %s' % (tag.b('%+i' % i[2]),
                                                        voted)) or '')))
            return lst

        elif name == 'TopVoted':
            realm = kw.get('realm')
            lst = tag.ul()
            for i in self.get_top_voted(req, realm=realm, top=top):
                if 'up-only' in args and i[2] < 1:
                    break
                resource = Resource(i[0], i[1])
                lst(tag.li(tag.a(
                    get_resource_description(env, resource, compact and
                                             'compact' or 'default'),
                    href=get_resource_url(env, resource, formatter.href),
                    title=(compact and '%+i' % i[2] or None)),
                    (not compact and ' (%+i)' % i[2] or '')))
            return lst

        elif name == 'VoteList':
            lst = tag.ul()
            resource = resource_from_path(env, req.path_info)
            for i in self.get_votes(req, resource, top=top):
                vote = ('at %s' % format_datetime(to_datetime(i[4])))
                lst(tag.li(
                    compact and format_author(i[3]) or
                    Markup(u'%s by %s %s' % (tag.b('%+i' % i[2]),
                                             tag(format_author(i[3])), vote)),
                    title=(compact and '%+i %s' % (i[2], vote) or None)))
            return lst
Esempio n. 7
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))
Esempio n. 8
0
def outline_tree(env, ol, outline, context, active, min_depth, max_depth):
    if min_depth > max_depth:
        min_depth, max_depth = max_depth, min_depth
    max_depth = min(6, max_depth)
    min_depth = max(1, min_depth)
    previous_depth = min_depth
    
    stack = [None] * (max_depth + 1)
    # stack of (<element for new sublists>, <element for new items>)
    stack[previous_depth] = (None, ol)
    
    for depth, anchor, heading in outline:
        if min_depth <= depth <= max_depth:
            for d in range(previous_depth, depth):
                li, ol = stack[d]
                if not li:
                    li = tag.li()
                    ol.append(li)
                    stack[d] = (li, ol)
                new_ol = tag.ol()
                li.append(new_ol)
                stack[d+1] = (None, new_ol)
            href = get_resource_url(env, context.resource, context.href)
            if href.endswith(context.req.path_info):
                href = ''
            href += '#' + anchor
            li, ol = stack[depth]
            li = tag.li(tag.a(Markup(heading), href=href),
                        class_=active and 'active' or None)
            ol.append(li)
            stack[depth] = (li, ol)
            previous_depth = depth
    return stack[min_depth][0]
Esempio n. 9
0
 def display(self, toc, ul):
     for name, title, sub in toc:
         if sub == None:
             ul.append(tag.li(
                     Markup(title),
                     class_= (name == self.curpage) and "active" or None))
         else:
             show_dots = not (name == None or sub)
             ul.append(tag.li(
                     tag.h4(Markup(title), show_dots and "..." or None)))
             if len(sub) > 0:
                 ul.append(self.display(sub, tag.ul()))
     return ul
Esempio n. 10
0
    def _wiki_view(self, req, stream):
        tags = self._page_tags(req)
        if not tags:
            return stream
        tag_system = TagSystem(self.env)
        add_stylesheet(req, 'tags/css/tractags.css')
        li = []
        for tag_ in tags:
            resource = Resource('tag', tag_)
            anchor = render_resource_link(self.env,
                Context.from_request(req, resource), resource)
            li.append(tag.li(anchor, ' '))

        insert = tag.ul(class_='tags')(tag.li('Tags', class_='header'), li)
        return stream | Transformer('//div[@class="buttons"]').before(insert)
Esempio n. 11
0
    def filter_stream(self, req, method, filename, stream, data):
        crumbs = self._get_crumbs(req.session)
        if not crumbs:
            return stream

        add_stylesheet(req, 'breadcrumbs/css/breadcrumbs.css')
        ul = []

        path = req.path_info
        if path.count('/') >= 2:
            _, realm, resource = path.split('/', 2)
            if '&' in resource:
                resource = resource[0:resource.index('&')]
            current = '/'.join( (realm, resource) )
        else:
            current = None

        href = req.href(req.base_path)
        offset = 0
        if crumbs and crumbs[0] == current:
            offset = 1
        for crumb in crumbs[offset:self.max_crumbs + offset]:
            realm, resource = crumb.split('/', 1)
            name = resource.replace('_', ' ')

            if realm == "ticket":
                name = "#" + resource
            elif realm != "wiki":
                name = "%s:%s" % (realm, name)

            link = req.href(realm, resource)

            first = ul == []
            li = tag.li(tag.a(title=name, href=link)(name))
            if first:
                li(class_="first")
            ul.append(li)

        if ul:
            last = ul.pop()
            ul.append(last(class_="last"))
            insert = tag.ul(class_="nav", id="breadcrumbs"
                     )(tag.li(self.label and self.label or \
                              "Breadcrumbs:"), ul)
        else:
            insert = ''

        return stream | Transformer('//div[@id="metanav"]/ul').after(insert)
Esempio n. 12
0
    def _wiki_view(self, req, stream):
        tags = self._page_tags(req)
        if not tags:
            return stream
        tag_system = TagSystem(self.env)
        add_stylesheet(req, 'tags/css/tractags.css')
        li = []
        for tag_ in tags:
            resource = Resource('tag', tag_)
            anchor = render_resource_link(self.env,
                                          Context.from_request(req, resource),
                                          resource)
            li.append(tag.li(anchor, ' '))

        insert = tag.ul(class_='tags')(tag.li('Tags', class_='header'), li)
        return stream | Transformer('//div[@class="buttons"]').before(insert)
Esempio n. 13
0
    def expand_macro(self, formatter, name, args):
        curpage = formatter.resource.id

        # scoped TOC (e.g. TranslateRu/Guide or 0.X/Guide ...)
        prefix = ''
        guideprefix = GUIDE_NAME + '/'
        data = {
            'guide': GUIDE_NAME,
        }
        idx = curpage.find('/')
        if idx > 0:
            prefix = curpage[:idx + 1]
        if prefix.endswith(guideprefix):
            prefix = prefix[:len(prefix) - len(guideprefix)]
        ws = WikiSystem(self.env)
        return tag.div(
            tag.h4(_('Table of Contents')),
            tag.ul([
                tag.li(tag.a(title,
                             href=formatter.href.wiki(prefix + ref % data),
                             class_=(not ws.has_page(prefix + ref % data)
                                     and 'missing')),
                       class_=(prefix + ref % data == curpage and 'active'))
                for ref, title in self.TOC
            ]),
            class_='wiki-toc')
Esempio n. 14
0
 def render_group(group):
     return tag.ul(
         tag.li(tag(tag.strong(elt[0].strip('/')), render_group(elt[1]))
                if isinstance(elt, tuple) else
                tag.a(wiki.format_page_name(omitprefix(elt)),
                      href=formatter.href.wiki(elt)))
         for elt in group)
Esempio n. 15
0
 def render_group(group):
     return tag.ul(
         tag.li(isinstance(elt, tuple) and 
                tag(tag.strong(elt[0]), render_group(elt[1])) or
                tag.a(wiki.format_page_name(elt),
                      href=formatter.href.wiki(elt)))
         for elt in group)
Esempio n. 16
0
 def render_group(group):
     return tag.ul(
         tag.li(isinstance(elt, tuple) and 
                tag(tag.strong(elt[0]), render_group(elt[1])) or
                tag.a(wiki.format_page_name(elt),
                      href=formatter.href.wiki(elt)))
         for elt in group)
Esempio n. 17
0
 def render_group(group):
     return tag.ul(
         tag.li(
             tag(tag.strong(elt[0].strip('/')), render_group(elt[1])
                 ) if isinstance(elt, tuple) else tag.
             a(wiki.format_page_name(omitprefix(elt)),
               href=formatter.href.wiki(elt))) for elt in group)
Esempio n. 18
0
    def _reminder_tags(self, req, data):
        if 'ticket' not in data or not data['ticket'].id:
            return None

        ticket = data['ticket']

        if ticket['status'] == 'closed':
            return None

        li_tags = [tag.li(self._format_reminder(req, ticket, *args)) for args in self._get_reminders(ticket.id)]
        if li_tags:
            list_tags = tag.ul(li_tags, class_="reminders")
        else:
            list_tags = []

        add_form = self._reminder_add_form(req)

        if not list_tags and not add_form:
            return None

        return \
            tag.div(
                tag.h2("Reminders", class_="foldable"),
                tag.div(
                    list_tags,
                    add_form,
                ),
                id="reminders",
            )
Esempio n. 19
0
    def expand_macro(self, formatter, name, content):
        attachment_type = ""
        if content:
            argv = [arg.strip() for arg in content.split(',')]
            if len(argv) > 0:
                attachment_type = argv[0]

        db = self.env.get_db_cnx()
        if db == None:
           return "No DB connection"
        
        attachmentFormattedList=""

        cursor = db.cursor()

        if attachment_type == None or attachment_type == "":
            cursor.execute("SELECT type,id,filename,size,time,"
                           "description,author,ipnr FROM attachment")
        else:
            cursor.execute("SELECT type,id,filename,size,time,"
                           "description,author,ipnr FROM attachment "
                           "WHERE type=%s", (attachment_type, ))
        
        formatters={"wiki": formatter.href.wiki, "ticket": formatter.href.ticket}
        types={"wiki": "", "ticket": "ticket "}

        return tag.ul(
                      [tag.li(
                          tag.a(filename, href=formatter.href.attachment(type + "/" + id + "/" + filename)), 
                          " (", tag.span(pretty_size(size), title=size), ") - added by ",
                          tag.em(author), " to ",
                          tag.a(types[type] + " " + id, href=formatters[type](id)), " ")
                    for type,id,filename,size,time,description,author,ipnr in cursor if self._has_perm(type, id, filename, formatter.context)])

        return attachmentFormattedList
Esempio n. 20
0
 def _process_view(self, req, stream, method, tags):
     stage = 1
     div_count = 1
     
     def tag_data():
         engine = TagEngine(self.env)
         for t in tags:
             href, title = engine.get_tag_link(t)
             yield t, href, title
     
     elm = tag.ul(tags and tag.lh('Tags'),
                  [tag.li(tag.a(t, href=href, title=title), ' ') for t, href, title in tag_data()],
                  class_='tags')
                  
     for kind, data, pos in stream:
         yield kind, data, pos
         if stage == 1 and \
            kind is START and \
            data[0].localname == 'div' and \
            'wikipage' in data[1].get('class', ''):
             stage = 2
         elif stage == 2:
             if kind is START and data[0].localname == 'div':
                 div_count += 1
             elif kind is END and data.localname == 'div':
                 div_count -= 1
                 
             if not div_count:
                 for e in elm.generate():
                     yield e
                 stage = None
Esempio n. 21
0
    def _reminder_tags(self, req, data):
        if 'ticket' not in data or not data['ticket'].id:
            return None

        ticket = data['ticket']

        if ticket['status'] == 'closed':
            return None

        li_tags = [tag.li(self._format_reminder(req, ticket, *args)) for args in self._get_reminders(ticket.id)]
        if li_tags:
            list_tags = tag.ul(li_tags, class_="reminders")
        else:
            list_tags = []

        add_form = self._reminder_add_form(req)

        if not list_tags and not add_form:
            return None

        return \
            tag.div(
                tag.h2("Reminders", class_="foldable"),
                tag.div(
                    list_tags,
                    add_form,
                ),
                id="reminders",
            )
Esempio n. 22
0
def render_cloud(env, req, cloud, renderer=None):
    """Render a tag cloud

    :cloud: Dictionary of {object: count} representing the cloud.
    :param renderer: A callable with signature (tag, count, percent) used to
                     render the cloud objects.
    """
    min_px = 10.0
    max_px = 30.0
    scale = 1.0

    if renderer is None:
        def default_renderer(tag, count, percent):
            href = get_resource_url(env, Resource('tag', tag), req.href)
            return builder.a(tag, rel='tag', title='%i' % count, href=href,
                             style='font-size: %ipx' %
                                   int(min_px + percent * (max_px - min_px)))
        renderer = default_renderer

    # A LUT from count to n/len(cloud)
    size_lut = dict([(c, float(i)) for i, c in
                     enumerate(sorted(set([r for r in cloud.values()])))])
    if size_lut:
        scale = 1.0 / len(size_lut)

    ul = builder.ul(class_='tagcloud')
    last = len(cloud) - 1
    for i, (tag, count) in enumerate(sorted(cloud.iteritems())):
        percent = size_lut[count] * scale
        li = builder.li(renderer(tag, count, percent))
        if i == last:
            li(class_='last')
        li()
        ul(li)
    return ul
Esempio n. 23
0
    def handle_edit_locale_admins(self, req, locale_id):
        if not locale_id:
            req.redirect(req.href.admin('translations', 'locales'))

        Session = session(self.env)
        locale = Session.query(Locale).get(int(locale_id))
        known_users = self.env.get_known_users()
        errors = []
        perm = PermissionSystem(self.env)
        sids_without_necessary_perms = []
        for admin in locale.admins:
            if not 'L10N_MODERATE' in perm.get_user_permissions(admin.sid):
                sids_without_necessary_perms.append(admin.sid)

        if sids_without_necessary_perms:
            msg = ngettext(
                "%s does not have the required permissions to administrate." % \
                ', '.join(["'%s'" % s for s in sids_without_necessary_perms]),
                "%s don't have the required permissions to administrate." % \
                ', '.join(["'%s'" % s for s in sids_without_necessary_perms]),
                 len(sids_without_necessary_perms))
            errors.append(
                tag(msg, _(" Don't forget to "),
                    tag.a(_('update permissions'),
                          href=req.href.admin('general', 'perm')), '.'))

        if req.method == 'POST' and len(req.args.getlist('admins')) >= 1:
            current_admins = req.args.getlist('current_admins')
            selected = req.args.getlist('admins')

            self.log.debug('Current Admins: %s', current_admins)
            self.log.debug('Selected Admins: %s', selected)

            allow_delete_admins = len(selected) >= 1
            if not allow_delete_admins:
                errors.append(
                    tag(_("There must be at least on admin for each locale.")))

            for admin in current_admins:
                if not allow_delete_admins:
                    break
                if admin not in selected:
                    locale_admin = Session.query(LocaleAdmin). \
                        filter(locale_admin_table.c.sid==admin).first()
                    Session.delete(locale_admin)
            for admin in selected:
                if admin not in locale.admins:
                    locale.admins.append(LocaleAdmin(locale, admin))
            Session.commit()
            req.redirect(req.href.admin('translations', 'locales'))
        elif req.method == 'POST' and len(req.args.getlist('admins')) < 1:
            errors.append(
                tag(_("There must be at least on admin for each locale.")))

        data = {'locale': locale, 'known_users': known_users}
        if errors:
            data['error'] = tag.ul(*[tag.li(e) for e in errors if e])

        return 'l10n_admin_locale_admins.html', data
Esempio n. 24
0
    def expand_macro(self, formatter, name, content):
        args, kw = parse_args(content)
        page = kw.get('page', '')
        sort = kw.get('sort', 'DESC')
        order = kw.get('order', 'time')

        self.env.log.error('sort %s, order %s' % (sort, order))

        attachment_type = ""
        wiki_path = ""
        if content:
            argv = [arg.strip() for arg in content.split(',')]
            if len(argv) > 0:
                attachment_type = argv[0]

        db = self.env.get_db_cnx()
        if db == None:
            return "No DB connection"

        attachmentFormattedList = ""

        cursor = db.cursor()

        if attachment_type == None or attachment_type == "":
            cursor.execute("SELECT type,id,filename,size,time,description,"
                           "author,ipnr FROM attachment")

        elif page == None or page == "":
            cursor.execute(
                "SELECT type,id,filename,size,time,description,"
                "author,ipnr FROM attachment WHERE type=%s ORDER "
                "BY " + order + " " + sort, (attachment_type, ))

        else:
            cursor.execute(
                "SELECT type,id,filename,size,time,description,"
                "author,ipnr FROM attachment WHERE type=%s and "
                "id=%s ORDER BY " + order + " " + sort,
                (attachment_type, page))

        formatters = {
            "wiki": formatter.href.wiki,
            "ticket": formatter.href.ticket
        }
        types = {"wiki": "", "ticket": "ticket "}

        return tag.ul([
            tag.li(
                tag.a(filename,
                      href=formatter.href.attachment(type + "/" + id + "/" +
                                                     filename)), " (",
                tag.span(pretty_size(size), title=size), ") - ",
                tag.em(format_datetime(time)), " - added by ", tag.em(author),
                " to ", tag.a(types[type] + " " + id,
                              href=formatters[type](id)), " ") for type, id,
            filename, size, time, description, author, ipnr in cursor
        ])

        return attachmentFormattedList
Esempio n. 25
0
 def _render_externals(self, prop):
     if not self._externals_map:
         for dummykey, value in self.svn_externals_section.options():
             value = value.split()
             if len(value) != 2:
                 self.log.warn(
                     "svn:externals entry %s doesn't contain " "a space-separated key value pair, skipping.",
                     dummykey,
                 )
                 continue
             key, value = value
             self._externals_map[key] = (
                 value.replace("%", "%%").replace("$path", "%(path)s").replace("$rev", "%(rev)s")
             )
     externals = []
     for external in prop.splitlines():
         elements = external.split()
         if not elements:
             continue
         localpath, rev, url = elements[0], "", elements[-1]
         if localpath.startswith("#"):
             externals.append((external, None, None, None, None))
             continue
         if len(elements) == 3:
             rev = elements[1]
             rev = rev.replace("-r", "")
         # retrieve a matching entry in the externals map
         prefix = []
         base_url = url
         while base_url:
             if base_url in self._externals_map or base_url == u"/":
                 break
             base_url, pref = posixpath.split(base_url)
             prefix.append(pref)
         href = self._externals_map.get(base_url)
         revstr = " at revision " + rev if rev else ""
         if not href and (url.startswith("http://") or url.startswith("https://")):
             href = url.replace("%", "%%")
         if href:
             remotepath = ""
             if prefix:
                 remotepath = posixpath.join(*reversed(prefix))
             externals.append((localpath, revstr, base_url, remotepath, href % {"path": remotepath, "rev": rev}))
         else:
             externals.append((localpath, revstr, url, None, None))
     externals_data = []
     for localpath, rev, url, remotepath, href in externals:
         label = localpath
         if url is None:
             title = ""
         elif href:
             if url:
                 url = " in " + url
             label += rev + url
             title = "".join((remotepath, rev, url))
         else:
             title = _("No svn:externals configured in trac.ini")
         externals_data.append((label, href, title))
     return tag.ul([tag.li(tag.a(label, href=href, title=title)) for label, href, title in externals_data])
Esempio n. 26
0
    def _wiki_view(self, req, stream):
        add_stylesheet(req, 'tags/css/tractags.css')
        tags = self._page_tags(req)
        if not tags:
            return stream
        li = []
        for tag_ in tags:
            resource = Resource('tag', tag_)
            anchor = render_resource_link(self.env, web_context(req, resource),
                                          resource)
            anchor = anchor(rel='tag')
            li.append(tag.li(anchor, ' '))

        # TRANSLATOR: Header label text for tag list at wiki page bottom.
        insert = tag.ul(class_='tags')(tag.li(_("Tags"), class_='header'), li)
        return stream | (
            Transformer('//div[contains(@class,"wikipage")]').after(insert))
Esempio n. 27
0
    def _wiki_view(self, req, stream):
        add_stylesheet(req, 'tags/css/tractags.css')
        tags = self._page_tags(req)
        if not tags:
            return stream
        li = []
        for tag_ in tags:
            resource = Resource('tag', tag_)
            anchor = render_resource_link(self.env,
                Context.from_request(req, resource), resource)
            anchor = anchor(rel='tag')
            li.append(tag.li(anchor, ' '))

        # TRANSLATOR: Header label text for tag list at wiki page bottom.
        insert = tag.ul(class_='tags')(tag.li(_("Tags"), class_='header'), li)
        return stream | (Transformer('//div[contains(@class,"wikipage")]')
                         .after(insert))
Esempio n. 28
0
 def render_hierarchy(group):
     return tag.ul(
         tag.li(isinstance(elt, tuple) and 
                tag(tag.a(elt[0], href=formatter.href.wiki(elt[0])),
                    render_hierarchy(elt[1][0:])) or
                tag.a(rpartition(elt, '/')[2],
                      href=formatter.href.wiki(elt)))
         for elt in group)
Esempio n. 29
0
 def render_hierarchy(group):
     return tag.ul(
         tag.li(tag(tag.a(elt[0], href=formatter.href.wiki(elt[1]))
                    if elt[1] else tag(elt[0]),
                    render_hierarchy(elt[2]))
                if len(elt) == 3 else
                tag.a('/'.join(elt[0]),
                      href=formatter.href.wiki(elt[1])))
         for elt in group)
Esempio n. 30
0
 def render_node(self, node, formatter):
     html = tag.li(tag.a(node.title,href=node.href))
     if node.children and len(node.children):
         html_children = [self.render_node(child, formatter) for child in node.children];
         if node.isroot:
             html += html_children
         else:
             html += tag.ul(html_children)
     return html
Esempio n. 31
0
 def render_child_col(self, req, col_root, model ):
     node_ul = tag.ul()
     for id, name, pid, ischildcol, ischilditem in col_root:
         node_li = tag.li( tag.a( name, href = req.href.zotero('collection/'+str(id))) )
         if ischildcol:
             child_col = model.get_child_collections(id)
             node_li.append( self.render_child_col(req, child_col, model) )
         node_ul.append(node_li)
     return node_ul 
Esempio n. 32
0
 def render_hierarchy(group):
     return tag.ul(
         tag.li(tag(tag.a(elt[0], href=formatter.href.wiki(elt[1]))
                    if elt[1] else tag(elt[0]),
                    render_hierarchy(elt[2]))
                if len(elt) == 3 else
                tag.a('/'.join(elt[0]),
                      href=formatter.href.wiki(elt[1])))
         for elt in group)
Esempio n. 33
0
    def expand_macro(self, formatter, name, content):
        prefix = limit = None
        if content:
            argv = [arg.strip() for arg in content.split(',')]
            if len(argv) > 0:
                prefix = argv[0]
                if len(argv) > 1:
                    limit = int(argv[1])

        cursor = formatter.db.cursor()

        sql = 'SELECT name, ' \
              '  max(version) AS max_version, ' \
              '  max(time) AS max_time ' \
              'FROM wiki'
        args = []
        if prefix:
            sql += ' WHERE name LIKE %s'
            args.append(prefix + '%')
        sql += ' GROUP BY name ORDER BY max_time DESC'
        if limit:
            sql += ' LIMIT %s'
            args.append(limit)
        cursor.execute(sql, args)

        entries_per_date = []
        prevdate = None
        for name, version, ts in cursor:
            if not 'WIKI_VIEW' in formatter.perm('wiki', name, version):
                continue
            time = datetime.fromtimestamp(ts, utc)
            date = format_date(time)
            if date != prevdate:
                prevdate = date
                entries_per_date.append((date, []))
            version = int(version)
            diff_href = None
            if version > 1:
                diff_href = formatter.href.wiki(name, action='diff',
                                                version=version)
            page_name = formatter.wiki.format_page_name(name)
            entries_per_date[-1][1].append((page_name, name, version,
                                            diff_href))

        return tag.div([tag.h3(date) +
                        tag.ul([tag.li(tag.a(page_name,
                                             href=formatter.href.wiki(name)),
                                       ' ',
                                       diff_href and 
                                       tag.small('(', tag.a('diff',
                                                            href=diff_href),
                                                 ')') or
                                       None)
                                for page_name, name, version, diff_href
                                in entries])
                        for date, entries in entries_per_date])
Esempio n. 34
0
 def render_list(self, req, data, hacks):
     ul = builder.ul()
     for votes, rank, resource, tags, title in sorted(hacks, key=lambda h: h[2].id):
         li = builder.li(builder.a(resource.id,
                                   href=req.href.wiki(resource.id)),
                         ' - ', title)
         ul(li)
     data['body'] = ul
     # TODO Top-n + sample
     return 'hacks_view.html', data, None
Esempio n. 35
0
 def filter_stream(self, req, method, filename, stream, data):
     
     if req.path_info.startswith('/wiki/'):
         if data and data.has_key('page') and hasattr(data['page'], 'resource'):
             title = data['title']
             filter = Transformer('//div[@id="pagepath"]')
             filter = filter.empty()
             filter = filter.append( tag.a( 'wiki:', href = req.href.wiki(), class_ = 'pathentry first' ) )
            
             resource = data['page'].resource
             relation_system = ResourceRelationSystem(self.env)
             tree = relation_system.get_cached_tree(req)    
             add_stylesheet(req, 'wikimenu/css/superfish.css')
             add_script(req, 'wikimenu/js/jquery.bgiframe.min.js')
             add_script(req, 'wikimenu/js/superfish.js')
             add_script(req, 'wikimenu/js/popup.js')
             resources = []
             for res in relation_system.get_ancestors(resource, tree=tree):
                 resources.append(res)
             for res in reversed( resources ):
                 label = get_resource_description(self.env, res)
                 if res.realm=='wiki':
                     if res.id and WikiSystem(self.env).has_page(res.id):
                         
                         menu = tag.ul( )
                                                     
                         for res_child in relation_system.get_children(res):
                             child_label = get_resource_description(self.env, res_child)
                             if res_child.realm=='wiki':
                                 if res_child.id and WikiSystem(self.env).has_page(res_child.id):
                                     anc = tag.a(child_label, href = req.href.wiki(child_label))
                                     menu.append(tag.li( anc ))
                                     
                         
                         filter = filter.append( tag.ul( tag.li( 
                             tag.a(label, href=req.href.wiki(label) ),
                                 menu ), class_= 'wiki_menu' ) )
                         if title != label:
                             filter = filter.append( tag.span( ' / ', 
                                     class_ = 'pathentry sep' ) )
             remove_tran = '//a[@title="View ' + title + '"]'
             return stream | filter
     return stream
Esempio n. 36
0
    def expand_macro(self, formatter, name, content):
        req = formatter.req
        query_result = TagSystem(self.env).query(req, content)

        def link(resource):
            return render_resource_link(self.env, formatter.context, resource,
                                        'compact')

        ul = builder.ul(class_='taglist')
        # Beware: Resources can be Unicode strings.
        for resource, tags in sorted(query_result, key=lambda r: r[0].id):
            tags = sorted(tags)
            if tags:
                rendered_tags = [link(resource('tag', tag)) for tag in tags]
                li = builder.li(link(resource), ' (', rendered_tags[0],
                                [(' ', tag) for tag in rendered_tags[1:]], ')')
            else:
                li = builder.li(link(resource))
            ul(li, '\n')
        return ul
Esempio n. 37
0
 def render_node(self, node, formatter):
     html = tag.li(tag.a(node.title, href=node.href))
     if node.children and len(node.children):
         html_children = [
             self.render_node(child, formatter) for child in node.children
         ]
         if node.isroot:
             html += html_children
         else:
             html += tag.ul(html_children)
     return html
Esempio n. 38
0
    def render_cloud(self, req, cloud, renderer=None, caseless_sort=False,
                     mincount=None, realms=()):
        """Render a tag cloud.

        :cloud: Dictionary of {object: count} representing the cloud.
        :param renderer: A callable with signature (tag, count, percent)
                         used to render the cloud objects.
        :param caseless_sort: Boolean, whether tag cloud should be sorted
                              case-sensitive.
        :param mincount: Integer threshold to hide tags with smaller count.
        """
        min_px = 10.0
        max_px = 30.0
        scale = 1.0

        if renderer is None:
            def default_renderer(tag, count, percent):
                href = self.get_href(req, realms, tag=Resource('tag', tag))
                return builder.a(tag, rel='tag', title='%i' % count,
                                 href=href, style='font-size: %ipx'
                                 % int(min_px + percent * (max_px - min_px)))
            renderer = default_renderer

        # A LUT from count to n/len(cloud)
        size_lut = dict([(c, float(i)) for i, c in
                         enumerate(sorted(set([r for r in cloud.values()])))])
        if size_lut:
            scale = 1.0 / len(size_lut)

        if caseless_sort:
            # Preserve upper-case precedence within similar tags.
            items = reversed(sorted(cloud.iteritems(),
                                    key=lambda t: t[0].lower(), reverse=True))
        else:
            items = sorted(cloud.iteritems())
        ul = li = None
        for i, (tag, count) in enumerate(items):
            percent = size_lut[count] * scale
            if mincount and count < as_int(mincount, 1):
                # Tag count is too low.
                continue
            if ul:
                # Found new tag for cloud; now add previously prepared one. 
                ul('\n', li)
            else:
                # Found first tag for cloud; now create the list.
                ul = builder.ul(class_='tagcloud')
            # Prepare current tag entry.
            li = builder.li(renderer(tag, count, percent))
        if li:
            # All tags checked; mark latest tag as last one (no tailing colon).
            li(class_='last')
            ul('\n', li, '\n')
        return ul and ul or _("No tags found")
Esempio n. 39
0
 def _create_milestone_item(self, milestone):
     icon = tag.span(tag.span('', class_='ui-icon %s' %
                                         self.mod.milestone_icon or ''),
                     class_='ui-icon-w')
     anchor = tag.a(milestone.name,
                    href=self.req.href('milestone', milestone.name))
     item = tag.li(icon, anchor,
                   style='background-color: %s;' %
                         self.mod.milestone_background_color,
                   class_='milestone')
     return item
Esempio n. 40
0
    def render_cloud(self, req, cloud, renderer=None, caseless_sort=False,
                     mincount=None, realms=()):
        """Render a tag cloud.

        :cloud: Dictionary of {object: count} representing the cloud.
        :param renderer: A callable with signature (tag, count, percent)
                         used to render the cloud objects.
        :param caseless_sort: Boolean, whether tag cloud should be sorted
                              case-sensitive.
        :param mincount: Integer threshold to hide tags with smaller count.
        """
        min_px = 10.0
        max_px = 30.0
        scale = 1.0

        if renderer is None:
            def default_renderer(tag, count, percent):
                href = self.get_href(req, realms, tag=Resource('tag', tag))
                return builder.a(tag, rel='tag', title='%i' % count,
                                 href=href, style='font-size: %ipx'
                                 % int(min_px + percent * (max_px - min_px)))
            renderer = default_renderer

        # A LUT from count to n/len(cloud)
        size_lut = dict([(c, float(i)) for i, c in
                         enumerate(sorted(set([r for r in cloud.values()])))])
        if size_lut:
            scale = 1.0 / len(size_lut)

        if caseless_sort:
            # Preserve upper-case precedence within similar tags.
            items = reversed(sorted(cloud.iteritems(),
                                    key=lambda t: t[0].lower(), reverse=True))
        else:
            items = sorted(cloud.iteritems())
        ul = li = None
        for i, (tag, count) in enumerate(items):
            percent = size_lut[count] * scale
            if mincount and count < as_int(mincount, 1):
                # Tag count is too low.
                continue
            if ul:
                # Found new tag for cloud; now add previously prepared one.
                ul('\n', li)
            else:
                # Found first tag for cloud; now create the list.
                ul = builder.ul(class_='tagcloud')
            # Prepare current tag entry.
            li = builder.li(renderer(tag, count, percent))
        if li:
            # All tags checked; mark latest tag as last one (no tailing colon).
            li(class_='last')
            ul('\n', li, '\n')
        return ul and ul or _("No tags found")
Esempio n. 41
0
    def expand_macro(self, formatter, name, content):
        citelist = getattr(formatter, CITELIST, [])
        bibdb = getattr(formatter, BIBDB, {})

        page = WikiPage(self.env, 'BibTex')
        if page.exists:
            if '{{{' in page.text and '}}}' in page.text:
                tmp = re.compile('{{{|}}}', 2).split(page.text)
                bibdb.update(extract_entries(tmp[1]))
                setattr(formatter, BIBDB, bibdb)

        str = ''
        for k in citelist:
            if bibdb.has_key(k) == False:
                str += 'No entry ' + k + ' found.\n'
        if str != '':
            raise TracError('[[' + str + ']]')

        l = []
        for k in citelist:
            content = []
            for bibkey in BIBTEX_KEYS:
                if bibdb[k].has_key(bibkey):
                    content.append(tag.span(Markup(bibdb[k][bibkey] + ', ')))
            if bibdb[k].has_key('url') == False:
                l.append(
                    tag.li(tag.a(name=k),
                           tag.a(href='#cite_%s' % k)('^'), content))
            else:
                url = bibdb[k]['url']
                l.append(
                    tag.li(tag.a(name=k),
                           tag.a(href='#cite_%s' % k)('^'), content, tag.br(),
                           tag.a(href=url)(url)))

        ol = tag.ol(*l)
        tags = []
        tags.append(tag.h1(id='References')('References'))
        tags.append(ol)

        return tag.div(id='References')(*tags)
Esempio n. 42
0
 def _get_bookmarks_menu(self, req):
     menu = tag.ul(class_='bookmarks')
     for url, name, username in self.get_bookmarks(req):
         params = self._format_name(req, url)
         if params['name']:
             label = '%s %s' % (params['linkname'], params['name'])
         else:
             label = params['linkname']
         if params['href'] is not None:
             anchor = tag.a(label, href=params['href'], title=label)
             menu.append(tag.li(anchor, class_=params['class_']))
     return menu
Esempio n. 43
0
    def handle_repo_paths(self, req):
        repopath = req.args.get('q')
        if not repopath.startswith('/'):
            repopath = '/%s' % repopath

        repos = self.env.get_repository(req.authname)

        def get_node_entries(path):
            # Should probably try to cache these searches,
            # although only meant for admins
            if not path.startswith('/'):
                path = '/%s' % path
            fallback = posixpath.dirname(path)
            try:
                node = repos.get_node(str(path), repos.youngest_rev)
            except (TracError, NoSuchNode):
                node = repos.get_node(fallback, repos.youngest_rev)
            node_entries = list(node.get_entries())
            entries = []
            for entry in node_entries:
                path = entry.path
                if not path.startswith('/'):
                    path = '/%s' % path
                if path.startswith(repopath):
                    # Only return those that we're interested in
                    entries.append(entry)
            entries.sort(key=attrgetter('path'))
            return entries

        entries = get_node_entries(repopath)

        if not entries:
            req.write(tag.center(
                tag.em(_("No matches found on repository for "),
                tag.b(repopath))
            ))
            raise RequestDone

        while len(entries) <= 1:
            # If returning only one entry, return a file no matter how deep
            if entries[0].kind == 'dir':
                entries = get_node_entries(entries[0].path)
            elif entries[0].kind == 'file':
                break

        req.write('<ul>')
        for entry in entries:
            path = entry.path
            if not path.startswith('/'):
                path = '/%s' % path
            req.write(tag.li(tag.b(repopath), tag(path.split(repopath)[1])))
        req.write('</ul>')
        raise RequestDone
Esempio n. 44
0
 def _create_milestone_item(self, milestone):
     icon = tag.span(tag.span('',
                              class_='ui-icon %s' % self.mod.milestone_icon
                              or ''),
                     class_='ui-icon-w')
     anchor = tag.a(milestone.name,
                    href=self.req.href('milestone', milestone.name))
     item = tag.li(icon,
                   anchor,
                   style='background-color: %s;' %
                   self.mod.milestone_background_color,
                   class_='milestone')
     return item
Esempio n. 45
0
    def expand_macro(self, formatter, name, content):
        args, kw = parse_args(content)
        prefix = args[0].strip() if args else None
        limit = _arg_as_int(args[1].strip(), min=1) if len(args) > 1 else None
        group = kw.get('group', 'date')

        sql = """SELECT name, max(version) AS max_version,
                        max(time) AS max_time FROM wiki"""
        args = []
        if prefix:
            with self.env.db_query as db:
                sql += " WHERE name %s" % db.prefix_match()
                args.append(db.prefix_match_value(prefix))
        sql += " GROUP BY name ORDER BY max_time DESC"
        if limit:
            sql += " LIMIT %s"
            args.append(limit)

        entries_per_date = []
        prevdate = None
        for name, version, ts in self.env.db_query(sql, args):
            if not 'WIKI_VIEW' in formatter.perm('wiki', name, version):
                continue
            req = formatter.req
            date = user_time(req, format_date, from_utimestamp(ts))
            if date != prevdate:
                prevdate = date
                entries_per_date.append((date, []))
            version = int(version)
            diff_href = None
            if version > 1:
                diff_href = formatter.href.wiki(name, action='diff',
                                                version=version)
            page_name = formatter.wiki.format_page_name(name)
            entries_per_date[-1][1].append((page_name, name, version,
                                            diff_href))

        items_per_date = (
            (date, (tag.li(tag.a(page, href=formatter.href.wiki(name)),
                           tag.small(' (', tag.a(_("diff"), href=diff_href),
                                     ')') if diff_href else None,
                           '\n')
                    for page, name, version, diff_href in entries))
            for date, entries in entries_per_date)

        if group == 'date':
            out = ((tag.h3(date), tag.ul(entries))
                   for date, entries in items_per_date)
        else:
            out = tag.ul(entries for date, entries in items_per_date)
        return tag.div(out)
Esempio n. 46
0
def render_cloud(self, req, type, renderer=None ):
    # Codes are from tractags plugin
    min_px = 10.0
    max_px = 30.0
    scale = 1.0
    add_stylesheet(req, 'zt/css/cloud.css')
    
    model = ZoteroModelProvider(self.env)
    value  = []
    labels = []
    links = []
    if type == 'author':
        author_count = model.count_by_author()
        for creatorID, cnum, firstName, lastName in author_count:
            value.append(cnum)
            labels.append(lastName + ' ' + firstName)
            links.append(req.href.zotero('qjump', author = creatorID))
    elif type == 'publisher':
        publisher_count = model.count_by_publisher()
        for publisher, pnum in publisher_count:
            value.append(pnum)
            labels.append(publisher)
            links.append(req.href.zotero('qjump', publisher = publisher))
    elif type == 'year':
        year_count = model.count_by_year()
        for year, ynum in year_count:
            value.append(ynum)
            labels.append(year)
            links.append(req.href.zotero('qjump', year = year))
    
    
    if renderer is None:
        def default_renderer(label, count, link,percent):
            return tag.a(label, rel='tag', title='%i' % count, href=link,
                             style='font-size: %ipx' %
                                   int(min_px + percent * (max_px - min_px)))
        renderer = default_renderer
    size_lut = dict([(c, float(i)) for i, c in
                     enumerate(sorted(set([r for r in value])))])
    if size_lut:
        scale = 1.0 / len(size_lut)
    ul = tag.ul(class_='tagcloud')
    last = len(value) - 1
    for i, label in enumerate(labels):
        percent = size_lut[value[i]] * scale
        li = tag.li(renderer(label, value[i], links[i], percent))
        if i == last:
            li(class_='last')
        li()
        ul(li, ' ')
    return ul
Esempio n. 47
0
    def expand_macro(self, formatter, name, content):
        prefix = limit = None
        if content:
            argv = [arg.strip() for arg in content.split(',')]
            if len(argv) > 0:
                prefix = argv[0]
                if len(argv) > 1:
                    limit = int(argv[1])

        cursor = formatter.db.cursor()

        sql = 'SELECT name, ' \
              '  max(version) AS max_version, ' \
              '  max(time) AS max_time ' \
              'FROM wiki'
        args = []
        if prefix:
            sql += ' WHERE name LIKE %s'
            args.append(prefix + '%')
        sql += ' GROUP BY name ORDER BY max_time DESC'
        if limit:
            sql += ' LIMIT %s'
            args.append(limit)
        cursor.execute(sql, args)

        entries_per_date = []
        prevdate = None
        for name, version, ts in cursor:
            if not 'WIKI_VIEW' in formatter.perm('wiki', name, version):
                continue
            date = format_date(from_utimestamp(ts))
            if date != prevdate:
                prevdate = date
                entries_per_date.append((date, []))
            version = int(version)
            diff_href = None
            if version > 1:
                diff_href = formatter.href.wiki(name, action='diff',
                                                version=version)
            page_name = formatter.wiki.format_page_name(name)
            entries_per_date[-1][1].append((page_name, name, version,
                                            diff_href))
        return tag.div(
            (tag.h3(date),
             tag.ul(
                 tag.li(tag.a(page, href=formatter.href.wiki(name)), ' ',
                        diff_href and
                        tag.small('(', tag.a('diff', href=diff_href), ')') or
                        None)
                 for page, name, version, diff_href in entries))
            for date, entries in entries_per_date)
Esempio n. 48
0
    def _wiki_view(self, req, stream):
        tags = self._page_tags(req)
        if not tags:
            return stream
        engine = TagEngine(self.env)
        add_stylesheet(req, 'tags/css/tractags.css')
        li = []
        for tag in tags:
            href, title = engine.get_tag_link(tag)
            li.append(T.li(T.a(title=title, href=href)(tag), ' '))

        insert = T.ul(class_='tags')(T.lh('Tags'), li)

        return stream | Transformer('//div[@class="buttons"]').before(insert)
Esempio n. 49
0
    def expand_macro(self, formatter, name, content):
        curpage = formatter.resource.id

        # scoped TOC (e.g. TranslateRu/TracGuide or 0.11/TracGuide ...)
        prefix = ''
        idx = curpage.find('/')
        if idx > 0:
            prefix = curpage[:idx+1]

        ws = WikiSystem(self.env)
        return tag.div(
            tag.h4(_('Table of Contents')),
            tag.ul([tag.li(tag.a(title, href=formatter.href.wiki(prefix+ref),
                                 class_=(not ws.has_page(prefix+ref) and
                                         'missing')),
                           class_=(prefix+ref == curpage and 'active'))
                    for ref, title in self.TOC]),
            class_='wiki-toc')
Esempio n. 50
0
 def _render_title_index(self, formatter, ol, page_resource, active,
                         show_title):
     page_text, page_exists = self.get_page_text(formatter, page_resource)
     if not page_exists:
         ol.append(
             system_message('Error: No page matching %s found' %
                            page_resource.id))
         return
     ctx = formatter.context(page_resource)
     fmt = OutlineFormatter(self.env, ctx)
     fmt.format(page_text, NullOut())
     title = ''
     if show_title and fmt.outline:
         title = ': ' + fmt.outline[0][2]
     ol.append((tag.li(tag.a(page_resource.id,
                             href=get_resource_url(self.env, page_resource,
                                                   ctx.href)),
                       Markup(title),
                       class_=active and 'active' or None)))
Esempio n. 51
0
def render_cloud(env, req, cloud, renderer=None):
    """Render a tag cloud

    :cloud: Dictionary of {object: count} representing the cloud.
    :param renderer: A callable with signature (tag, count, percent) used to
                     render the cloud objects.
    """
    min_px = 10.0
    max_px = 30.0
    scale = 1.0

    if renderer is None:

        def default_renderer(tag, count, percent):
            href = get_resource_url(env, Resource('tag', tag), req.href)
            return builder.a(tag,
                             rel='tag',
                             title='%i' % count,
                             href=href,
                             style='font-size: %ipx' % int(min_px + percent *
                                                           (max_px - min_px)))

        renderer = default_renderer

    # A LUT from count to n/len(cloud)
    size_lut = dict([
        (c, float(i))
        for i, c in enumerate(sorted(set([r for r in cloud.values()])))
    ])
    if size_lut:
        scale = 1.0 / len(size_lut)

    ul = builder.ul(class_='tagcloud')
    last = len(cloud) - 1
    for i, (tag, count) in enumerate(sorted(cloud.iteritems())):
        percent = size_lut[count] * scale
        li = builder.li(renderer(tag, count, percent))
        if i == last:
            li(class_='last')
        li()
        ul(li)
    return ul
Esempio n. 52
0
 def filter_stream(self, req, method, filename, stream, data):
     #self.log.debug('ITemplateStreamFilter method')
     if filename != 'wiki_view.html':
         #self.log.debug('filter stream not matching "wiki_view.html"')
         return stream
     if not self.config.getbool('notification', 'smtp_enabled', False):
         return stream
     page = page = req.path_info[6:] or 'WikiStart'
     watched = self._get_watched_pages(req)
     if page in watched:
         link = tag.a('Un-Watch Page',
                      title='Un-Watch Page',
                      href=req.href.notification(page))
     else:
         link = tag.a('Watch Page',
                      title='Watch Page',
                      href=req.href.notification(page))
     #self.log.debug('Transforming output...')
     return stream | Transformer(
         '//div[@id="ctxtnav"]/ul/li[@class="last"]').attr(
             'class', None).after(tag.li(link, class_="last"))
Esempio n. 53
0
    def _create_ticket_item(self, t):
        req = self.req
        style = None
        tktid = t.get('id')
        background = self.get_priority_color(t.get('priority'))
        if background:
            style = 'background-color: %s' % background
        item = tag.li(title='#%d %s' % (t.get('id'), t.get('summary')),
                      style=style,
                      data_href=req.href('ticketcalendar-ticket', id=tktid))

        for key, icon_class in (('_begin', 'arrowthick-1-e'),
                                ('_end', 'arrowthick-1-w')):
            if t.get(key):
                class_ = 'ui-icon ui-icon-' + icon_class
                item(tag.span(tag.span('', class_=class_), class_='ui-icon-w'))

        if t.get('_beginend'):
            item(
                tag.span(u'\u2666',
                         style='display: inline-block; margin: 0 0.4em;'))

        icon = self.get_ticket_type_icon(t.get('type'))
        if icon:
            item(
                tag.span(tag.span('',
                                  title=t.get('type'),
                                  class_='ui-icon %s' % icon),
                         class_='ui-icon-w'))
        else:
            item(tag.span(t.get('type'), class_='type'))

        item(
            tag.span(
                tag.a('#%d' % tktid,
                      href=req.href('ticket', tktid),
                      class_='open-ticketcalendar-ticket-detail %s' %
                      t.get('status')), u'\u00a0', t.get('summary')))

        return item
Esempio n. 54
0
    def expand_macro(self, formatter, name, content):
        # Make sure data capsule is in place
        if not hasattr(formatter, '_footnotes'):
            formatter._footnotes = []

        # Chrome
        add_stylesheet(formatter.req, 'footnote/footnote.css')
        add_script(formatter.req, 'footnote/footnote.js')

        if content:
            # Add a new footnote
            try:
                # Reference to an existing footnote
                output_id = int(content)

                try:
                    content = formatter._footnotes[output_id-1][0]
                except IndexError:
                    content = 'Unknown footnote'
            except ValueError:
                output_id = None

                # Try to collate with an existing footnote
                for i in xrange(len(formatter._footnotes)):
                    if formatter._footnotes[i][0] == content:
                        output_id = i + 1
                        break

                # Format markup
                markup = format_to_oneliner(self.env, formatter.context, content)

                # Adding a new footnote
                if not output_id:
                    formatter._footnotes.append((content, markup))
                    output_id = len(formatter._footnotes)

            return tag.sup(
                tag.a(
                    output_id,
                    title=shorten_line(content, 50),
                    id='FootNoteRef%s'%output_id,
                    href='#FootNote%s'%output_id,
                ),
                class_='footnote',
            )
        else:
            # Dump all accumulated notes
            footnotes = formatter._footnotes[:]
            formatter._footnotes = [(content, None) for content, markup in footnotes]
            if formatter._footnotes:
                return tag.div(
                    tag.hr(),
                    tag.ol(
                        [tag.li(
                            tag.a(
                                '%s.'%(i+1),
                                href='#FootNoteRef%s'%(i+1),
                                class_='sigil',
                            ),
                            ' ',
                            markup,
                            id='FootNote%s'%(i+1),
                        ) for i, (content, markup) in enumerate(footnotes) if markup],
                    ),
                    class_='footnotes',
                )
            else:
                return []
Esempio n. 55
0
 def _render_externals(self, prop):
     if not self._externals_map:
         for dummykey, value in self.svn_externals_section.options():
             value = value.split()
             if len(value) != 2:
                 self.log.warn(
                     "svn:externals entry %s doesn't contain "
                     "a space-separated key value pair, "
                     "skipping.", dummykey)
                 continue
             key, value = value
             self._externals_map[key] = value.replace('%', '%%') \
                                        .replace('$path', '%(path)s') \
                                        .replace('$rev', '%(rev)s')
     externals = []
     for external in prop.splitlines():
         elements = external.split()
         if not elements:
             continue
         localpath, rev, url = elements[0], '', elements[-1]
         if localpath.startswith('#'):
             externals.append((external, None, None, None, None))
             continue
         if len(elements) == 3:
             rev = elements[1]
             rev = rev.replace('-r', '')
         # retrieve a matching entry in the externals map
         if not self._is_abs_url(url):
             externals.append((external, None, None, None, None))
             continue
         prefix = []
         base_url = url
         while base_url:
             if base_url in self._externals_map or base_url == u'/':
                 break
             base_url, pref = posixpath.split(base_url)
             prefix.append(pref)
         href = self._externals_map.get(base_url)
         revstr = ' at revision ' + rev if rev else ''
         if not href and (url.startswith('http://')
                          or url.startswith('https://')):
             href = url.replace('%', '%%')
         if href:
             remotepath = ''
             if prefix:
                 remotepath = posixpath.join(*reversed(prefix))
             externals.append(
                 (localpath, revstr, base_url, remotepath, href % {
                     'path': remotepath,
                     'rev': rev
                 }))
         else:
             externals.append((localpath, revstr, url, None, None))
     externals_data = []
     for localpath, rev, url, remotepath, href in externals:
         label = localpath
         if url is None:
             title = ''
         elif href:
             if url:
                 url = ' in ' + url
             label += rev + url
             title = ''.join((remotepath, rev, url))
         else:
             title = _('No svn:externals configured in trac.ini')
         externals_data.append((label, href, title))
     return tag.ul([
         tag.li(tag.a(label, href=href, title=title))
         for label, href, title in externals_data
     ])
Esempio n. 56
0
File: io.py Progetto: trucgiao91/woo
 def __call__(self,obj,depth=0,dontRender=False):
     from genshi.builder import tag
     if depth>self.maxDepth: raise RuntimeError("Maximum nesting depth %d exceeded"%self.maxDepth)
     kw=self.padding.copy()
     if depth>0: kw.update(width='100%')
     # was [1:] to omit leading woo./wooExtra., but that is not desirable
     objInExtra=obj.__class__.__module__.startswith('wooExtra.')
     if self.hideWooExtra and objInExtra: head=tag.span(tag.b(obj.__class__.__name__),title=_ensureUnicode(obj.__class__.__doc__))
     else: 
         head=tag.b('.'.join(obj.__class__.__module__.split('.')[0:])+'.'+obj.__class__.__name__)
         head=tag.a(head,href=woo.document.makeObjectUrl(obj),title=_ensureUnicode(obj.__class__.__doc__))
     ret=tag.table(tag.th(head,colspan=3,align='left'),frame='box',rules='all',**kw)
     # get all attribute traits first
     traits=obj._getAllTraits()
     for trait in traits:
         if trait.hidden or (self.hideNoGui and trait.noGui) or trait.noDump or (trait.hideIf and eval(trait.hideIf,globals(),{'self':obj})): continue
         # start new group (additional line)
         if trait.startGroup:
             ret.append(tag.tr(tag.td(tag.i(u'▸ %s'%_ensureUnicode(trait.startGroup)),colspan=3)))
         attr=getattr(obj,trait.name)
         if self.showDoc: tr=tag.tr(tag.td(_ensureUnicode(trait.doc)))
         else:
             try:
                 if self.hideWooExtra and objInExtra: label=tag.span(tag.b(trait.name),title=_ensureUnicode(trait.doc))
                 else: label=tag.a(trait.name,href=woo.document.makeObjectUrl(obj,trait.name),title=_ensureUnicode(trait.doc))
                 tr=tag.tr(tag.td(label))
             except UnicodeEncodeError:
                 print('ERROR: UnicodeEncodeError while formatting the attribute ',obj.__class__.__name__+'.'+trait.name)
                 print('ERROR: the docstring is',trait.doc)
                 raise
         # tr=tag.tr(tag.td(trait.name if not self.showDoc else trait.doc.decode('utf-8')))
         # nested object
         if isinstance(attr,woo.core.Object):
             tr.append([tag.td(self(attr,depth+1),align='justify'),tag.td()])
         # sequence of objects (no units here)
         elif hasattr(attr,'__len__') and len(attr)>0 and isinstance(attr[0],woo.core.Object):
             tr.append(tag.td(tag.ol([tag.li(self(o,depth+1)) for o in attr])))
         else:
             # !! make deepcopy so that the original object is not modified !!
             import copy
             attr=copy.deepcopy(attr)
             if not trait.multiUnit: # the easier case
                 if not trait.prefUnit: unit=u'−'
                 else:
                     unit=_ensureUnicode(trait.prefUnit[0][0])
                     # create new list, where entries are multiplied by the multiplier
                     if type(attr)==list: attr=[a*trait.prefUnit[0][1] for a in attr]
                     else: attr=attr*trait.prefUnit[0][1]
             else: # multiple units
                 unit=[]
                 wasList=isinstance(attr,list)
                 if not wasList: attr=[attr] # handle uniformly
                 for i in range(len(attr)):
                     attr[i]=[attr[i][j]*trait.prefUnit[j][1] for j in range(len(attr[i]))]
                 for pu in trait.prefUnit:
                     unit.append(_ensureUnicode(pu[0]))
                 if not wasList: attr=attr[0]
                 unit=', '.join(unit)
             # sequence type, or something similar                
             if hasattr(attr,'__len__') and not isinstance(attr,(str,unicode,bytes)):
                 if len(attr)>0:
                     tr.append(tag.td(self.htmlSeq(attr,insideTable=False),align='right'))
                 else:
                     tr.append(tag.td(tag.i('[empty]'),align='right'))
             else:
                 tr.append(tag.td(float2str(attr) if isinstance(attr,float) else str(attr),align='right'))
             if unit:
                 tr.append(tag.td(unit,align='right'))
         ret.append(tr)
     if depth>0 or dontRender: return ret
     r1=ret.generate().render('xhtml',encoding='ascii')
     if isinstance(r1,bytes): r1=r1.decode('ascii')
     return r1+u'\n'
Esempio n. 57
0
                       if len(elt) == 3 else
                       tag.a('/'.join(elt[0]),
                             href=formatter.href.wiki(elt[1])))
                for elt in group)

        transform = {
            'group': lambda p: render_group(tree_group(split_pages_group(p))),
            'hierarchy': lambda p: render_hierarchy(
                                    tree_hierarchy(split_pages_hierarchy(p))),
            }.get(format)

        if transform:
            titleindex = transform(pages)
        else:
            titleindex = tag.ul(
                tag.li(tag.a(wiki.format_page_name(omitprefix(page)),
                             href=formatter.href.wiki(page)))
                for page in pages)

        return tag.div(titleindex, class_='titleindex')


class RecentChangesMacro(WikiMacroBase):
    _domain = 'messages'
    _description = cleandoc_(
    """List all pages that have recently been modified, ordered by the
    time they were last modified.

    This macro accepts two ordered arguments and a named argument. The named
    argument can be placed in any position within the argument list.

    The first parameter is a prefix string: if provided, only pages with names