Exemple #1
0
 def _render_property(self, name, mode, context, props):
     repos, revs = props[name]
     def link(rev):
         chgset = repos.get_changeset(rev)
         return tag.a(rev, class_="changeset",
                      title=shorten_line(chgset.message),
                      href=context.href.changeset(rev, repos.reponame))
     if name == 'Parents' and len(revs) == 2: # merge
         new = context.resource.id
         parent_links = [
                 (link(rev), ' (',
                  tag.a('diff', title=_("Diff against this parent "
                        "(show the changes merged from the other parents)"),
                        href=context.href.changeset(new, repos.reponame, 
                                                    old=rev)), ')')
                        for rev in revs]
         return tag([(parent, ', ') for parent in parent_links[:-1]],
                    parent_links[-1], tag.br(),
                    tag.span(tag_("Note: this is a %(merge)s changeset, "
                                  "the changes displayed below correspond "
                                  "to the merge itself.",
                                  merge=tag.strong('merge')),
                             class_='hint'), tag.br(), 
                    # TODO: only keep chunks present in both parents 
                    #       (conflicts) or in none (extra changes)
                    # tag.span('No changes means the merge was clean.',
                    #         class_='hint'), tag.br(), 
                    tag.span(tag_("Use the %(diff)s links above to see all "
                                  "the changes relative to each parent.",
                                  diff=tag.tt('(diff)')),
                             class_='hint'))
     return tag([tag(link(rev), ', ') for rev in revs[:-1]],
                link(revs[-1]))
 def _user_field_input(self, req):
     return tag.div(self._hackedHiddenField()
                    + self._toggleBox(req,
                                      'Show milestone descriptions',
                                      'show_descriptions',
                                      'true')
                    + tag.br()
                    + self._filterBox(req, "Include: ", "inc_milestones")
                    + tag.br()
                    + self._filterBox(req, "Exclude: ", "exc_milestones")
                    )                    
Exemple #3
0
    def filter_stream(self, req, method, filename, stream, data):
        if filename.startswith("roadmap"):
            filter_projects = smp_filter_settings(req, 'roadmap', 'projects')
            filter = Transformer('//form[@id="prefs"]/fieldset/div[1]')
            stream = stream | filter.before(
                tag.label("Filter Projects:")) | filter.before(
                    tag.br()) | filter.before(
                        self._projects_field_input(
                            req, filter_projects)) | filter.before(tag.br())

        return stream
Exemple #4
0
    def filter_stream(self, req, method, filename, stream, data):
        if filename == 'timeline.html':
            filter_projects = self._filtered_projects(req)

            filter = Transformer('//form[@id="prefs"]/div[1]')
            stream = stream | filter.before(
                tag.label("Filter Projects:")) | filter.before(
                    tag.br()) | filter.before(
                        self._projects_field_input(
                            req, filter_projects)) | filter.before(
                                tag.br()) | filter.before(tag.br())

        return stream
Exemple #5
0
def _render_change(old, new):
    rendered = None
    if old and not new:
        rendered = tag(
            Markup(_("%(value)s reset to default value", value=tag.em(old))))
    elif new and not old:
        rendered = tag(
            Markup(_("from default value set to %(value)s",
                     value=tag.em(new))))
    elif old and new:
        if len(old) < 20 and len(new) < 20:
            rendered = tag(
                Markup(
                    _("changed from %(old)s to %(new)s",
                      old=tag.em(old),
                      new=tag.em(new))))
        else:
            nbsp = tag.br()
            # TRANSLATOR: same as before, but with additional line breaks
            rendered = tag(
                Markup(
                    _("changed from %(old)s to %(new)s",
                      old=tag.em(nbsp, old),
                      new=tag.em(nbsp, new))))
    return rendered
Exemple #6
0
 def _link_refs(self, req, refs_text, verbose_link=False):
     items_tag = None
     items, verbose_items = [], []
     elem = verbose_elem = "#%s" % refs_text
     try:
         c = self.cursor
         c.execute("SELECT id,name FROM assets_feature WHERE id ='%s'" % refs_text)
         row = c.fetchone()
         if row:
             title = shorten_line(row[1])
             attr = {
                 "class_": "assigned",
                 "href": "/splice/tractab/SPLICE/projects/feature/" + str(row[0]),
                 "title": title,
             }
             elem = tag.a("#%s %s" % (refs_text, title), **attr)
             verbose_elem = tag.a("#%s %s" % (refs_text, title), **attr)
     except ResourceNotFound:
         pass  # not supposed to happen, just in case
     items.extend([elem, ", "])
     verbose_items.extend([verbose_elem, tag.br()])
     if items:
         items_tag = [tag.span(items[:-1], id="tref_ticketid")]
         if verbose_link:
             vattr = {"id": "tref_summary", "class_": "tref-display-none"}
             items_tag.append(tag.span(verbose_items[:-1], **vattr))
     return tag(items_tag)
Exemple #7
0
 def _process_edit(self, req, stream, method, tags):
     stage = 1                     
     elm = tag.div([tag.label('Tag under: (', 
                              tag.a('view all tags', href=req.href.tags()),
                              ')', 
                              for_='tags'), 
                    tag.br(), 
                    tag.input(title='Comma separated list of tags',
                              type='text',
                              id='tags',
                              size='30',
                              name='tags',
                              value=', '.join(tags)
                             ),
                   ], class_='field')
     for kind, data, pos in stream:            
         yield kind, data, pos
         if stage == 1 and \
            kind is START and \
            data[0].localname == 'input' and \
            data[1].get('id') == 'comment':
             stage = 2
         elif stage == 2 and \
              kind is END and \
              data.localname == 'div':
             for e in elm.generate():
                 yield e
             stage = None
