def expand_macro(self, formatter, name, arguments): self.mc.options(arguments) extras = self.mc.extras() extra = '' if 'extra' in extras: extra = extras['extra'] return tag.div( tag.h3('[[%s(%s)]]' % (name, arguments)), tag.table(tag.tr(tag.th('Name'), tag.th('Value'), tag.th('Qualified'), tag.th('Default?'), tag.th('Macroarg?'), tag.th('Extra?'), tag.th('Known?'), tag.th('Default'), tag.th('Documentation')), self._show_option('text', self.mo_text, TracMacroConfigExample.mo_text), self._show_option('bool', self.mo_bool, TracMacroConfigExample.mo_bool), self._show_option('int', self.mo_int, TracMacroConfigExample.mo_int), self._show_option('list', self.mo_list, TracMacroConfigExample.mo_list), self._show_option('nodtext', self.mo_nodtext, TracMacroConfigExample.mo_nodtext), self._show_option('nodbool', self.mo_nodbool, TracMacroConfigExample.mo_nodbool), self._show_option('nodint', self.mo_nodint, TracMacroConfigExample.mo_nodint), self._show_option('nodlist', self.mo_nodlist, TracMacroConfigExample.mo_nodlist), self._show_extra('extra', extra), border=1, cellpadding=1, cellspacing=0))
def expand_macro(self, formatter, name, args): from trac.config import Option section_filter = key_filter = '' args, kw = parse_args(args) if args: section_filter = args.pop(0).strip() if args: key_filter = args.pop(0).strip() registry = Option.get_registry(self.compmgr) sections = {} for (section, key), option in registry.iteritems(): if section.startswith(section_filter): sections.setdefault(section, {})[key] = option return tag.div(class_='tracini')( (tag.h3(tag.code('[%s]' % section), id='%s-section' % section), tag.table(class_='wiki')( tag.tbody(tag.tr(tag.td(tag.tt(option.name)), tag.td(format_to_oneliner( self.env, formatter.context, to_unicode(option.__doc__)))) for option in sorted(sections[section].itervalues(), key=lambda o: o.name) if option.name.startswith(key_filter)))) for section in sorted(sections))
def _generate_html(self, relation, relation_type, relation_role, stream, ticket): config = self.config['ticket-custom'] try: if relation_type == 'one': if ticket[relation.name + '_' + relation_role] is not None: target_ticket = Ticket(self.env, int(ticket[relation.name + '_' + relation_role])) stream |= Transformer('//div[@id="ticket"]//td[@headers="h_%s"]/text()' % (relation.name + '_' + relation_role)) \ .replace(tag.a('#%s %s' % (target_ticket.id, target_ticket['summary']), href='/ticket/' + str(target_ticket.id))) else: if ticket[relation.name + '_' + relation_role] is not None: target_tickets = [Ticket(self.env, int(i)) for i in ticket[relation.name + '_' + relation_role].split(',')] format = map(unicode.strip, config.get(relation.name + '_' + relation_role + '.format').split(',')) tbody = tag.tbody() for target_ticket in target_tickets: columns = [tag.td(tag.a('#' + str(target_ticket.id), href='/ticket/' + str(target_ticket.id)))] columns.extend([tag.td(target_ticket[field]) for field in format]) tbody.append(tag.tr(*columns)) stream |= Transformer('//div[@id="ticket"]//td[@headers="h_%s"]/text()' % (relation.name + '_' + relation_role)) \ .replace(tag.table(tbody, class_='relation_table')) except Exception as e: self.log.error(e.message) return stream
def htmlSeq(self,s,insideTable): from genshi.builder import tag table=tag.table(frame='box',rules='all',width='100%',**self.padding) if hasattr(s[0],'__len__') and not isinstance(s[0],str): # 2d array # disregard insideTable in this case for r in range(len(s) if type(s)!=AlignedBox3 else 2): # len(s) is sufficient, but some version of minieigen report erroneously that AlignedBox3 has length of 3 tr=tag.tr() for c in range(len(s[0])): tr.append(tag.td(float2str(s[r][c]) if isinstance(s[r][c],float) else str(s[r][c]),align='right',width='%g%%'%(100./len(s[0])-1.))) table.append(tr) return table splitLen=0 if len(s)>1: if isinstance(s[0],int): splitLen=self.splitIntSeq elif isinstance(s[0],str): splitLen=self.splitStrSeq elif isinstance(s[0],float): splitLen=self.splitFloatSeq # 1d array if splitLen==0 or len(s)<splitLen: ret=table if not insideTable else [] for e in s: ret.append(tag.td(float2str(e) if isinstance(e,float) else str(e),align='right',width='%g%%'%(100./len(s)-1.))) # 1d array, but with lines broken else: ret=table for i,e in enumerate(s): if i%splitLen==0: tr=tag.tr() tr.append(tag.td(float2str(e) if isinstance(e,float) else str(e),align='right',width='%g%%'%(100./splitLen-1.))) # last in the line, or last overall if i%splitLen==(splitLen-1) or i==len(s)-1: table.append(tr) return ret
def make_list(items): parts = [item.rsplit('.', 1) for item in items] return tag.table(tag.tbody( tag.tr(tag.td(c, class_='trac-name'), tag.td('(%s.*)' % m, class_='trac-name')) for m, c in parts), class_='trac-pluglist')
def expand_macro(self, formatter, name, content): interwikis = [] for k in sorted(self.keys()): prefix, url, title = self[k] interwikis.append({ 'prefix': prefix, 'url': url, 'title': title, 'rc_url': self._expand_or_append(url, ['RecentChanges']), 'description': url if title == prefix else title }) return tag.table( tag.tr(tag.th(tag.em(_("Prefix"))), tag.th(tag.em(_("Site")))), [ tag.tr( tag.td(tag.a(w['prefix'], href=w['rc_url'])), tag.td(tag.a(w['description'], href=w['url']))) for w in interwikis ], class_="wiki interwiki")
def expand_macro(self, formatter, name, content): intertracs = {} for key, value in self.config.options("intertrac"): idx = key.rfind(".") # rsplit only in 2.4 if idx > 0: # 0 itself doesn't help much: .xxx = ... prefix, attribute = key[:idx], key[idx + 1 :] intertrac = intertracs.setdefault(prefix, {}) intertrac[attribute] = value else: intertracs[key] = value # alias if "trac" not in intertracs: intertracs["trac"] = {"title": _("The Trac Project"), "url": "http://trac.edgewall.org"} def generate_prefix(prefix): intertrac = intertracs[prefix] if isinstance(intertrac, basestring): yield tag.tr(tag.td(tag.b(prefix)), tag.td("Alias for ", tag.b(intertrac))) else: url = intertrac.get("url", "") if url: title = intertrac.get("title", url) yield tag.tr(tag.td(tag.a(tag.b(prefix), href=url + "/timeline")), tag.td(tag.a(title, href=url))) return tag.table(class_="wiki intertrac")( tag.tr(tag.th(tag.em("Prefix")), tag.th(tag.em("Trac Site"))), [generate_prefix(p) for p in sorted(intertracs.keys())], )
def expand_macro(self, formatter, name, content): intertracs = {} for key, value in self.intertrac_section.options(): idx = key.rfind('.') if idx > 0: # 0 itself doesn't help much: .xxx = ... prefix, attribute = key[:idx], key[idx + 1:] intertrac = intertracs.setdefault(prefix, {}) intertrac[attribute] = value else: intertracs[key] = value # alias if 'trac' not in intertracs: intertracs['trac'] = { 'title': _('The Trac Project'), 'url': 'http://trac.edgewall.org' } def generate_prefix(prefix): intertrac = intertracs[prefix] if isinstance(intertrac, basestring): yield tag.tr(tag.td(tag.b(prefix)), tag.td('Alias for ', tag.b(intertrac))) else: url = intertrac.get('url', '') if url: title = intertrac.get('title', url) yield tag.tr( tag.td(tag.a(tag.b(prefix), href=url + '/timeline')), tag.td(tag.a(title, href=url))) return tag.table(class_="wiki intertrac")( tag.tr(tag.th(tag.em('Prefix')), tag.th(tag.em('Trac Site'))), [generate_prefix(p) for p in sorted(intertracs.keys())])
def expand_macro(self, formatter, name, content, args={}): self.href = formatter.req.href db = self.env.get_db_cnx() cursor = db.cursor() params = [x.strip() for x in content.split(',')] pages = [x for x in params if '=' not in x] kwargs = dict([x.split('=', 1) for x in params if '=' in x]) if not pages: pages = ['*'] order = kwargs.get('order') != 'reverse' and 'DESC' or '' self.date_format = kwargs.get('date_format', '%Y-%m-%d %H:%M:%S') self.pagename = kwargs.get('pagename') cursor.execute( 'SELECT name, time, author, version, comment FROM wiki AS w1' + ' WHERE version=(SELECT MAX(version) FROM wiki AS w2 WHERE w1.name=w2.name) AND (' + ' OR '.join(['name LIKE "%s"' % x.replace('*', '%') for x in pages]) + ')' + ' ORDER BY time ' + order) rows = [self._build_row(*x) for x in cursor] return tag.table(self.thead, tag.tbody(rows), class_='wikistatuslist', bgcolor=kwargs.get('bgcolor', '#F0F0F0'))
def expand_macro(self, formatter, name, content): args, opts = parse_args(content) if len(args) != 1: raise TracError("Requied single table name") table = args[0] excludes = [e.strip() for e in opts.get('exclude', '').split('|')] ccount = int(opts.get('column_count', 3)) cdtsys = CustomDBTableSystem(self.env) try: items = cdtsys.sorted_column(table, 'name') except: raise TracError("Table not found: %s" % table) if excludes: items = [e for e in items if e not in excludes] ttable = tag.table(class_='wiki customdbtable') tr = td = None i = 0 for item in items: if i % ccount == 0: tr = tag.tr() ttable(tr) td = tag.td(item) tr(td) i += 1 while i % ccount != 0: tr(tag.td()) i += 1 return ttable
def expand_macro(self, formatter, name, content): intertracs = {} for key, value in self.intertrac_section.options(): idx = key.rfind('.') if idx > 0: # 0 itself doesn't help much: .xxx = ... prefix, attribute = key[:idx], key[idx+1:] intertrac = intertracs.setdefault(prefix, {}) intertrac[attribute] = value else: intertracs[key] = value # alias if 'trac' not in intertracs: intertracs['trac'] = {'title': _('The Trac Project'), 'url': 'http://trac.edgewall.org'} def generate_prefix(prefix): intertrac = intertracs[prefix] if isinstance(intertrac, basestring): yield tag.tr(tag.td(tag.b(prefix)), tag.td('Alias for ', tag.b(intertrac))) else: url = intertrac.get('url', '') if url: title = intertrac.get('title', url) yield tag.tr(tag.td(tag.a(tag.b(prefix), href=url + '/timeline')), tag.td(tag.a(title, href=url))) return tag.table(class_="wiki intertrac")( tag.tr(tag.th(tag.em('Prefix')), tag.th(tag.em('Trac Site'))), [generate_prefix(p) for p in sorted(intertracs.keys())])
def expand_macro(self, formatter, name, content): from trac.mimeview.api import Mimeview mime_map = Mimeview(self.env).mime_map mime_type_filter = '' args, kw = parse_args(content) if args: mime_type_filter = args.pop(0).strip().rstrip('*') mime_types = {} for key, mime_type in mime_map.iteritems(): if (not mime_type_filter or mime_type.startswith(mime_type_filter)) and key != mime_type: mime_types.setdefault(mime_type, []).append(key) return tag.div(class_='mimetypes')( tag.table(class_='wiki')( tag.thead(tag.tr( tag.th(_("MIME Types")), # always use plural tag.th(tag.a("WikiProcessors", href=formatter.context.href.wiki( 'WikiProcessors'))))), tag.tbody( tag.tr(tag.th(tag.tt(mime_type), style="text-align: left"), tag.td(tag.code( ' '.join(sorted(mime_types[mime_type]))))) for mime_type in sorted(mime_types.keys()))))
def expand_macro(self, formatter, name, arguments): self.mc.options(arguments) extras = self.mc.extras() extra = '' if 'extra' in extras: extra = extras['extra'] return tag.div( tag.h3('[[%s(%s)]]' % ( name, arguments )), tag.table( tag.tr( tag.th('Name'), tag.th('Value'), tag.th('Qualified'), tag.th('Default?'), tag.th('Macroarg?'), tag.th('Extra?'), tag.th('Known?'), tag.th('Default'), tag.th('Documentation') ), self._show_option('text', self.mo_text, TracMacroConfigExample.mo_text), self._show_option('bool', self.mo_bool, TracMacroConfigExample.mo_bool), self._show_option('int', self.mo_int, TracMacroConfigExample.mo_int), self._show_option('list', self.mo_list, TracMacroConfigExample.mo_list), self._show_option('nodtext', self.mo_nodtext, TracMacroConfigExample.mo_nodtext), self._show_option('nodbool', self.mo_nodbool, TracMacroConfigExample.mo_nodbool), self._show_option('nodint', self.mo_nodint, TracMacroConfigExample.mo_nodint), self._show_option('nodlist', self.mo_nodlist, TracMacroConfigExample.mo_nodlist), self._show_extra('extra', extra), border=1, cellpadding=1, cellspacing=0 ) )
def render_table(items, colspec, render_item, colspace=1): try: columns = max(int(colspec), 1) except Exception: columns = 3 nbsp = Markup(' ') # hdr = [tag.th(nbsp, 'Display'), tag.th('Markup', nbsp)] spacer_style = 'width:%dem;border:none' % colspace # Find max width to make value cols equally wide width = 0 for i in items: if (isinstance(i, str) or isinstance(i, unicode)) and len(i) > width: width = len(i) value_style = 'border:none' #noinspection PyUnusedLocal if width: # empirical... value_style = '%s;width:%dem' % (value_style, width*2/3) def render_def(s): rendered = s and render_item(s) or None if isinstance(s, str): s = Markup(s.replace('&', '&')) return [tag.td(rendered, nbsp, style='border:none'), tag.td(tag.kbd(s), style=value_style)] return tag.table(#tag.tr((hdr + [tag.td(style=spacer_style)]) * # (columns-1) + hdr), [tag.tr([render_def(s) + [tag.td(style=spacer_style)] for s in row[:-1]] + render_def(row[-1])) for row in group_over(sorted(items), columns)], class_='wiki', style='border:none')
def expand_macro(self, formatter, name, content): from trac.mimeview.api import Mimeview mime_map = Mimeview(self.env).mime_map mime_type_filter = '' args, kw = parse_args(content) if args: mime_type_filter = args.pop(0).strip().rstrip('*') mime_types = {} for key, mime_type in mime_map.iteritems(): if (not mime_type_filter or mime_type.startswith(mime_type_filter)) and key != mime_type: mime_types.setdefault(mime_type, []).append(key) return tag.div(class_='mimetypes')( tag.table(class_='wiki')( tag.thead(tag.tr( tag.th(_("MIME Types")), # always use plural tag.th(tag.a("WikiProcessors", href=formatter.context.href.wiki( 'WikiProcessors'))))), tag.tbody( tag.tr(tag.th(tag.code(mime_type), style="text-align: left"), tag.td(tag.code( ' '.join(sorted(mime_types[mime_type]))))) for mime_type in sorted(mime_types.keys()))))
def fn(stream): for kind, data, pos in stream: if kind is END and data.localname == 'body': first_time = req._tracdeveloper_hdlr.buf \ and req._tracdeveloper_hdlr.buf[0].created elm = tag.div(tag.table( tag.thead( tag.tr( tag.th('Time'), tag.th('Module'), tag.th('Level'), tag.th('Message'), )), class_='listing')([ tag.tr( tag.td(int((r.created - first_time) * 1000)), tag.td(r.module), tag.td(r.levelname), tag.td(r.getMessage()), class_=(i % 2 and 'even' or 'odd'), ) for i, r in enumerate(req._tracdeveloper_hdlr.buf) ]), id='tracdeveloper-log') for evt in elm.generate(): yield evt del elm req._tracdeveloper_hdlr.formatter = None del req._tracdeveloper_hdlr.buf[:] self.log.removeHandler(req._tracdeveloper_hdlr) del req._tracdeveloper_hdlr yield kind, data, pos
def expand_macro(self, formatter, name, content): intertracs = {} for key, value in self.config.options('intertrac'): idx = key.rfind('.') # rsplit only in 2.4 if idx > 0: # 0 itself doesn't help much: .xxx = ... prefix, attribute = key[:idx], key[idx+1:] intertrac = intertracs.setdefault(prefix, {}) intertrac[attribute] = value else: intertracs[key] = value # alias def generate_prefix(prefix): intertrac = intertracs[prefix] if isinstance(intertrac, basestring): yield tag.tr(tag.td(tag.b(prefix)), tag.td('Alias for ', tag.b(intertrac))) else: url = intertrac.get('url', '') if url: title = intertrac.get('title', url) yield tag.tr(tag.td(tag.a(tag.b(prefix), href=url + '/timeline')), tag.td(tag.a(title, href=url))) return tag.table(class_="wiki intertrac")( tag.tr(tag.th(tag.em('Prefix')), tag.th(tag.em('Trac Site'))), [generate_prefix(p) for p in sorted(intertracs.keys())])
def htmlSeq(self,s,insideTable): from genshi.builder import tag table=tag.table(frame='box',rules='all',width='100%',**self.padding) if hasattr(s[0],'__len__') and not isinstance(s[0],(str,unicode,bytes)): # 2d array # disregard insideTable in this case for r in range(len(s) if type(s)!=AlignedBox3 else 2): # len(s) is sufficient, but some version of minieigen report erroneously that AlignedBox3 has length of 3 tr=tag.tr() for c in range(len(s[0])): tr.append(tag.td(float2str(s[r][c]) if isinstance(s[r][c],float) else str(s[r][c]),align='right',width='%g%%'%(100./len(s[0])-1.))) table.append(tr) return table splitLen=0 if len(s)>1: if isinstance(s[0],int): splitLen=self.splitIntSeq elif isinstance(s[0],(str,unicode)): splitLen=self.splitStrSeq elif isinstance(s[0],float): splitLen=self.splitFloatSeq # 1d array if splitLen==0 or len(s)<splitLen: ret=table if not insideTable else [] for e in s: ret.append(tag.td(float2str(e) if isinstance(e,float) else str(e),align='right',width='%g%%'%(100./len(s)-1.))) # 1d array, but with lines broken else: ret=table for i,e in enumerate(s): if i%splitLen==0: tr=tag.tr() tr.append(tag.td(float2str(e) if isinstance(e,float) else str(e),align='right',width='%g%%'%(100./splitLen-1.))) # last in the line, or last overall if i%splitLen==(splitLen-1) or i==len(s)-1: table.append(tr) return ret
def render(self, context, mimetype, content, filename=None, url=None): content = content.read() content = re.split('\r[\n]', content) if not content: return None head = content[0] if not head: return None head = re.split(',', head) if not head: return None thead = tag.thead(tag.tr([tag.th(h) for h in head])) content = content[1:] if not content: return None tbody = [] for r in content: if r: r = re.split(',', r) if r: tbody.append(tag.tr([tag.td(c) for c in r ])) return tag.table(thead,tag.tbody(tbody), class_="wiki")
def fn(stream): for kind, data, pos in stream: if kind is END and data.localname == 'body': first_time = req._tracdeveloper_hdlr.buf \ and req._tracdeveloper_hdlr.buf[0].created elm = tag.div(tag.table(tag.thead(tag.tr( tag.th('Time'), tag.th('Module'), tag.th('Level'), tag.th('Message'), )), class_='listing')([ tag.tr( tag.td(int((r.created - first_time) * 1000)), tag.td(r.module), tag.td(r.levelname), tag.td(r.getMessage()), class_=(i%2 and 'even' or 'odd'), ) for i, r in enumerate(req._tracdeveloper_hdlr.buf) ]), id='tracdeveloper-log') for evt in elm.generate(): yield evt del elm req._tracdeveloper_hdlr.formatter = None del req._tracdeveloper_hdlr.buf[:] self.log.removeHandler(req._tracdeveloper_hdlr) del req._tracdeveloper_hdlr yield kind, data, pos
def render_table(items, colspec, render_item, colspace=1): try: columns = max(int(colspec), 1) except Exception: columns = 3 nbsp = Markup(' ') # hdr = [tag.th(nbsp, 'Display'), tag.th('Markup', nbsp)] spacer_style = 'width:%dem;border:none' % colspace # Find max width to make value cols equally wide width = 0 for i in items: if (isinstance(i, str) or isinstance(i, unicode)) and len(i) > width: width = len(i) value_style = 'border:none' #noinspection PyUnusedLocal value_style += ';width:%dem' % (width*2/3) if width else '' # empirical... def render_def(s): rendered = s and render_item(s) or None if isinstance(s, str): s = Markup(s.replace('&', '&')) return [tag.td(rendered, nbsp, style='border:none'), tag.td(tag.kbd(s), style=value_style)] return tag.table(#tag.tr((hdr + [tag.td(style=spacer_style)]) * # (columns-1) + hdr), [tag.tr([render_def(s) + [tag.td(style=spacer_style)] for s in row[:-1]] + render_def(row[-1])) for row in group_over(sorted(items), columns)], class_='wiki', style='border:none')
def expand_macro(self, formatter, name, content): args, opts = parse_args(content) if len(args) != 1: raise TracError("Requied single table name") table = args[0] excludes = [e.strip() for e in opts.get('exclude', '').split('|')] cdtsys = CustomDBTableSystem(self.env) try: columns = cdtsys.column_names(table) except: raise TracError("Table not found: %s" % table) _columns = opts.get('column', '') if _columns: _columns = [c.strip() for c in _columns.split('|')] if len(_columns) == 0: raise TracError("No column specified") for c in _columns: if c not in columns: raise TracError("Column not found: %s" % c) else: _columns = columns ttable = tag.table(class_='wiki customdbtable') for row in cdtsys.sorted_dicts(table): if row['name'] in excludes: continue tr = tag.tr() for c in _columns: tr(tag.td(row[c])) ttable(tr) return ttable
def _render_source(self, context, stream, annotations): from trac.web.chrome import add_warning annotators, labels, titles = {}, {}, {} for annotator in self.annotators: atype, alabel, atitle = annotator.get_annotation_type() if atype in annotations: labels[atype] = alabel titles[atype] = atitle annotators[atype] = annotator annotations = [a for a in annotations if a in annotators] if isinstance(stream, list): stream = HTMLParser(StringIO(u'\n'.join(stream))) elif isinstance(stream, unicode): text = stream def linesplitter(): for line in text.splitlines(True): yield TEXT, line, (None, -1, -1) stream = linesplitter() annotator_datas = [] for a in annotations: annotator = annotators[a] try: data = (annotator, annotator.get_annotation_data(context)) except TracError as e: self.log.warning("Can't use annotator '%s': %s", a, e.message) add_warning( context.req, tag.strong( tag_("Can't use %(annotator)s annotator: %(error)s", annotator=tag.em(a), error=tag.pre(e.message)))) data = (None, None) annotator_datas.append(data) def _head_row(): return tag.tr([ tag.th(labels[a], class_=a, title=titles[a]) for a in annotations ] + [tag.th(u'\xa0', class_='content')]) def _body_rows(): for idx, line in enumerate(_group_lines(stream)): row = tag.tr() for annotator, data in annotator_datas: if annotator: annotator.annotate_row(context, row, idx + 1, line, data) else: row.append(tag.td()) row.append(tag.td(line)) yield row return tag.table(class_='code')(tag.thead(_head_row()), tag.tbody(_body_rows()))
def filter_stream(self, req, method, filename, stream, data): if req.path_info.startswith('/ticket/'): div = None if 'ticket' in data: # get parents data ticket = data['ticket'] # title div = tag.div(class_='description') if ticket['status'] != 'closed': link = tag.a(_('add'), href=req.href.newticket(parents=ticket.id), title=_('Create new child ticket')) link = tag.span('(', link, ')', class_='addsubticket') else: link = None div.append(tag.h3(_('Subtickets '), link)) if 'subtickets' in data: # table tbody = tag.tbody() div.append(tag.table(tbody, class_='subtickets')) # tickets def _func(children, depth=0): for id in sorted(children, key=lambda x: int(x)): ticket = Ticket(self.env, id) # 1st column attrs = {'href': req.href.ticket(id)} if ticket['status'] == 'closed': attrs['class_'] = 'closed' link = tag.a('#%s' % id, **attrs) summary = tag.td(link, ': %s' % ticket['summary'], style='padding-left: %dpx;' % (depth * 15)) # 2nd column type = tag.td(ticket['type']) # 3rd column status = tag.td(ticket['status']) # 4th column href = req.href.query(status='!closed', owner=ticket['owner']) owner = tag.td(tag.a(ticket['owner'], href=href)) tbody.append(tag.tr(summary, type, status, owner)) if depth >= 0: _func(children[id], depth + 1) if self.recursion: _func(data['subtickets']) else: _func(data['subtickets'],-1) if div: add_stylesheet(req, 'subtickets/css/subtickets.css') stream |= Transformer('.//div[@id="ticket"]').append(div) return stream
def _field_group(self, req, group): fieldset_id = 'properties_%s' % group['name'] table_id = 'table_%s' % group['name'] fieldset = tag.fieldset(id=fieldset_id, class_='property_group') fieldset.append(tag.legend(group['label'])) fieldset.append(tag.table(id=table_id)) return fieldset
def expand_macro(self, formatter, name, args): from trac.config import ConfigSection, Option section_filter = key_filter = '' args, kw = parse_args(args) if args: section_filter = args.pop(0).strip() if args: key_filter = args.pop(0).strip() def getdoc(option_or_section): doc = to_unicode(option_or_section.__doc__) if doc: doc = dgettext(option_or_section.doc_domain, doc) return doc registry = ConfigSection.get_registry(self.compmgr) sections = dict((name, getdoc(section)) for name, section in registry.iteritems() if name.startswith(section_filter)) registry = Option.get_registry(self.compmgr) options = {} for (section, key), option in registry.iteritems(): if section.startswith(section_filter): options.setdefault(section, {})[key] = option sections.setdefault(section, '') def default_cell(option): default = option.default if default is True: default = 'true' elif default is False: default = 'false' elif default == 0: default = '0.0' if isinstance(default, float) else '0' elif default: default = ', '.join(to_unicode(val) for val in default) \ if isinstance(default, (list, tuple)) \ else to_unicode(default) else: return tag.td(_("(no default)"), class_='nodefault') return tag.td(tag.code(default), class_='default') return tag.div(class_='tracini')( (tag.h3(tag.code('[%s]' % section), id='%s-section' % section), format_to_html(self.env, formatter.context, section_doc), tag.table(class_='wiki')(tag.tbody( tag.tr( tag.td(tag.tt(option.name)), tag.td( format_to_oneliner(self.env, formatter.context, getdoc(option))), default_cell(option)) for option in sorted(options.get(section, {}).itervalues(), key=lambda o: o.name) if option.name.startswith(key_filter)))) for section, section_doc in sorted(sections.iteritems()))
def _render_mergeinfo(self, name, mode, context, props): rows = [] for row in props[name].splitlines(): try: (path, revs) = row.rsplit(":", 1) rows.append([tag.td(path), tag.td(revs.replace(",", u",\u200b"))]) except ValueError: rows.append(tag.td(row, colspan=2)) return tag.table(tag.tbody([tag.tr(row) for row in rows]), class_="props")
def _render_source(self, context, stream, annotations): from trac.web.chrome import add_warning annotators, labels, titles = {}, {}, {} for annotator in self.annotators: atype, alabel, atitle = annotator.get_annotation_type() if atype in annotations: labels[atype] = alabel titles[atype] = atitle annotators[atype] = annotator annotations = [a for a in annotations if a in annotators] if isinstance(stream, list): stream = HTMLParser(StringIO(u"\n".join(stream))) elif isinstance(stream, unicode): text = stream def linesplitter(): for line in text.splitlines(True): yield TEXT, line, (None, -1, -1) stream = linesplitter() annotator_datas = [] for a in annotations: annotator = annotators[a] try: data = (annotator, annotator.get_annotation_data(context)) except TracError as e: self.log.warning("Can't use annotator '%s': %s", a, e) add_warning( context.req, tag.strong( tag_("Can't use %(annotator)s annotator: %(error)s", annotator=tag.em(a), error=tag.pre(e)) ), ) data = None, None annotator_datas.append(data) def _head_row(): return tag.tr( [tag.th(labels[a], class_=a, title=titles[a]) for a in annotations] + [tag.th(u"\xa0", class_="content")] ) def _body_rows(): for idx, line in enumerate(_group_lines(stream)): row = tag.tr() for annotator, data in annotator_datas: if annotator: annotator.annotate_row(context, row, idx + 1, line, data) else: row.append(tag.td()) row.append(tag.td(line)) yield row return tag.table(class_="code")(tag.thead(_head_row()), tag.tbody(_body_rows()))
def expand_macro(self, formatter, name, args): if not args: return Markup() config = None if name == self.CONFIG_KEY: lines = args.splitlines() if not lines or not lines[0].startswith('#!'): return Markup() config = self._parse_config([i.strip() for i in lines[0][2:].split(',')]) else: config = self.CONFIG[name] if not config: return Markup() def to_html(text): if not text: return '' return Markup('<br>'.join([format_to_oneliner(self.env, formatter.context, line) \ for line in text.splitlines()])) def has_keys(dict, keys): for key in keys: if dict.has_key(key): return True return False rows = self.parse_doc(args) if not rows: return Markup() seen = [] for desc, keys in config: if [row for row in rows if has_keys(row, keys)]: seen.append(desc) thead = tag.thead() for desc, keys in config: if not desc in seen: continue thead(tag.td(tag.b(desc))) tbody = tag.tbody() for row in rows: trow = tag.tr() for desc, keys in config: if not desc in seen: continue tcol = tag.td() for key in keys: if row.has_key(key): tcol(to_html(row[key])) trow(tcol) tbody(trow) return tag.table([thead, tbody], class_='wiki')
def render_refs_box(self, req, ids, order = 'year', desc = 1, headhref=False, path=[],args=[],page=None,max=None ): # Check parameters if not ids: return [] columns = self.env.config.get('zotero', 'columns','firstCreator, year, publicationTitle, title' ) columns = columns.split(',') columns = [c.strip() for c in columns] model = ZoteroModelProvider(self.env) if page: page = (page-1)*max data = model.get_item_columns_by_iids(ids,columns, order, desc = desc, offset=page,limit=max) apath = args_path(args) heads = [] for idx, column in enumerate(columns): label = column if zotero_fields_mapping_name.has_key(column): label = zotero_fields_mapping_name[column]['label'] if headhref and path: head = [] th_class = '' th_href = req.href(path, order=column)+apath if order == column: if desc: th_class = 'desc' else: th_class = 'asc' th_href = req.href(path, order=column, desc = str(1))+apath head = tag.th(tag.a(label, href = th_href),class_= th_class) heads.append(head) else: heads.append(tag.th(label)) body = [] for idx, item in enumerate(data): item_class = 'even' if idx % 2 == 1: item_class = 'odd' item_td = [] for idx, col in enumerate(columns): col_td = [] if not col or item[idx+1] == 'None': col_td = tag.td() elif col == 'title': col_td = tag.td(tag.a(item[idx+1], href = req.href.zotero('item',str(item[0])))) else: col_td = tag.td(item[idx+1]) item_td.append(col_td) item_tr = tag.tr( item_td,class_=item_class) body.append(item_tr) return tag.table( tag.thead( heads ), tag.tbody(body), class_="listing dirlist", id="dirlist")
def expand_macro(self, formatter, name, content, args=None): t = [render_table(p, '1', lambda s: self._format_phrase(formatter, s, None)) for p in [self.fixme_phrases, self.todo_phrases, self.done_phrases]] style = 'border:none;text-align:center;vertical-align:top' spacer = tag.td(style='width:2em;border:none') return tag.table(tag.tr(tag.td(t[0], style=style), spacer, tag.td(t[1], style=style), spacer, tag.td(t[2], style=style)))
def filter_stream(self, req, method, filename, stream, data): if req.path_info.startswith('/ticket/'): div = None if 'ticket' in data: # get parents data ticket = data['ticket'] # title div = tag.div(class_='description') if ticket['status'] != 'closed': link = tag.a(_('add'), href=req.href.newticket(parents=ticket.id), title=_('Create new child ticket')) link = tag.span('(', link, ')', class_='addsubticket') else: link = None div.append(tag.h3(_('Subtickets '), link)) if 'subtickets' in data: # table tbody = tag.tbody() div.append(tag.table(tbody, class_='subtickets')) # tickets def _func(children, depth=0): for id in sorted(children, key=lambda x: int(x)): ticket = Ticket(self.env, id) # 1st column attrs = {'href': req.href.ticket(id)} if ticket['status'] == 'closed': attrs['class_'] = 'closed' link = tag.a('#%s' % id, **attrs) summary = tag.td(link, ': %s' % ticket['summary'], style='padding-left: %dpx;' % (depth * 15)) # 2nd column type = tag.td(ticket['type']) # 3rd column status = tag.td(ticket['status']) # 4th column href = req.href.query(status='!closed', owner=ticket['owner']) owner = tag.td(tag.a(ticket['owner'], href=href)) tbody.append(tag.tr(summary, type, status, owner)) _func(children[id], depth + 1) _func(data['subtickets']) if div: add_stylesheet(req, 'subtickets/css/subtickets.css') stream |= Transformer('.//div[@id="ticket"]').append(div) return stream
def expand_macro(self, formatter, name, content, args): title = 'Color Scheme' classes = 'colormacro' if args and 'title' in args: title = args['title'] if args and 'class' in args: classes += ' ' + args['class'] tbody = [] have_comment = False colors = self._parse_arguments(content) for color in colors: if len(color['title']) > 0: have_comment = True ## Create row tbody.append( [ tag.td()(tag.strong(color['title'])), tag.td( style='background-color:' + color['orig'] )( tag.div(style='color: black')(color['hex']), tag.div(style='color: white')(color['hex']) ), tag.td( style='background-color:' + color['orig'] )( tag.div(style='color: black')(color['rgbp']), tag.div(style='color: white')(color['rgbp']) ), ] ) ## end for loop if len(tbody) > 0: colcount = len(tbody[0]) if not have_comment: colcount -= 1 table = tag.table(class_=classes) table()(tag.thead()(tag.th(colspan='%d' % colcount)(title))) ## Attach row in table. if have_comment: table()(tag.tbody(class_='colorlist')([tag.tr(row) for row in tbody])) else: table()(tag.tbody(class_='colorlist')([tag.tr(row[1:]) for row in tbody])) return table; else: return tag.div(class_='colormacro')('Nothing to display')
def expand_macro(self, formatter, name, args): from trac.config import ConfigSection, Option section_filter = key_filter = '' args, kw = parse_args(args) if args: section_filter = args.pop(0).strip() if args: key_filter = args.pop(0).strip() def getdoc(option_or_section): doc = to_unicode(option_or_section.__doc__) if doc: doc = dgettext(option_or_section.doc_domain, doc) return doc registry = ConfigSection.get_registry(self.compmgr) sections = dict((name, getdoc(section)) for name, section in registry.iteritems() if name.startswith(section_filter)) registry = Option.get_registry(self.compmgr) options = {} for (section, key), option in registry.iteritems(): if section.startswith(section_filter): options.setdefault(section, {})[key] = option sections.setdefault(section, '') def default_cell(option): default = option.default if default is True: default = 'true' elif default is False: default = 'false' elif default == 0: default = '0.0' if isinstance(default, float) else '0' elif default: default = ', '.join(to_unicode(val) for val in default) \ if isinstance(default, (list, tuple)) \ else to_unicode(default) else: return tag.td(_("(no default)"), class_='nodefault') return tag.td(tag.code(default), class_='default') return tag.div(class_='tracini')( (tag.h3(tag.code('[%s]' % section), id='%s-section' % section), format_to_html(self.env, formatter.context, section_doc), tag.table(class_='wiki')(tag.tbody( tag.tr(tag.td(tag.tt(option.name)), tag.td(format_to_oneliner( self.env, formatter.context, getdoc(option))), default_cell(option)) for option in sorted(options.get(section, {}).itervalues(), key=lambda o: o.name) if option.name.startswith(key_filter)))) for section, section_doc in sorted(sections.iteritems()))
def _render(self, text=None): if text is None: text = self._get_text() data = csv.reader(StringIO(text)) rows = (tag.tr(tag.td(cell) for cell in row) for row in data) stream = tag.table(rows) return stream.generate()
def _render_mergeinfo(self, name, mode, context, props): rows = [] for row in props[name].splitlines(): try: (path, revs) = row.rsplit(':', 1) rows.append([tag.td(path), tag.td(revs.replace(',', u',\u200b'))]) except ValueError: rows.append(tag.td(row, colspan=2)) return tag.table(tag.tbody([tag.tr(row) for row in rows]), class_='props')
def expand_macro(self, formatter, name, content): from trac.config import ConfigSection, Option section_filter = key_filter = '' args, kw = parse_args(content) if args: section_filter = args.pop(0).strip() if args: key_filter = args.pop(0).strip() def getdoc(option_or_section): doc = to_unicode(option_or_section.__doc__) if doc: doc = dgettext(option_or_section.doc_domain, doc) return doc registry = ConfigSection.get_registry(self.compmgr) sections = dict((name, getdoc(section)) for name, section in registry.iteritems() if name.startswith(section_filter)) registry = Option.get_registry(self.compmgr) options = {} for (section, key), option in registry.iteritems(): if section.startswith(section_filter): options.setdefault(section, {})[key] = option sections.setdefault(section, '') def default_cell(option): default = option.default if default is not None and default != '': return tag.td(tag.code(option.dumps(default)), class_='default') else: return tag.td(_("(no default)"), class_='nodefault') return tag.div(class_='tracini')( (tag.h3(tag.code('[%s]' % section), id='%s-section' % section), format_to_html(self.env, formatter.context, section_doc), tag.table(class_='wiki')(tag.tbody( tag.tr(tag.td(tag.code(option.name)), tag.td( format_to_oneliner(self.env, formatter.context, getdoc(option))), default_cell(option), class_='odd' if idx % 2 else 'even') for idx, option in enumerate( sorted(options.get(section, {}).itervalues(), key=lambda o: o.name)) if option.name.startswith(key_filter)))) for section, section_doc in sorted(sections.iteritems()))
def pygmentize_to_tag(code, language, linenos=False, **kwargs): """ Rebuild a raw pygmentize highlighting as tag elements, avoiding Genshi to delete blank lines. See http://genshi.edgewall.org/wiki/GenshiFaq#WhatisGenshidoingwiththewhitespaceinmymarkuptemplate """ codeblock = pygmentize(code, language, linenos, **kwargs) pre = re.findall("<pre>(.*?)\n*</pre>", codeblock, re.DOTALL) if len(pre) == 1: return tag.pre(Markup(pre[0]), data_language=language) return tag.table( tag.tr(tag.td(tag.pre(pre[0])), tag.td(tag.pre(Markup(pre[1])))), data_language=language # line numbers # code )
def expand_macro(self, formatter, name, content): from trac.config import ConfigSection, Option section_filter = key_filter = '' args, kw = parse_args(content) if args: section_filter = args.pop(0).strip() if args: key_filter = args.pop(0).strip() def getdoc(option_or_section): doc = to_unicode(option_or_section.__doc__) if doc: doc = dgettext(option_or_section.doc_domain, doc) return doc registry = ConfigSection.get_registry(self.compmgr) sections = dict((name, getdoc(section)) for name, section in registry.iteritems() if name.startswith(section_filter)) registry = Option.get_registry(self.compmgr) options = {} for (section, key), option in registry.iteritems(): if section.startswith(section_filter): options.setdefault(section, {})[key] = option sections.setdefault(section, '') def default_cell(option): default = option.default if default is not None and default != '': return tag.td(tag.code(option.dumps(default)), class_='default') else: return tag.td(_("(no default)"), class_='nodefault') return tag.div(class_='tracini')( (tag.h3(tag.code('[%s]' % section), id='%s-section' % section), format_to_html(self.env, formatter.context, section_doc), tag.table(class_='wiki')(tag.tbody( tag.tr(tag.td(tag.tt(option.name)), tag.td(format_to_oneliner( self.env, formatter.context, getdoc(option))), default_cell(option), class_='odd' if idx % 2 else 'even') for idx, option in enumerate(sorted(options.get(section, {}).itervalues(), key=lambda o: o.name)) if option.name.startswith(key_filter)))) for section, section_doc in sorted(sections.iteritems()))
def options_table(section, options): if options: return tag.table(class_='wiki')( tag.tbody( tag.tr( tag.td(tag.a(tag.code(option.name), class_='tracini-option', href='#%s-%s-option' % (section, option.name))), tag.td(format_to_html(self.env, formatter.context, option.doc)), default_cell(option), id='%s-%s-option' % (section, option.name), class_='odd' if idx % 2 else 'even') for idx, option in enumerate(options)))
def expand_macro(self, formatter, name, content, args): title = 'Color Gradient' classes = 'colorgradient'; if args and 'title' in args: title = args['title'] if args and 'class' in args: classes += ' ' + args['class'] colors = self._parse_arguments(content) lastcolor = {} tbody = [] for color in colors: if 'orig' in lastcolor: tbody.append(self._create_gradient(lastcolor, color)) tbody.append([ tag.td( style='background-color:' + color['orig'] )( tag.div(style='color: black')(color['hex']), tag.div(style='color: white')(color['hex']) ), tag.td( style='background-color:' + color['orig'] )( tag.div(style='color: black')(color['rgbp']), tag.div(style='color: white')(color['rgbp']) ) ]) lastcolor = color ## end for loop if len(tbody) > 0: table = tag.table(class_=classes) table()(tag.thead()(tag.th(colspan="2")(title))) table()(tag.tbody(class_='colorgradient')([tag.tr()(td) for td in tbody])) return table; else: return tag.div(class_='colorgradient')('Nothing to display')
def expand_macro(self, formatter, name, content): interwikis = [] for k in sorted(self.keys()): prefix, url, title = self[k] interwikis.append({ 'prefix': prefix, 'url': url, 'title': title, 'rc_url': self._expand_or_append(url, ['RecentChanges']), 'description': url if title == prefix else title}) return tag.table(tag.tr(tag.th(tag.em(_("Prefix"))), tag.th(tag.em(_("Site")))), [tag.tr(tag.td(tag.a(w['prefix'], href=w['rc_url'])), tag.td(tag.a(w['description'], href=w['url']))) for w in interwikis ], class_="wiki interwiki")
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
def render_table(items, colspec, render_item): try: columns = max(int(colspec), 1) except: columns = 3 nbsp = Markup(' ') hdr = [tag.th('Markup', nbsp), tag.th(nbsp, 'Display')] def render_def(s): rendered = s and render_item(s) or None return [tag.td(s), tag.td(rendered)] return tag.table(tag.tr((hdr + [tag.th(nbsp)]) * (columns-1) + hdr), [tag.tr([render_def(s) + [tag.td(nbsp)] for s in row[:-1]] + render_def(row[-1])) for row in group(sorted(items), columns)], class_="wiki")
def expand_macro(self, formatter, name, content): content = content.strip() if content else '' name_filter = content.strip('*') items = {} for subscriber in NotificationSystem(self.env).subscribers: name = subscriber.__class__.__name__ if not name_filter or name.startswith(name_filter): items[name] = subscriber.description() return tag.div(class_='trac-subscriberlist')(tag.table(class_='wiki')( tag.thead(tag.tr(tag.th(_("Subscriber")), tag.th(_("Description")))), tag.tbody( tag.tr(tag.td(tag.code(name)), tag.td(items[name]), class_='odd' if idx % 2 else 'even') for idx, name in enumerate(sorted(items.keys())))))
def expand_macro(self, formatter, name, content): content = content.strip() if content else '' name_filter = content.strip('*') items = {} for subscriber in NotificationSystem(self.env).subscribers: name = subscriber.__class__.__name__ if not name_filter or name.startswith(name_filter): items[name] = subscriber.description() return tag.div(class_='trac-subscriberlist')( tag.table(class_='wiki')( tag.thead(tag.tr( tag.th(_("Subscriber")), tag.th(_("Description")))), tag.tbody( tag.tr(tag.td(tag.code(name)), tag.td(items[name]), class_='odd' if idx % 2 else 'even') for idx, name in enumerate(sorted(items.keys())))))
def _add_custom_field_tables(self, stream, ticket): ticket_body = Transformer('//div[@id="ticket"]') for table_info in self._get_table_fields(ticket): headers = table_info["headers"] columns = table_info["columns"] tickets = table_info["tickets"] table = tag.div( tag.h3(table_info["title"]), tag.table( tag.thead(self._get_header(headers)), tag.tbody(self._get_body(tickets, columns)), class_="listing tickets", ), ) stream = stream | ticket_body.after(table) return stream
def expand_macro(self, formatter, name, args): from trac.config import ConfigSection, Option section_filter = key_filter = '' args, kw = parse_args(args) if args: section_filter = args.pop(0).strip() if args: key_filter = args.pop(0).strip() registry = ConfigSection.get_registry(self.compmgr) sections = dict( (name, dgettext(section.doc_domain, to_unicode(section.__doc__))) for name, section in registry.iteritems() if name.startswith(section_filter)) registry = Option.get_registry(self.compmgr) options = {} for (section, key), option in registry.iteritems(): if section.startswith(section_filter): options.setdefault(section, {})[key] = option sections.setdefault(section, '') return tag.div(class_='tracini')( (tag.h3(tag.code('[%s]' % section), id='%s-section' % section), format_to_html(self.env, formatter.context, section_doc), tag.table(class_='wiki')(tag.tbody( tag.tr( tag.td(tag.tt(option.name)), tag.td( format_to_oneliner( self.env, formatter.context, dgettext(option.doc_domain, to_unicode(option.__doc__)))), tag.td( tag.code(option.default or 'false') if option.default or option.default is False else _("(no default)"), class_='default' if option.default or option.default is False else 'nodefault')) for option in sorted(options.get(section, {}).itervalues(), key=lambda o: o.name) if option.name.startswith(key_filter)))) for section, section_doc in sorted(sections.iteritems()))
def expand_macro(self, formatter, name, content): evs = EarnValueSystem(self.env) kwargs = self._parse_arg(content) users = evs.get_users(formatter.req, kwargs.get('users', 'authenticated')) format = kwargs.get('format', 'table') start_time = self._parse_date(kwargs.get('start'), 0) end_time = self._parse_date(kwargs.get('end'), None) if format == 'plain': ev = dict([(u, evs.get_user_ev(u, start_time, end_time)) for u in users]) tags = [] for k, v in ev.items(): tags.append(tag.span(k + ': ' + str(v))) tags.append(tag.br) return tag.p(*tags) elif format == 'table': evc = evs.get_users_ev_detail(users, start_time, end_time) rows = [tag.tr( tag.td(ev['action_name']), tag.td(ev['value']), tag.td(ev['fullname']), tag.td(ev['time']), tag.td(ev['summary']) ) for evcs in evc.values() for ev in evcs ] return tag.div( tag.table(tag.thead( tag.tr( tag.th('Action'), tag.th('Value'), tag.th('User'), tag.th('Date'), tag.th('Summary'), class_='trac-columns') ), tag.tbody( *rows ), class_='listing tickets') ) return None
def render(self, context, mimetype, content, filename=None, url=None): content = content.read() content = re.split('\r[\n]', content) if not content: return None head = content[0] if not head: return None head = re.split(',', head) if not head: return None thead = tag.thead(tag.tr([tag.th(h) for h in head])) content = content[1:] if not content: return None tbody = [] for r in content: if r: r = re.split(',', r) if r: tbody.append(tag.tr([tag.td(c) for c in r])) return tag.table(thead, tag.tbody(tbody), class_="wiki")
def __call__(self,obj,depth=0,dontRender=False): from genshi.builder import tag if depth>self.maxDepth: raise RuntimeError("Maximum nesting depth %d exceeded"%self.maxDepth) kw=self.padding.copy() if depth>0: kw.update(width='100%') # was [1:] to omit leading woo./wooExtra., but that is not desirable objInExtra=obj.__class__.__module__.startswith('wooExtra.') if self.hideWooExtra and objInExtra: head=tag.span(tag.b(obj.__class__.__name__),title=_ensureUnicode(obj.__class__.__doc__)) else: head=tag.b('.'.join(obj.__class__.__module__.split('.')[0:])+'.'+obj.__class__.__name__) head=tag.a(head,href=woo.document.makeObjectUrl(obj),title=_ensureUnicode(obj.__class__.__doc__)) ret=tag.table(tag.th(head,colspan=3,align='left'),frame='box',rules='all',**kw) # get all attribute traits first traits=obj._getAllTraits() for trait in traits: if trait.hidden or (self.hideNoGui and trait.noGui) or trait.noDump or (trait.hideIf and eval(trait.hideIf,globals(),{'self':obj})): continue # start new group (additional line) if trait.startGroup: ret.append(tag.tr(tag.td(tag.i(u'▸ %s'%_ensureUnicode(trait.startGroup)),colspan=3))) attr=getattr(obj,trait.name) if self.showDoc: tr=tag.tr(tag.td(_ensureUnicode(trait.doc))) else: try: if self.hideWooExtra and objInExtra: label=tag.span(tag.b(trait.name),title=_ensureUnicode(trait.doc)) else: label=tag.a(trait.name,href=woo.document.makeObjectUrl(obj,trait.name),title=_ensureUnicode(trait.doc)) tr=tag.tr(tag.td(label)) except UnicodeEncodeError: print('ERROR: UnicodeEncodeError while formatting the attribute ',obj.__class__.__name__+'.'+trait.name) print('ERROR: the docstring is',trait.doc) raise # tr=tag.tr(tag.td(trait.name if not self.showDoc else trait.doc.decode('utf-8'))) # nested object if isinstance(attr,woo.core.Object): tr.append([tag.td(self(attr,depth+1),align='justify'),tag.td()]) # sequence of objects (no units here) elif hasattr(attr,'__len__') and len(attr)>0 and isinstance(attr[0],woo.core.Object): tr.append(tag.td(tag.ol([tag.li(self(o,depth+1)) for o in attr]))) else: # !! make deepcopy so that the original object is not modified !! import copy attr=copy.deepcopy(attr) if not trait.multiUnit: # the easier case if not trait.prefUnit: unit=u'−' else: unit=_ensureUnicode(trait.prefUnit[0][0]) # create new list, where entries are multiplied by the multiplier if type(attr)==list: attr=[a*trait.prefUnit[0][1] for a in attr] else: attr=attr*trait.prefUnit[0][1] else: # multiple units unit=[] wasList=isinstance(attr,list) if not wasList: attr=[attr] # handle uniformly for i in range(len(attr)): attr[i]=[attr[i][j]*trait.prefUnit[j][1] for j in range(len(attr[i]))] for pu in trait.prefUnit: unit.append(_ensureUnicode(pu[0])) if not wasList: attr=attr[0] unit=', '.join(unit) # sequence type, or something similar if hasattr(attr,'__len__') and not isinstance(attr,(str,unicode,bytes)): if len(attr)>0: tr.append(tag.td(self.htmlSeq(attr,insideTable=False),align='right')) else: tr.append(tag.td(tag.i('[empty]'),align='right')) else: tr.append(tag.td(float2str(attr) if isinstance(attr,float) else str(attr),align='right')) if unit: tr.append(tag.td(unit,align='right')) ret.append(tr) if depth>0 or dontRender: return ret r1=ret.generate().render('xhtml',encoding='ascii') if isinstance(r1,bytes): r1=r1.decode('ascii') return r1+u'\n'
def depart_option_list(self, node): self.context.commit_elem(tag.tbody) waste, waste_, attr = self.parse(node) self.context.commit_elem(tag.table(**attr))
def expand_macro(self, formatter, name, content, args=None): class_list = ['wikiextras', 'box'] style_list = [] #noinspection PyArgumentList if not Icons(self.env).shadowless: class_list.append('shadow') class_arg = args.get('class', '') if class_arg: class_list.append(class_arg) align = 'right' if name in ['newsbox', 'rbox'] else \ 'center' if name=='imagebox' else '' align = args.get('align', align) if align: class_list.append(align) type = 'news' if name=='newsbox' else \ 'image' if name=='imagebox' else \ self._get_type(args.get('type')) if type in self.types: td = self.types[type] # type data if td[1]: #icon class_list += ['icon', td[1]] else: class_list.append(type) bg = self.urgency_bg.get(td[0]) if bg: class_list.append(bg) del td elif type: class_list.append(type) style = args.get('style', '') if style: style_list.append(style) width = args.get('width', '') if width: if width.isdigit(): width += 'px' if self._has_icon(type): # compensate for icon width if width.endswith('px'): width = '%dpx' % (int(width[:-2]) - 37) style_list.append('width:' + width) elif align == 'center': style_list.append('width:0') # for the table below html = format_to_html(self.env, formatter.context, content) class_ = ' '.join(class_list) style = ';'.join(style_list) if align == 'center': return tag.table(tag.tr(tag.td(), tag.td(html, class_=class_, style=style), tag.td()), class_='wikiextras center-box') else: return tag.div(html, class_=class_, style=style)