Exemplo n.º 1
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
Exemplo n.º 2
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
Exemplo n.º 3
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
Exemplo n.º 4
0
    def expand_macro(self, formatter, name, content):
        args, kw = parse_args(content)
        prefix = args[0].strip() if args else None
        limit = int(args[1].strip()) 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)
Exemplo n.º 5
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)
Exemplo n.º 6
0
        def gentd(week_idx, day_info):
            day = day_info['date']
            tt = day_info['milestones'] + day_info['tickets']
            if len(tt) < 6:
                ttshow = tt
                ttall = []
            else:
                ttshow = tt[:4]
                ttall = tt

            tdclass = []
            if day == today:
                tdclass.append('today')
            if day.weekday() in (5, 6):
                tdclass.append('weekend')

            formatted_day = format_date(day, format='long', locale=locale)

            td = tag.td(class_=' '.join(tdclass),
                        data_for_start_date=day.strftime(start_date_format),
                        data_for_due_date=day.strftime(due_date_format),
                        data_fdate=formatted_day)

            label = []
            if day == today:
                label.append(tag.span(_("Today"), class_='today'))
            label.append(
                tag.span(unicode(day.day),
                         class_=('day normal', 'day')[day == today]))
            td(tag.div(label))
            if ttshow:
                td(tag.ul([genli(t) for t in ttshow]))

            if ttall:
                id = 'calendar-more-%s' % str(day)
                td(
                    tag.a(_("%d more tickets...") % (len(ttall) - 4),
                          href='#' + id,
                          class_='show-all-list'),
                    tag.div(tag.h4(formatted_day),
                            tag.ul([genli(t) for t in ttall]),
                            class_='ticketcalendar-popup-list',
                            id=id,
                            data_title=format_date(day,
                                                   locale=locale,
                                                   format='full')))

            return td
Exemplo n.º 7
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
Exemplo n.º 8
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)
    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')
        li = []

        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)
            
            li.append(
                tag.li(
                    tag.a(title=name, href=link,
                    )(name)
                )
            )
            
        insert = tag.ul(class_="nav", id="breadcrumbs")(("Breadcrumbs:"), li)

        return stream | Transformer('//div[@id="metanav"]/ul').after(insert)
        
Exemplo n.º 10
0
    def post_process_request (self, req, template, data, content_type):
	add_stylesheet(req, 'mainnavsubmenu/css/menu.css')
        mainnav = req.chrome['nav']['mainnav']

        for item in mainnav:
            submenus = self._submenus.get(item['name'])
            if not submenus:
                continue

            ul = tag.ul()
            for _item in submenus:
                href = _item.get('href')
                if href == '@milestones@':
                    self._add_milestones(req, ul)
                elif href == '@ticket_types@':
                    self._add_ticket_types(req, ul)
                elif href == '@saved_query@':
                    self._add_saved_query(req, ul, self._item_label(req, _item))
                else:
                    label = self._item_label(req, _item)
                    self._add_item(req, ul, label, href)

            item['label'] = tag(item['label'], ul)

        return (template, data, content_type)
Exemplo n.º 11
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))
Exemplo n.º 12
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
Exemplo 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')
Exemplo n.º 14
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",
            )
Exemplo n.º 15
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)
Exemplo n.º 16
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)
Exemplo n.º 17
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
Exemplo n.º 18
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
Exemplo n.º 19
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",
            )
Exemplo 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
Exemplo n.º 21
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))
Exemplo n.º 22
0
    def render_reviewlink(self, req):
        """Render the "143 commits." box that shows in the topnav."""
        #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' + str, href=href)
            li = tag.li(a)
            els.append(li)            
        
        ul = tag.ul(els, class_='review')
        className = ''
        title = "Reviews"
        add_ctxtnav(req, tag.span(ul, id='icureview', title=title, class_=className))
Exemplo n.º 23
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')
        li = []

        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)

            li.append(tag.li(tag.a(
                title=name,
                href=link,
            )(name)))

        insert = tag.ul(class_="nav", id="breadcrumbs")(tag.lh("Breadcrumbs:"),
                                                        li)

        return stream | Transformer('//div[@id="metanav"]/ul').after(insert)
Exemplo n.º 24
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])
Exemplo n.º 25
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
Exemplo n.º 26
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
Exemplo n.º 27
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)
Exemplo n.º 28
0
        def gentd(week_idx, day_info):
            day = day_info['date']
            tt = day_info['milestones'] + day_info['tickets']
            if len(tt) < 6:
                ttshow = tt
                ttall = []
            else:
                ttshow = tt[:4]
                ttall = tt

            tdclass = []
            if day == today:
                tdclass.append('today')
            if is_weekend(day, locale):
                tdclass.append('weekend')

            formatted_day = format_date(day, format='long', locale=locale)

            td = tag.td(
                class_=' '.join(tdclass),
                data_for_start_date=day.strftime(start_date_format),
                data_for_due_date=day.strftime(due_date_format),
                data_fdate=formatted_day)

            label = []
            if day == today:
                label.append(tag.span(_("Today"), class_='today'))
            label.append(tag.span(unicode(day.day),
                                  class_=('day normal', 'day')[day == today]))
            td(tag.div(label))
            if ttshow:
                td(tag.ul([genli(t) for t in ttshow]))

            if ttall:
                id = 'calendar-more-%s' % str(day)
                td(tag.a(_("%d more tickets...") % (len(ttall) - 4),
                         href='#' + id,
                         class_='show-all-list'),
                   tag.div(tag.h4(formatted_day),
                           tag.ul([genli(t) for t in ttall]),
                           class_='ticketcalendar-popup-list',
                           id=id,
                           data_title=format_date(day, locale=locale,
                                                  format='full')))

            return td
Exemplo n.º 29
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 
Exemplo 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
Exemplo n.º 31
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)
Exemplo 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)
Exemplo 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])
Exemplo 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
Exemplo 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
Exemplo n.º 36
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")
Exemplo 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
Exemplo 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")
Exemplo n.º 39
0
 def _get_bookmarks_menu(self, req):
     menu = tag.ul()
     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))
     return menu
Exemplo n.º 40
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
Exemplo n.º 41
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
Exemplo n.º 42
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
Exemplo n.º 43
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
Exemplo n.º 44
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)
Exemplo n.º 45
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)
Exemplo n.º 46
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)
Exemplo n.º 47
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)
Exemplo n.º 48
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)
Exemplo n.º 49
0
 def expand_macro(self, formatter, name, content):
     """Prints children pages on currently opened page.
     """
     # parse args
     class_ = "flex-children"
     if content:
         args = content.split(',')
         for arg in args:
             arg = arg.strip()
             if arg.startswith('class='):
                 class_ = arg.split('=', 1)[1].strip()
     # print output
     node = self.get_start_node(formatter, name)
     if node:
         return tag.ul(self.render_node(node, formatter), class_=class_)
     else:
         return ''
Exemplo n.º 50
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))
Exemplo n.º 51
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')
Exemplo n.º 52
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
Exemplo n.º 53
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
Exemplo n.º 54
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