Exemple #8
0
 def _launch(self, encoded_input, *args):
     """Launch a process (cmd), and returns exitcode, stdout + stderr"""
     # Note: subprocess.Popen doesn't support unicode options arguments
     # (http://bugs.python.org/issue1759845) so we have to encode them.
     # Anyway, dot expects utf-8 or the encoding specified with -Gcharset.
     encoded_cmd = []
     for arg in args:
         if isinstance(arg, unicode):
             arg = arg.encode(self.encoding, 'replace')
         encoded_cmd.append(arg)
     p = subprocess.Popen(encoded_cmd, stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     if input:
         p.stdin.write(encoded_input)
     p.stdin.close()
     out = p.stdout.read()
     err = p.stderr.read()
     reason = None
     if p.wait() != 0:
         reason = _("failed with the following output:")
     if err or out:
         reason = _("succeeded but emitted the following output:")
     if reason:
         return tag.p(tag.br(), _("The command:"), 
                      tag.pre(repr(' '.join(encoded_cmd))), reason, 
                      out and tag.pre(repr(out)), err and tag.pre(repr(err)))
 def _launch(self, encoded_input, *args):
     """Launch a process (cmd), and returns exitcode, stdout + stderr"""
     # Note: subprocess.Popen doesn't support unicode options arguments
     # (http://bugs.python.org/issue1759845) so we have to encode them.
     # Anyway, dot expects utf-8 or the encoding specified with -Gcharset.
     encoded_cmd = []
     for arg in args:
         if isinstance(arg, unicode):
             arg = arg.encode(self.encoding, 'replace')
         encoded_cmd.append(arg)
     p = subprocess.Popen(encoded_cmd, stdin=subprocess.PIPE,
                          stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     if encoded_input:
         p.stdin.write(encoded_input)
     p.stdin.close()
     out = p.stdout.read()
     err = p.stderr.read()
     failure = p.wait() != 0
     if failure or err or out:
         return (failure, tag.p(tag.br(), _("The command:"), 
                      tag.pre(repr(' '.join(encoded_cmd))), 
                      (_("succeeded but emitted the following output:"),
                       _("failed with the following output:"))[failure],
                      out and tag.pre(repr(out)), 
                      err and tag.pre(repr(err))))
     else:
         return (False, None)
Exemple #10
0
    def _provider_failure(self, exc, req, ep, current_filters, all_filters):
        """Raise a TracError exception explaining the failure of a provider.

        At the same time, the message will contain a link to the timeline
        without the filters corresponding to the guilty event provider `ep`.
        """
        ep_name, exc_name = [i.__class__.__name__ for i in (ep, exc)]
        self.log.error("Timeline event provider failed: %s", exception_to_unicode(exc, traceback=True))

        guilty_filters = [f[0] for f in ep.get_timeline_filters(req)]
        guilty_kinds = [f[1] for f in ep.get_timeline_filters(req)]
        other_filters = [f for f in current_filters if not f in guilty_filters]
        if not other_filters:
            other_filters = [f for f in all_filters if not f in guilty_filters]
        args = [(a, req.args.get(a)) for a in ("from", "format", "max", "daysback")]
        href = req.href.timeline(args + [(f, "on") for f in other_filters])
        raise TracError(
            tag(
                tag.p(
                    ", ".join(guilty_kinds),
                    " event provider (",
                    tag.tt(ep_name),
                    ") failed:",
                    tag.br(),
                    exc_name,
                    ": ",
                    to_unicode(exc),
                    class_="message",
                ),
                tag.p("You may want to see the other kind of events from the ", tag.a("Timeline", href=href)),
            )
        )
Exemple #11
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')
Exemple #12
0
 def __linkify_ids_p(self, ids, data):
     # チケットの表示のページでinterTracリンクの表示するための元を作る
     # 先行、親など指定しているidを検索する
     if not ids:
         del data[-1]
         return
     tickets = ids.split(',')
     #なにもない場合はエラーになるのでifが必要
     for ticket in tickets:
         if not ticket:
             continue
         t = self.__get_intertrac_ticket(ticket, True)
         error = t['error']
         if error is None:
             tkt = t['ticket']
             status = tkt['status']
             title1 = tkt['summary']
             data.append(
                 tag.a(ticket,
                       href=t['url'],
                       class_='%s ticket' % status,
                       title=title1))
             data.append(', ')
     if data:
         # 最後のカンマを削除する.
         del data[-1]
     data.append(tag.br())
Exemple #13
0
 def launch(self, proc_cmd, encoded_input, *args):
     """Launch a process (cmd), and returns exitcode, stdout + stderr"""
     # Note: subprocess.Popen doesn't support unicode options arguments
     # (http://bugs.python.org/issue1759845) so we have to encode them.
     # Anyway, dot expects utf-8 or the encoding specified with -Gcharset.
     encoded_cmd = proc_cmd
     proc = subprocess.Popen(encoded_cmd,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
     if encoded_input:
         proc.stdin.write(encoded_input)
     proc.stdin.close()
     out = proc.stdout.read()
     err = proc.stderr.read()
     failure = proc.wait() != 0
     if failure or err or out:
         return (failure,
                 tag.div(tag.br(),
                         _("The command:"),
                         tag.pre(repr(' '.join(encoded_cmd))),
                         (_("succeeded but emitted the following output:"),
                          _("failed with the following output:"))[failure],
                         out and tag.pre(out),
                         err and tag.pre(err),
                         class_="system-message"))
     else:
         return (False, None)
Exemple #14
0
 def _process_edit(self, req, stream, method, tags):
     stage = 1
     elm = tag.div([
         tag.label('Tag under: (',
                   tag.a('view all tags', href=req.href.tags()),
                   ')',
                   for_='tags'),
         tag.br(),
         tag.input(title='Comma separated list of tags',
                   type='text',
                   id='tags',
                   size='30',
                   name='tags',
                   value=', '.join(tags)),
     ],
                   class_='field')
     for kind, data, pos in stream:
         yield kind, data, pos
         if stage == 1 and \
            kind is START and \
            data[0].localname == 'input' and \
            data[1].get('id') == 'comment':
             stage = 2
         elif stage == 2 and \
              kind is END and \
              data.localname == 'div':
             for e in elm.generate():
                 yield e
             stage = None
 def show_all_errors(self, e):
     container = tag.span()
     for field_name, error in e.error_dict().items():
         text = u'%s: %s' % (field_name, error.details().msg())
         container.append(system_message(text))
         container.append(tag.br())
     return container
Exemple #16
0
def generate_home(self, req):
    
    model = ZoteroModelProvider(self.env)
    
    title = tag.h1( 'Tops' )
    authors_top = model.count_by_author_top()
    authors = []
    for creatorID, firstName, lastName in authors_top:
        authors.append(tag.a( lastName + ' ' + firstName, 
                href = req.href.zotero('qjump', author = creatorID) ) )
        authors.append(tag.span(' | '))
    authors = tag.tr(tag.th( tag.b('Authors:'), 
        tag.td( authors, 
                tag.a('more...', href = req.href.zotero('cloud', t = 'author' ) ) ),
        valign="top", style="text-align: right; width: 15%;"))
    
    publisher_top = model.count_by_publisher_top()
    publisher = []
    for p in publisher_top:
        publisher.append(tag.a( p, 
                href = req.href.zotero('qjump', publisher = p) ) )
        publisher.append(tag.br())
    publisher = tag.tr(tag.th( tag.b('Publishers:'), 
            tag.td(publisher, 
                   tag.a('more...', href = req.href.zotero('cloud', t = 'publisher' ))),
            valign="top", style="text-align: right; width: 15%;"))
    
    year_top = model.count_by_year_top()
    years = []
    for y in year_top:
        years.append(tag.a( y, 
                href = req.href.zotero('qjump', year = y) ) )
        years.append(tag.span(' | '))
    years = tag.tr(tag.th( tag.b('Years:'), 
            tag.td(years, 
                   tag.a('more...', href = req.href.zotero('cloud', t = 'year' ))),
            valign="top", style="text-align: right; width: 15%;"))
    # For recently add
    recent_ids = model.get_recents()
    recents_title = tag.div( tag.br(), tag.br(),tag.h1('Recent Changes'))
    recents = render_refs_box(self, req, recent_ids )
    home = tag.div( title, 
        tag.table(authors, years, publisher, border="0", cellpadding="2", cellspacing="2"),
        recents_title, recents)
    
    return home
Exemple #17
0
    def filter_stream(self, req, method, filename, stream, data):
        if 'TICKET_ADMIN' in req.perm and req.path_info.startswith('/admin/ticket/components'):
            if data.get('components'):
                filter = Transformer('//form[@id="addcomponent"]/fieldset/div[@class="buttons"]')
                stream = stream | filter.before(tag.div("Default CC:",
                                                tag.br(),
                                                tag.input(type='text', name='defaultcc'),
                                                class_='field'))

                default_ccs = DefaultCC.select(self.env)

                stream = stream | Transformer('//table[@id="complist"]/thead/tr') \
                    .append(tag.th('Default CC'))

                filter = Transformer('//table[@id="complist"]/tbody')
                default_comp = self.config.get('ticket', 'default_component')
                for comp in data.get('components'):
                    if comp.name == default_comp:
                        default_tag = tag.input(type='radio', name='default', value=comp.name, checked='checked')
                    else:
                        default_tag = tag.input(type='radio', name='default', value=comp.name)

                    if comp.name in default_ccs:
                        default_cc = default_ccs[comp.name]
                    else:
                        default_cc = ''

                    filter = filter.append(tag.tr(tag.td(tag.input(type='checkbox', name='sel', value=comp.name), class_='sel'),
                                                  tag.td(tag.a(comp.name, href=req.href.admin('ticket', 'components') + '/' + comp.name), class_='name'),
                                                  tag.td(comp.owner, class_='owner'),
                                                  tag.td(default_tag, class_='default'),
                                                  tag.td(default_cc, class_='defaultcc')))
                return stream | filter

            elif data.get('component'):
                cc = DefaultCC(self.env, data.get('component').name)
                filter = Transformer('//form[@id="modcomp"]/fieldset/div[@class="buttons"]')
                filter = filter.before(tag.div("Default CC:",
                                               tag.br(),
                                               tag.input(type='text', name='defaultcc', value=cc.cc),
                                               class_='field')) \
                                               .before(tag.input(type='hidden', name='old_name', value=cc.name))
                return stream | filter

        return stream
Exemple #18
0
    def render_timeline_event(self, context, field, event):
        codereview_page, name, notes, reviewersList = event[3]

        if field == 'url':
            return context.href.peerReviewView(Review=codereview_page.id)
        if field == 'title':
            return tag('Code review ', tag.em(name), ' has been raised')
        if field == 'description':
            return tag('Assigned to: ', reviewersList, tag.br(), ' Additional notes: ', notes)
Exemple #19
0
 def _user_field_input(self, req):
     return tag.div(
         self._hackedHiddenField()
         + self._toggleBox(req, _("Show milestone descriptions"), "show_descriptions", "true")
         + tag.br()
         + self._filterBox(req, _("Filter:  "), "inc_milestones")
         #                       + tag.br()
         #                       + self._filterBox(req, "Exclude: ", "exc_milestones")
     )
Exemple #20
0
    def filter_stream(self, req, method, filename, stream, data):
        if 'TICKET_ADMIN' in req.perm and \
                req.path_info.startswith('/admin/ticket/components'):
            if data.get('component'):
                cc = DefaultCC(self.env, data.get('component').name)
                filter = Transformer('//form[@id="modcomp"]/fieldset'
                                     '/div[@class="field"][2]')
                filter = filter.after(tag.div("Default CC:",
                                              tag.br(),
                                              tag.input(type='text',
                                                        name='defaultcc',
                                                        value=cc.cc),
                                              class_='field')) \
                               .before(tag.input(type='hidden',
                                                 name='old_name',
                                                 value=cc.name))
                return stream | filter
            else:
                filter = Transformer('//form[@id="addcomponent"]'
                                     '/fieldset/div[@class="buttons"]')
                stream |= filter.before(tag.div("Default CC:",
                                                tag.br(),
                                                tag.input(type='text',
                                                          name='defaultcc'),
                                                class_='field'))

                default_ccs = DefaultCC.select(self.env)

                stream |= Transformer('//table[@id="complist"]/thead/tr') \
                          .append(tag.th('Default CC'))

                for i, comp in enumerate(data.get('components')):
                    if comp.name in default_ccs:
                        default_cc = default_ccs[comp.name]
                    else:
                        default_cc = ''
                    filter = Transformer('//table[@id="complist"]'
                                         '/tbody/tr[%d]' % (i + 1))
                    stream |= filter.append(tag.td(default_cc,
                                                   class_='defaultcc'))
                return stream

        return stream
Exemple #21
0
 def _wiki_edit(self, req, stream):
     insert = tag.div(class_='field')(
         tag.label(
             'Tag under: (', tag.a('view all tags', href=req.href.tags()), ')',
             tag.br(),
             tag.input(id='tags', type='text', name='tags', size='30',
                       value=req.args.get('tags', ' '.join(self._page_tags(req)))),
             )
         )
     return stream | Transformer('//div[@id="changeinfo1"]').append(insert)
Exemple #22
0
def get_powered_by_sign():
    return tag.p("Powered by ",
                 tag.a(tag.strong("IttecoTracPlugin %s" % __version__),
                       href="http://tracplugin.itteco.com/"),
                 tag.br(),
                 tag(
                     "By ",
                     tag.a("Itteco Software", href="http://www.itteco.com"),
                 ),
                 class_="left")
Exemple #23
0
    def __new_project(self):
        all_projects = self.__SmpModel.get_all_projects()

        return tag.div(tag.label(
            'Project:', tag.br(),
            tag.select(tag.option(), [
                tag.option(row[1], value=row[0])
                for row in sorted(all_projects, key=itemgetter(1))
            ],
                       name="project")),
                       class_="field")
Exemple #24
0
    def filter_stream(self, req, method, filename, stream, data):
        if 'TICKET_ADMIN' in req.perm and \
                req.path_info.startswith('/admin/ticket/components'):
            if data.get('component'):
                cc = DefaultCC(self.env, data.get('component').name)
                filter = Transformer('//form[@class="mod"]/fieldset'
                                     '/div[@class="field"][2]')
                filter = filter.after(tag.div("Default CC:",
                                              tag.br(),
                                              tag.input(type='text',
                                                        name='defaultcc',
                                                        value=cc.cc),
                                              class_='field')) \
                               .before(tag.input(type='hidden',
                                                 name='old_name',
                                                 value=cc.name))
                return stream | filter
            else:
                filter = Transformer('//form[@id="addcomponent"]'
                                     '/fieldset/div[@class="buttons"]')
                stream |= filter.before(
                    tag.div("Default CC:",
                            tag.br(),
                            tag.input(type='text', name='defaultcc'),
                            class_='field'))

                default_ccs = DefaultCC.select(self.env)

                stream |= Transformer('//table[@id="complist"]/thead'
                                      '/tr/th[3]') \
                          .after(tag.th('Default CC'))

                components = data.get('components')
                if components:
                    func = self._inject_default_cc_cols(
                        default_ccs, components)
                    stream |= Transformer('//table[@id="complist"]'
                                          '/tbody/tr').apply(func)
                return stream

        return stream
Exemple #25
0
 def _wiki_edit(self, req, stream):
     # TRANSLATOR: Label text for link to '/tags'.
     link = tag.a(_("view all tags"), href=req.href.tags())
     # TRANSLATOR: ... (view all tags)
     insert = tag(Markup(_("Tag under: (%(tags_link)s)", tags_link=link)))
     insert(
         tag.br(),
         tag.input(id='tags', type='text', name='tags', size='50',
             value=req.args.get('tags', ' '.join(self._page_tags(req))))
     )
     insert = tag.div(tag.label(insert), class_='field')
     return stream | Transformer('//div[@id="changeinfo1"]').append(insert)
Exemple #26
0
 def _wiki_edit(self, req, stream):
     # TRANSLATOR: Label text for link to '/tags'.
     link = tag.a(_("view all tags"), href=req.href.tags())
     # TRANSLATOR: ... (view all tags)
     insert = tag(Markup(_("Tag under: (%(tags_link)s)", tags_link=link)))
     insert(
         tag.br(),
         tag.input(id='tags', type='text', name='tags', size='50',
             value=req.args.get('tags', ' '.join(self._page_tags(req))))
     )
     insert = tag.div(tag.label(insert), class_='field')
     return stream | Transformer('//div[@id="changeinfo1"]').append(insert)
 def noscript_fallback_tag(self):
     return tag.noscript(
         tag.iframe(src=self.noscript_url(),
                    height=300,
                    width=500,
                    frameborder=0),
         tag.br(),
         tag.textarea(name='recaptcha_challenge_field', rows=3, cols=40),
         tag.input(type='hidden',
                   name='recaptcha_response_field',
                   value='manual_challenge'),
     )
Exemple #28
0
 def _generate_attachmentflags_fieldset(self,
                                        readonly=True,
                                        current_flags=None,
                                        form=False):
     fields = Fragment()
     for flag in self.known_flags:
         flagid = 'flag_' + flag
         if current_flags and flag in current_flags:
             date = datetime.datetime.fromtimestamp(
                 current_flags[flag]["updated_on"], utc)
             text = tag.span(
                 tag.strong(flag), " set by ",
                 tag.em(current_flags[flag]["updated_by"]), ", ",
                 tag.span(pretty_timedelta(date),
                          title=format_datetime(date)), " ago")
             if readonly == True:
                 fields += tag.input(text, \
                                     type='checkbox', id=flagid, \
                                     name=flagid, checked="checked",
                                     disabled="true") + tag.br()
             else:
                 fields += tag.input(text, \
                                     type='checkbox', id=flagid, \
                                     name=flagid, checked="checked") + tag.br()
         else:
             if readonly == True:
                 fields += tag.input(flag, \
                                     type='checkbox', id=flagid, \
                                     name=flagid, disabled="true") + tag.br()
             else:
                 fields += tag.input(flag, \
                                     type='checkbox', id=flagid, \
                                     name=flagid) + tag.br()
     if form and not readonly:
         return tag.form(tag.fieldset(
             tag.legend("Attachment Flags") + fields,
             tag.input(type="hidden", name="action", value="update_flags"),
             tag.input(type="submit", value="Update flags")),
                         method="POST")
     return tag.fieldset(tag.legend("Attachment Flags") + fields)
Exemple #29
0
    def __new_project(self):
        all_projects = self.__SmpModel.get_all_projects()

        return tag.div(
                       tag.label(
                       'Project:',
                       tag.br(),
                       tag.select(
                       tag.option(),
                       [tag.option(row[1], value=row[0]) for row in sorted(all_projects, key=itemgetter(1))],
                       name="project")
                       ),
                       class_="field")
Exemple #30
0
 def _wiki_edit(self, req, stream):
     insert = T.div(class_='field')(T.label(
         'Tag under: (',
         T.a('view all tags', href=req.href.tags()),
         ')',
         T.br(),
         T.input(id='tags',
                 type='text',
                 name='tags',
                 size='30',
                 value=req.args.get('tags',
                                    ' '.join(self._page_tags(req)))),
     ))
     return stream | Transformer('//div[@id="changeinfo1"]').append(insert)
Exemple #31
0
def _create_select(label_text, id, name, options, selected_name=None, default_selection=None):
    select = tag.select(id=id, name=name)
    if selected_name is None and default_selection is not None:
        selected_name = default_selection
    for option_name in options:
        if option_name == selected_name:
            select.append(tag.option(option_name, value=option_name, selected='selected'))
        else:
            select.append(tag.option(option_name, value=option_name))
    insert = tag(label_text)
    insert(
        tag.br(), select
    )
    insert = tag.div(tag.label(insert), class_='field')
    return insert
Exemple #32
0
    def filter_stream(self, req, method, filename, stream, data):
        if 'TICKET_ADMIN' in req.perm:
            if req.path_info == '/admin/ticket/components' or req.path_info == '/admin/ticket/components/':
                components = data.get('components')
                # 'components' will be None if component with specified name already exists.
                if not components:
                    return stream
                
                default_ccs = DefaultCC.select(self.env)

                stream = stream | Transformer('//table[@id="complist"]/thead/tr') \
                    .append(tag.th('Default CC'))

                filter = Transformer('//table[@id="complist"]/tbody')
                default_comp = self.config.get('ticket', 'default_component')
                for comp in components:
                    if default_comp == comp.name:
                        default_tag = tag.input(type='radio', name='default', value=comp.name, checked='checked')
                    else:
                        default_tag = tag.input(type='radio', name='default', value=comp.name)

                    if comp.name in default_ccs:
                        default_cc = default_ccs[comp.name]
                    else:
                        default_cc = ''

                    filter = filter.append(tag.tr(tag.td(tag.input(type='checkbox', name='sel', value=comp.name), class_='sel'),
                                                  tag.td(tag.a(comp.name, href=req.href.admin('ticket', 'components') + '/' + comp.name), class_='name'),
                                                  tag.td(comp.owner, class_='owner'),
                                                  tag.td(default_tag, class_='default'),
                                                  tag.td(default_cc, class_='defaultcc')))
                return stream | filter

            elif req.path_info.startswith('/admin/ticket/components/') and data.get('component'):
                cc = DefaultCC(self.env, data.get('component').name)
                filter = Transformer('//form[@id="modcomp"]/fieldset/div[@class="buttons"]')
                filter = filter.before(tag.div("Default CC:",
                                               tag.br(),
                                               tag.input(type="text", name="defaultcc", value=cc.cc),
                                               class_="field")) \
                                               .before(tag.input(type='hidden', name='old_name', value=cc.name))
                return stream | filter

        return stream
Exemple #33
0
    def __edit_project(self, data):
        component = data.get('component').name
        all_projects = self.__SmpModel.get_all_projects()
        id_project_component = self.__SmpModel.get_id_projects_component(component)
        id_projects_selected = []

        for id_project in id_project_component:
            id_projects_selected.append(id_project[0])

        return tag.div(
                       tag.label(
                       'Available in Project(s):',
                       tag.br(),
                       tag.select(
                       tag.option("All", value="0"),
                       [tag.option(row[1], selected=(row[0] in id_projects_selected or None), value=row[0]) for row in sorted(all_projects, key=itemgetter(1))],
                       name="project", multiple="multiple", size="10")
                       ),
                       class_="field")
Exemple #34
0
def _render_change(old, new):
    rendered = None
    if old and not new:
        rendered = tag(Markup(_("%(value)s reset to default value",
                                value=tag.em(old))))
    elif new and not old:
        rendered = tag(Markup(_("from default value set to %(value)s",
                                value=tag.em(new))))
    elif old and new:
        if len(old) < 20 and len(new) < 20:
            rendered = tag(Markup(_("changed from %(old)s to %(new)s",
                                    old=tag.em(old), new=tag.em(new))))
        else:
            nbsp = tag.br()
            # TRANSLATOR: same as before, but with additional line breaks
            rendered = tag(Markup(_("changed from %(old)s to %(new)s",
                                    old=tag.em(nbsp, old),
                                    new=tag.em(nbsp, new))))
    return rendered
 def _user_field_input(self, req):
     return tag.div(tag.label("Include users: ",
                              tag.input(type="text",
                                        name="inc_users",
                                        value=req.session.get('timeline.filter.inc_users',''),
                                        style_="width:60%"
                                       )
                             )
                    +
                    tag.br()
                    +
                    tag.label("Exclude users: ",
                              tag.input(type="text",
                                        name="exc_users",
                                        value=req.session.get('timeline.filter.exc_users',''),
                                        style_="width:60%"
                                       )
                             )
                   )                    
                                
Exemple #36
0
    def __edit_project(self, data):
        milestone = data.get('milestone').name
        all_projects = self.__SmpModel.get_all_projects()
        id_project_milestone = self.__SmpModel.get_id_project_milestone(milestone)

        if id_project_milestone != None:
            id_project_selected = id_project_milestone[0]
        else:
            id_project_selected = None

        return tag.div(
                       tag.label(
                       'Project:',
                       tag.br(),
                       tag.select(
                       tag.option(),
                       [tag.option(row[1], selected=(id_project_selected == row[0] or None), value=row[0]) for row in sorted(all_projects, key=itemgetter(1))],
                       name="project")
                       ),
                       class_="field")
Exemple #37
0
    def __edit_project(self, data):
        version = data.get('version').name
        all_projects = self.__SmpModel.get_all_projects()
        id_project_version = self.__SmpModel.get_id_project_version(version)

        if id_project_version != None:
            id_project_selected = id_project_version[0]
        else:
            id_project_selected = None

        return tag.div(tag.label(
            'Project:', tag.br(),
            tag.select(tag.option(), [
                tag.option(row[1],
                           selected=(id_project_selected == row[0] or None),
                           value=row[0])
                for row in sorted(all_projects, key=itemgetter(1))
            ],
                       name="project")),
                       class_="field")
Exemple #38
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)
Exemple #39
0
    def _version_edit(self, data):
        milestone = data.get('milestone').name
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute("SELECT version FROM milestone_version WHERE milestone=%s", (milestone,))
        row = cursor.fetchone()
        value = row and row[0]

        cursor.execute("SELECT name FROM version WHERE time IS NULL OR time = 0 OR time>%s "
                       "OR name = %s ORDER BY name",
                       (to_timestamp(None), value))

        return tag.div(
            tag.label(
                'Version:',
                tag.br(),
                tag.select(
                    tag.option(),
                    [tag.option(row[0], selected=(value == row[0] or None)) for row in cursor],
                    name="version")),
            class_="field")
Exemple #40
0
    def filter_stream(self, req, method, filename, stream, data):
        if req.path_info.startswith('/register') and (
            req.method == 'GET' or
            'registration_error' in data):
            question = None
            if self.question is not None and len(self.question)>0:
                question = tag.label(
                    tag(self.question + " "),
                    tag.input(id='question', type='text', name='question')
                    )
            # First Fieldset of the registration form XPath match
            xpath_match = '//form[@id="acctmgr_registerform"]/fieldset[1]'
            if question is None:
                return stream
            else:
                return stream | Transformer(xpath_match). \
                    append(tag(Markup(question)))
        # Admin Configuration
        elif req.path_info.startswith('/admin/accounts/config'):
            api_html = tag.div(
                tag.label("Question:", for_="registerquestion_question") +
                tag.input(class_="textwidget", name="question",
                          value=self.question, size=60)
            ) + tag.div(
                tag.label("Answer:", for_="registerquestion_answer") +
                tag.input(class_="textwidget", name="answer",
                          value=self.answer, size=60)
            ) + tag.div(
                tag.label("Hint:", for_="registerquestion_hint") +
                tag.input(class_="textwidget", name="hint",
                          value=self.hint, size=60)
            ) + tag.br()


            # First fieldset of the Account Manager config form
            xpath_match = '//form[@id="accountsconfig"]/fieldset[1]'

            return stream | Transformer(xpath_match). \
                before(tag.fieldset(tag.legend("Anti-Robot Question For Registration") + api_html))
        return stream
Exemple #41
0
    def filter_stream(self, req, method, filename, stream, data):
        if req.path_info.startswith('/register') and (
                req.method == 'GET' or 'registration_error' in data):
            question = None
            if self.question is not None and len(self.question) > 0:
                question = tag.label(
                    tag(self.question + " "),
                    tag.input(id='question', type='text', name='question'))
            # First Fieldset of the registration form XPath match
            xpath_match = '//form[@id="acctmgr_registerform"]/fieldset[1]'
            if question is None:
                return stream
            else:
                return stream | Transformer(xpath_match). \
                    append(tag(Markup(question)))
        # Admin Configuration
        elif req.path_info.startswith('/admin/accounts/config'):
            api_html = tag.div(
                tag.label("Question:", for_="registerquestion_question") +
                tag.input(class_="textwidget",
                          name="question",
                          value=self.question,
                          size=60)
            ) + tag.div(
                tag.label("Answer:", for_="registerquestion_answer") +
                tag.input(class_="textwidget",
                          name="answer",
                          value=self.answer,
                          size=60)
            ) + tag.div(
                tag.label("Hint:", for_="registerquestion_hint") + tag.input(
                    class_="textwidget", name="hint", value=self.hint, size=60)
            ) + tag.br()

            # First fieldset of the Account Manager config form
            xpath_match = '//form[@id="accountsconfig"]/fieldset[1]'

            return stream | Transformer(xpath_match). \
                before(tag.fieldset(tag.legend("Anti-Robot Question For Registration") + api_html))
        return stream
 def _user_field_input(self, req):
     return tag.div(
         tag.label(
             "Include users: ",
             tag.input(
                 type="text",
                 name="inc_users",
                 value=req.session.get("timeline.filter.inc_users", ""),
                 style_="width:60%",
             ),
         )
         + tag.br()
         + tag.label(
             "Exclude users: ",
             tag.input(
                 type="text",
                 name="exc_users",
                 value=req.session.get("timeline.filter.exc_users", ""),
                 style_="width:60%",
             ),
         )
     )
Exemple #43
0
    def __edit_project(self, data):
        component = data.get('component').name
        all_projects = self.__SmpModel.get_all_projects()
        id_project_component = self.__SmpModel.get_id_projects_component(
            component)
        id_projects_selected = []

        for id_project in id_project_component:
            id_projects_selected.append(id_project[0])

        return tag.div(tag.label(
            'Available in Project(s):', tag.br(),
            tag.select(tag.option("All", value="0"), [
                tag.option(row[1],
                           selected=(row[0] in id_projects_selected or None),
                           value=row[0])
                for row in sorted(all_projects, key=itemgetter(1))
            ],
                       name="project",
                       multiple="multiple",
                       size="10")),
                       class_="field")
Exemple #44
0
    def _version_edit(self, data):
        milestone = data.get('milestone').name
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute(
            "SELECT version FROM milestone_version WHERE milestone=%s",
            (milestone, ))
        row = cursor.fetchone()
        value = row and row[0]

        cursor.execute(
            "SELECT name FROM version WHERE time IS NULL OR time = 0 OR time>%s "
            "OR name = %s ORDER BY name", (to_timestamp(None), value))

        return tag.div(tag.label(
            'Version:', tag.br(),
            tag.select(tag.option(), [
                tag.option(row[0], selected=(value == row[0] or None))
                for row in cursor
            ],
                       name="version")),
                       class_="field")
Exemple #45
0
    def _customize_View(self, stream):

        filter = Transformer('.//div [@id="banner"]')
        stream = stream | filter.wrap(self.css_banner_top2)

        buffer = StreamBuffer()
        stream = stream | Transformer('.//div [@id="banner"]').copy(buffer) \
              .end().select('.//div [@id="top2"]') \
              .after(tag.div(id_='top1')(buffer))

        filter = Transformer('.//div [@id="mainnav"]')
        stream = stream | filter.wrap(self.css_banner_top4)

        buffer = StreamBuffer()
        stream = stream | Transformer('.//div [@id="mainnav"]').copy(buffer) \
              .end().select('.//div [@id="top4"]') \
              .after(tag.div(id_='top3')(buffer))

        filter = Transformer('.//div [@id="top3"]')
        stream = stream | filter.after(tag.div(id_='right')(tag.p()))

        filter = Transformer('.//div [@id="right"]')
        stream = stream | filter. \
            append(tag.div(class_='wiki-toc')(tag.h4(_('Table of Contents'))))

        # just for the menu / TOC
        filter = Transformer('.//div [@class="wiki-toc"]')

        if self.anchors and self.keylist:
            for key in self.keylist:
                stream = stream | filter.append(
                    tag.a(key,
                          href='#' + self.anchors.get(key),
                          onclick="scrollup();") + tag.br())
        filter = Transformer('.//div [@id="main"]')
        stream = stream | filter.wrap(self.css_left)

        return stream
Exemple #46
0
 def __linkify_ids_p(self, ids, data):
     # チケットの表示のページでinterTracリンクの表示するための元を作る
     # 先行、親など指定しているidを検索する
     if not ids:
         del data[-1]
         return
     tickets = ids.split(',') 
     #なにもない場合はエラーになるのでifが必要
     for ticket in tickets:
         if not ticket:
             continue
         t = self.__get_intertrac_ticket(ticket, True)
         error = t['error']
         if error is None:
             tkt = t['ticket']
             status = tkt['status']
             title1 = tkt['summary']
             data.append(tag.a(ticket, href=t['url'], class_='%s ticket'%status, title=title1))
             data.append(', ')
     if data:
         # 最後のカンマを削除する.
         del data[-1]
     data.append(tag.br())
Exemple #47
0
	def launch(self, proc_cmd, encoded_input, *args):
		"""Launch a process (cmd), and returns exitcode, stdout + stderr"""
		# Note: subprocess.Popen doesn't support unicode options arguments
		# (http://bugs.python.org/issue1759845) so we have to encode them.
		# Anyway, dot expects utf-8 or the encoding specified with -Gcharset.
		encoded_cmd = proc_cmd
		proc = subprocess.Popen(encoded_cmd, stdin=subprocess.PIPE,
			stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		if encoded_input:
			proc.stdin.write(encoded_input)
		proc.stdin.close()
		out = proc.stdout.read()
		err = proc.stderr.read()
		failure = proc.wait() != 0
		if failure or err or out:
			return (failure, tag.div(tag.br(), _("The command:"), 
				tag.pre(repr(' '.join(encoded_cmd))), 
					       (_("succeeded but emitted the following output:"),
						_("failed with the following output:"))[failure],
					       out and tag.pre(out), 
					       err and tag.pre(err), class_="system-message"))
		else:
			return (False, None)
Exemple #48
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)
Exemple #49
0
    def render_property(self, name, mode, context, props):
        def sha_link(sha, label=None):
            # sha is assumed to be a non-abbreviated 40-chars sha id
            try:
                reponame = context.resource.parent.id
                repos = self.env.get_repository(reponame)
                cset = repos.get_changeset(sha)
                if label is None:
                    label = repos.display_rev(sha)

                return tag.a(label,
                             class_='changeset',
                             title=shorten_line(cset.message),
                             href=context.href.changeset(sha, repos.reponame))

            except Exception as e:
                return tag.a(sha,
                             class_='missing changeset',
                             title=to_unicode(e),
                             rel='nofollow')

        if name == 'Branches':
            branches = props[name]

            # simple non-merge commit
            return tag(*intersperse(', ', (sha_link(rev, label)
                                           for label, rev in branches)))

        elif name in ('Parents', 'Children'):
            revs = props[name]  # list of commit ids

            if name == 'Parents' and len(revs) > 1:
                # we got a merge...
                current_sha = context.resource.id
                reponame = context.resource.parent.id

                parent_links = intersperse(', ', \
                    ((sha_link(rev),
                      ' (',
                      tag.a(_("diff"),
                            title=_("Diff against this parent (show the "
                                    "changes merged from the other parents)"),
                            href=context.href.changeset(current_sha, reponame,
                                                        old=rev)),
                      ')')
                     for rev in revs))

                return tag(
                    list(parent_links), tag.br(),
                    tag.span(Markup(
                        _("Note: this is a <strong>merge"
                          "</strong> changeset, the "
                          "changes displayed below "
                          "correspond to the merge "
                          "itself.")),
                             class_='hint'), tag.br(),
                    tag.span(Markup(
                        _("Use the <code>(diff)</code> "
                          "links above to see all the "
                          "changes relative to each "
                          "parent.")),
                             class_='hint'))

            # simple non-merge commit
            return tag(*intersperse(', ', map(sha_link, revs)))

        elif name in ('git-committer', 'git-author'):
            user_, time_ = props[name]
            _str = "%s (%s)" % (Chrome(self.env).format_author(
                context.req,
                user_), format_datetime(time_, tzinfo=context.req.tz))
            return unicode(_str)

        raise TracError(_("Internal error"))
    def filter_stream(self, req, method, filename, stream, data):
        if filename == "ticket.html":
            ##Check Permissions
            enchants = self.config.get('blackmagic', 'tweaks', '')
            for field in (x.strip() for x in enchants.split(',')):
                self.env.log.debug("Checking %s:" % field)
                disabled = False
                hidden = False
                #Get a list of the permissions from the config, split them on commas and remove spaces
                perms = self.config.get('blackmagic', '%s.permission' % field, '').upper()
                #Default to not having permissions
                hasPerm = True
                if perms:
                    hasPerm = False
                    #If there are permissions
                    self.env.log.debug("perm: %s" % len(perms))
                    perms = perms.split(',')
                    #walk the list we got back and check the request for the permission
                    for perm in perms:
                        perm = perm.strip()
                        self.env.log.debug("Checking perm: %s" % perm)
                        if perm in req.perm:
                            self.env.log.debug("User has perm: %s" % perm)
                            hasPerm = True
                    if hasPerm == False:
                        denial = self.config.get('blackmagic', '%s.ondenial' % field, None)
                        if denial:
                            if denial == "disable":
                                disabled = True
                            elif denial == "hide":
                                hidden = True
                            else:
                                disabled = True
                        else:
                            disabled = True

                self.env.log.debug('hasPerm: %s' % hasPerm)
                if hidden == False:
                    if self.config.get('blackmagic', '%s.label' % field, None):
                        labelTXT = self.config.get('blackmagic', '%s.label' % field)
                        label = tag.label("%s:" %labelTXT, for_="field-%s" % field)
                        stream = stream | Transformer('//label[@for="field-%s"]' % field).replace(label)

                if hasPerm == False:   
                    if istrue(self.config.get('blackmagic', '%s.hide' % field, None)):
                        hidden = True
                        
                    if disabled or istrue(self.config.get('blackmagic', '%s.disable' % field, False)):
                        stream = stream | Transformer('//*[@id="field-%s"]' % field).attr("disabled", "disabled")
                        label = self.config.get('blackmagic', '%s.label' % field)
                        if not label:
                            label = field.capitalize()
                        if not self.gray_disabled:
                            stream = stream | Transformer('//label[@for="field-%s"]' % field).replace(
                                tag.strike()('%s:' % label)
                            )
                        else:
                            stream = stream | Transformer('//label[@for="field-%s"]' % field).replace(
                                tag.span(style="color:%s" % self.gray_disabled)('%s:' % label)
                            )
                    
                    if hidden or istrue(self.config.get('blackmagic', '%s.hide' % field, None)):
                        stream = stream | Transformer('//th[@id="h_%s"]' % field).replace(" ") 
                        stream = stream | Transformer('//td[@headers="h_%s"]' % field).replace(" ")
                        stream = stream | Transformer('//label[@for="field-%s"]' % field).replace(" ")
                        stream = stream | Transformer('//*[@id="field-%s"]' % field).replace(" ")

                    
                if hidden == False:
                    if self.config.get('blackmagic', '%s.notice' % field, None):
                        stream = stream | Transformer('//*[@id="field-%s"]' % field).after(
                            tag.br() + tag.small(class_="notice-%s" %field)(
                                tag.em()(
                                    Markup(self.config.get('blackmagic', '%s.notice' % field))
                                )
                            )
                        )
                    
                tip = self.config.get('blackmagic', '%s.tip' % field, None)
                if tip:
                    stream = stream | Transformer('//div[@id="banner"]').before(
                        tag.script(type="text/javascript", 
                        src=req.href.chrome("blackmagic", "js", "wz_tooltip.js"))()
                    )
                    
                    stream = stream | Transformer('//*[@id="field-%s"]' % field).attr(
                        "onmouseover", "Tip('%s')" % tip.replace(r"'", r"\'")
                    )
                        
                    
        return stream
Exemple #51
0
    def expand_macro(self, formatter, name, arguments):

        self.ref = formatter
        self.tz_info = formatter.req.tz
        self.thistime = datetime.datetime.now(self.tz_info)

        # Add CSS stylesheet
        add_stylesheet(self.ref.req,
            'wikiticketcalendar/css/wikiticketcalendar.css')


        # Parse arguments from macro invocation
        args, kwargs = parse_args(arguments, strict=False)

        # Find out whether use http param, current or macro param year/month
        http_param_year = formatter.req.args.get('year','')
        http_param_month = formatter.req.args.get('month','')

        if http_param_year == "":
            # not clicked on a prev or next button
            if len(args) >= 1 and args[0] <> "*":
                # year given in macro parameters
                year = int(args[0])
            else:
                # use current year
                year = self.thistime.year
        else:
            # year in http params (clicked by user) overrides everything
            year = int(http_param_year)

        if http_param_month == "":
            # not clicked on a prev or next button
            if len(args) >= 2 and args[1] <> "*":
                # month given in macro parameters
                month = int(args[1])
            else:
                # use current month
                month = self.thistime.month
        else:
            # month in http params (clicked by user) overrides everything
            month = int(http_param_month)

        showbuttons = True
        if len(args) >= 3 or kwargs.has_key('nav'):
            try:
                showbuttons = kwargs['nav'] in ["True", "true", "yes", "1"]
            except KeyError:
                showbuttons = args[2] in ["True", "true", "yes", "1"]

        wiki_page_format = "%Y-%m-%d"
        if len(args) >= 4 and args[3] != "*" or kwargs.has_key('wiki'):
            try:
                wiki_page_format = str(kwargs['wiki'])
            except KeyError:
                wiki_page_format = str(args[3])

        show_t_open_dates = True
        if len(args) >= 5 or kwargs.has_key('cdate'):
            try:
                show_t_open_dates = kwargs['cdate'] in \
                                               ["True", "true", "yes", "1"]
            except KeyError:
                show_t_open_dates = args[4] in ["True", "true", "yes", "1"]

        # template name tried to create new pages
        # optional, default (empty page) is used, if name is invalid
        wiki_page_template = ""
        if len(args) >= 6 or kwargs.has_key('base'):
            try:
                wiki_page_template = kwargs['base']
            except KeyError:
                wiki_page_template = args[5]

        # TracQuery support for ticket selection
        query_args = "id!=0"
        if len(args) >= 7 or kwargs.has_key('query'):
            # prefer query arguments provided by kwargs
            try:
                query_args = kwargs['query']
            except KeyError:
                query_args = args[6]
        self.tickets = self._ticket_query(formatter, query_args)

        # compress long ticket lists
        list_condense = 0
        if len(args) >= 8 or kwargs.has_key('short'):
            # prefer query arguments provided by kwargs
            try:
                list_condense = int(kwargs['short'])
            except KeyError:
                list_condense = int(args[7])

        # control calendar display width
        cal_width = "100%;"
        if len(args) >= 9 or kwargs.has_key('width'):
            # prefer query arguments provided by kwargs
            try:
                cal_width = kwargs['width']
            except KeyError:
                cal_width = args[8]


        # Can use this to change the day the week starts on,
        # but this is a system-wide setting.
        calendar.setfirstweekday(calendar.MONDAY)
        cal = calendar.monthcalendar(year, month)

        curr_day = None
        if year == self.thistime.year and month == self.thistime.month:
            curr_day = self.thistime.day

        # Compile regex pattern before use for better performance
        pattern_del  = '(?:<span .*?>)|(?:</span>)'
        pattern_del += '|(?:<p>)|(?:<p .*?>)|(?:</p>)'
        pattern_del += '|(?:</table>)|(?:<td.*?\n)|(?:<tr.*?</tr>)'
        self.end_RE  = re.compile('(?:</a>)')
        self.del_RE  = re.compile(pattern_del)
        self.item_RE = re.compile('(?:<img .*?>)')
        self.open_RE = re.compile('(?:<a .*?>)')
        self.tab_RE  = re.compile('(?:<table .*?>)')

        # for prev/next navigation links
        prevMonth = month - 1
        nextMonth = month + 1
        nextYear = prevYear = year
        # check for year change (KISS version)
        if prevMonth == 0:
            prevMonth = 12
            prevYear -= 1
        if nextMonth == 13:
            nextMonth = 1
            nextYear += 1

        # for fast-forward/-rewind navigation links
        ffYear = frYear = year
        if month < 4:
            frMonth = month + 9
            frYear -= 1
        else:
            frMonth = month - 3
        if month > 9:
            ffMonth = month - 9
            ffYear += 1
        else:
            ffMonth = month + 3


        # Finally building the output
        # Begin with caption and optional navigation links
        buff = tag.caption()

        if showbuttons is True:
            # calendar navigation buttons
            nx = 'next'
            pv = 'prev'
            nav_pvY = self._mknav('&nbsp;&lt;&lt;', pv, month, year-1)
            nav_frM = self._mknav('&nbsp;&lt;&nbsp;', pv, frMonth, frYear)
            nav_pvM = self._mknav('&nbsp;&laquo;&nbsp;', pv, prevMonth,
                                                                 prevYear)
            nav_nxM = self._mknav('&nbsp;&raquo;&nbsp;', nx, nextMonth,
                                                                 nextYear)
            nav_ffM = self._mknav('&nbsp;&gt;&nbsp;', nx, ffMonth, ffYear)
            nav_nxY = self._mknav('&nbsp;&gt;&gt;', nx, month, year+1)

            # add buttons for going to previous months and year
            buff(nav_pvY, nav_frM, nav_pvM)

        # The caption will always be there.
        buff(tag.strong(to_unicode(format_date(self._mkdatetime(
                                               year, month), '%B %Y'))))

        if showbuttons is True:
            # add buttons for going to next months and year
            buff(nav_nxM, nav_ffM, nav_nxY)

        buff = tag.table(buff)
        width=":".join(['min-width', cal_width]) 
        buff(class_='wikiTicketCalendar', style=width)

        heading = tag.tr()
        heading(align='center')

        for day in calendar.weekheader(2).split()[:-2]:
            col = tag.th(day)
            col(class_='workday', scope='col')
            heading(col)
        for day in calendar.weekheader(2).split()[-2:]:
            col = tag.th(day)
            col(class_='weekend', scope='col')
            heading(col)

        heading = buff(tag.thead(heading))

        # Building main calendar table body
        buff = tag.tbody()
        for row in cal:
            line = tag.tr()
            line(align='right')
            for day in row:
                if not day:
                    cell = tag.td('')
                    cell(class_='fill')
                    line(cell)
                else:
                    # check for wikipage with name specified in
                    # 'wiki_page_format'
                    wiki = format_date(self._mkdatetime(year, month, day),
                                                         wiki_page_format)
                    url = self.env.href.wiki(wiki)
                    if WikiSystem(self.env).has_page(wiki):
                        a_class = "day_haspage"
                        title = _("Go to page %s") % wiki
                    else:
                        a_class = "day"
                        url += "?action=edit"
                        # adding template name, if specified
                        if wiki_page_template != "":
                            url += "&template=" + wiki_page_template
                        title = _("Create page %s") % wiki
                    if day == curr_day:
                        td_class = 'today'
                    else:
                        td_class = 'day'

                    cell = tag.a(tag.b(day), href=url)
                    cell(class_=a_class, title_=title)
                    cell = tag.td(cell)
                    cell(class_=td_class, valign='top')

                    day_dt = self._mkdatetime(year, month, day)
                    day_ts = to_utimestamp(day_dt)
                    day_ts_eod = day_ts + 86399999999

                    # check for milestone(s) on that day
                    db = self.env.get_db_cnx()
                    cursor = db.cursor()
                    cursor.execute("""
                        SELECT name
                          FROM milestone
                         WHERE due >= %s and due <= %s
                    """, (day_ts, day_ts_eod))
                    while (1):
                        row = cursor.fetchone()
                        if row is None:
                            cell(tag.br())
                            break
                        else:
                            name = to_unicode(row[0])
                            url = self.env.href.milestone(name)
                            milestone = '* ' + name
                            milestone = tag.div(tag.a(milestone, href=url))
                            milestone(class_='milestone')

                            cell(milestone)

                    match = []
                    match_od = []
                    ticket_heap = tag('')
                    ticket_list = tag.div('')
                    ticket_list(align='left', class_='condense')

                    # get tickets with due date set to day
                    for t in self.tickets:
                        due = t.get(self.due_field_name)
                        if due is None or due in ['', '--']:
                            continue
                        else:
                            if self.due_field_fmt == 'ts':
                                if not isinstance(due, datetime.datetime):
                                    continue
                                due_ts = to_utimestamp(due)
                                if due_ts < day_ts or \
                                    due_ts > day_ts_eod:
                                    continue
                            else:
                                duedate = format_date(day_dt,
                                                      self.due_field_fmt)
                                if not due == duedate:
                                    continue

                        id = t.get('id')
                        ticket, short = self._gen_ticket_entry(t)
                        ticket_heap(ticket)
                        if not id in match:
                            if len(match) == 0:
                                ticket_list(short)
                            else:
                                ticket_list(', ', short)
                            match.append(id)

                    # optionally get tickets created on day
                    if show_t_open_dates is True:
                        ticket_od_list = tag.div('')
                        ticket_od_list(align='left',
                                       class_='opendate_condense')

                        for t in self.tickets:
                            ticket_ts = to_utimestamp(t.get('time'))
                            if ticket_ts < day_ts or ticket_ts > day_ts_eod:
                                continue

                            a_class = 'opendate_'
                            id = t.get('id')
                            ticket, short = self._gen_ticket_entry(t, a_class)
                            ticket_heap(ticket)
                            if not id in match:
                                if len(match_od) == 0:
                                    ticket_od_list(short)
                                else:
                                    ticket_od_list(', ', short)
                                match_od.append(id)

                    matches = len(match) + len(match_od)
                    if list_condense > 0 and matches >= list_condense:
                        if len(match_od) > 0:
                            if len(match) > 0:
                                ticket_list(', ')
                            ticket_list = tag(ticket_list, ticket_od_list)
                        line(cell(ticket_list))
                    else:
                        line(cell(ticket_heap))

            buff(line)

        buff = tag.div(heading(buff))
        if cal_width.startswith('+') is True:
            width=":".join(['width', cal_width]) 
            buff(class_='wikiTicketCalendar', style=width)
        else:
            buff(class_='wikiTicketCalendar')

        return buff
Exemple #52
0
    def filter_stream(self, req, method, filename, stream, data):

        field_name = self._get_field_name(req.args)

        if 'TICKET_ADMIN' in req.perm and field_name and \
           req.path_info.startswith('/admin/ticket'):

            if field_name in self._non_abstract_enums:
                field_objects = data.get(field_name + 's')
            else:
                field_objects = data.get('enums')

            default_ccs = DefaultCC.select(self.env, field_name)

            if field_objects:
                # list of field objects

                stream = stream | Transformer(
                    '//table[@class="listing"]/thead/tr').append(
                        tag.th('CC'))

                if field_name == 'component':
                    transformer = Transformer('//table[@id="complist"]/tbody')
                    default_comp = self.config.get(
                        'ticket', 'default_component')

                for idx, field_object in enumerate(field_objects):

                    # Milestone object can be a tuple :/
                    try:
                        field_object_name = field_object.name
                    except AttributeError:
                        field_object_name = field_object[0].name

                    if field_object_name in default_ccs:
                        default_cc = default_ccs[field_object_name]
                    else:
                        default_cc = ''

                    # Annoyingly, we can't just append to the row if the
                    # collection is components, it appears to blat it for
                    # rendering later so you end up with no rows
                    # This may be due to the collection being a generator,
                    # but then again, who knows?
                    if field_name == 'component':

                        if default_comp == field_object_name:
                            default_tag = tag.input(
                                type='radio', name='default',
                                value=field_object_name, checked='checked')
                        else:
                            default_tag = tag.input(
                                type='radio', name='default',
                                value=field_object_name)

                        transformer = transformer.append(
                            tag.tr(
                                tag.td(
                                    tag.input(type='checkbox', name='sel',
                                              value=field_object_name),
                                    class_='sel'),
                                tag.td(
                                    tag.a(field_object_name,
                                          href=req.href.admin(
                                              'ticket', 'components') + '/' + \
                                          field_object_name),
                                    class_='name'),
                                tag.td(field_object.owner, class_='owner'),
                                tag.td(default_tag, class_='default'),
                                tag.td(default_cc, class_='defaultcc')
                            )
                        )

                    else:
                        stream = stream | Transformer(
                            '//table[@class="listing"]/tbody/tr[%s]' % (idx+1,)
                            ).append(tag.td(default_cc, class_='defaultcc'))

                if field_name == 'component':
                    return stream | transformer

            else:
                # edit field object
                if field_name in self._non_abstract_enums:
                    field_object = data.get(field_name)
                else:
                    field_object = data.get('enum')

                if field_object:

                    # Milestone object can be a tuple :/
                    try:
                        field_object_name = field_object.name
                    except AttributeError:
                        field_object_name = field_object[0]

                    if field_object_name in default_ccs:
                        default_cc = default_ccs[field_object_name]
                    else:
                        default_cc = ''

                    transformer = Transformer(
                        '//form[@class="mod"]/fieldset/div[@class="buttons"]')
                    transformer = transformer.before(
                        tag.div(tag.label("Default CC:"), tag.br(),
                                tag.input(type="text", name="defaultcc",
                                          value=default_cc),
                                class_="field")
                        ).before(tag.input(type='hidden', name='old_name',
                                           value=field_object_name))

                    return stream | transformer

        return stream
    def filter_stream(self, req, method, filename, stream, data):
        if req.path_info.startswith('/register') and (
            req.method == 'GET' or
            'registration_error' in data or
            'captcha_error' in req.session):
            if not (self.private_key or self.private_key):
                return stream
            captcha_opts = tag.script("""\
var RecaptchaOptions = {
  theme: "%s",
  lang: "%s"
}""" % (self.theme, self.lang), type='text/javascript')
            captcha_js = captcha.displayhtml(
                self.public_key, use_ssl=True,
                error='reCAPTCHA incorrect. Please try again.'
            )
            # First Fieldset of the registration form XPath match
            xpath_match = '//form[@id="acctmgr_registerform"]/fieldset[1]'
            return stream | Transformer(xpath_match). \
                append(captcha_opts + tag(Markup(captcha_js)))
        # Admin Configuration
        elif req.path_info.startswith('/admin/accounts/config'):
            api_html = tag.div(
                tag.label("Public Key:", for_="recaptcha_public_key") +
                tag.input(class_="textwidget", name="recaptcha_public_key",
                          value=self.public_key, size=40)
            ) + tag.div(
                tag.label("Private Key:", for_="recaptcha_private_key") +
                tag.input(class_="textwidget", name="recaptcha_private_key",
                          value=self.private_key, size=40)
            )
            if not (self.private_key or self.public_key):
                api_html = tag.div(
                    tag.a("Generate a reCAPTCHA API key for this Trac "
                          "instance domain.", target="_blank",
                          href="https://recaptcha.net/api/getkey?domain=%s&"
                            "app=TracRecaptchaRegister" %
                            req.environ.get('SERVER_NAME')
                    )
                ) + tag.br() + api_html

            theme_html = tag.div(
                tag.label("reCPATCHA theme:", for_='recaptcha_theme') +
                tag.select(
                    tag.option("Black Glass",
                               value="blackglass",
                               selected=self.theme=='blackglass' or None) +
                    tag.option("Clean",
                               value="clean",
                               selected=self.theme=='clean' or None) +
                    tag.option("Red",
                               value="red",
                               selected=self.theme=='red' or None) +
                    tag.option("White",
                               value="white",
                               selected=self.theme=='white' or None),
                    name='recaptcha_theme'
                )
            )

            language_html = tag.div(
                tag.label("reCAPTCHA language:", for_='recaptcha_lang') +
                tag.select(
                    tag.option("Dutch",
                               value="nl",
                               selected=self.lang=='nl' or None) +
                    tag.option("English",
                               value="en",
                               selected=self.lang=='en' or None) +
                    tag.option("French",
                               selected=self.lang=='fr' or None) +
                    tag.option("German",
                               value="de",
                               selected=self.lang=='de' or None) +
                    tag.option("Portuguese",
                               value="pt",
                               selected=self.lang=='pt' or None) +
                    tag.option("Russian",
                               value="ru",
                               selected=self.lang=='ru' or None) +
                    tag.option("Spanish",
                               value="es",
                               selected=self.lang=='es' or None) +
                    tag.option("Turkish",
                               value="tr",
                               selected=self.lang=='tr' or None),
                    name='recaptcha_lang'))

            # First fieldset of the Account Manager config form
            xpath_match = '//form[@id="accountsconfig"]/fieldset[1]'

            return stream | Transformer(xpath_match). \
                before(tag.fieldset(tag.legend("reCAPTCHA") + api_html +
                                    tag.br() + theme_html + language_html))
        return stream
 def filter_stream(self, req, method, filename, stream, data):
     if filename == 'timeline.html':
         # Insert the new field for entering user names
         filter = Transformer('//form[@id="prefs"]/fieldset')
         return stream | filter.before(tag.br()) | filter.before(tag.label("Filter Components (none for all): ")) | filter.before(tag.br()) | filter.before(self._components_field_input(req))
     return stream