def render_relevanceDiv(self, context, data):
     if self.query.order == 'relevance':
         return tags.xml('<span class="selectedCriterium">'
                         'relevance</span>')
     else:
         return tags.xml("""<span class="unselectedCriterium"><a href="javascript: sortBy('relevance');">"""
                         'relevance</a></span>')
 def test_xml(self):
     """
     An L{xml} instance is flattened to the UTF-8 representation of itself.
     """
     self.assertStringEqual(self.flatten(xml("foo")), "foo")
     unich = u"\N{LATIN CAPITAL LETTER E WITH GRAVE}"
     self.assertStringEqual(self.flatten(xml(unich)), unich.encode('utf-8'))
 def render_publicationDiv(self, context, data):
     if self.query.order == 'publication_time':
         return tags.xml('<span class="selectedCriterium">'
                         'publication time</span>')
     else:
         return tags.xml("""<span class="unselectedCriterium"><a href="javascript: sortBy('publication_time');">"""
                         'publication time</a></span>')
 def test_xml(self):
     """
     An L{xml} instance is flattened to the UTF-8 representation of itself.
     """
     self.assertStringEqual(self.flatten(xml("foo")), "foo")
     unich = u"\N{LATIN CAPITAL LETTER E WITH GRAVE}"
     self.assertStringEqual(self.flatten(xml(unich)), unich.encode('utf-8'))
 def render_previous(self, context, data):
     """computes 'Previous' link"""
     if self.query.offset <= 0:
         return tags.xml('<span class="selectedCriterium">Previous</span>')
     offset = self.query.offset - 15
     return tags.xml(
         '<a href="javascript: browseResults(%s);">Previous</a>' % (offset))
 def render_popularityDiv(self, context, data):
     if self.query.order == 'popularity':
         return tags.xml('<span class="selectedCriterium">'
                         'popularity</span>')
     else:
         return tags.xml("""<span class="unselectedCriterium"><a href="javascript: sortBy('popularity');">"""
                         'popularity</a></span>')
Beispiel #7
0
 def cruftifyMultipleSpaces(text):
     """Replace multiple spaces with &nbsp; such that they are rendered as we want."""
     if text.startswith(' '):
         yield tags.xml('&#160;')
         text = text[1:]
     chunks = text.split('  ')
     for i in SpacePreservingStringRenderer.intersperse(tags.xml(' &#160;'), chunks):
         yield i
 def render_allResultsDiv(self, context, data):
     if not (self.onlyLocal or self.onlyDistant):
         return tags.xml(
             '<span class="selectedAllResults">all results</span>')
     else:
         return tags.xml(
             '<span class="allResults">'
             '<a href="javascript: allResults();">all results</a></span>')
def inlineJSSerializer(original, ctx):
    from nevow import livepage
    from nevow.tags import script, xml
    theJS = livepage.js(original.children)
    new = livepage.JavascriptContext(ctx, invisible[theJS])
    return serialize(script(type="text/javascript")[
        xml('\n//<![CDATA[\n'),
        serialize(theJS, new),
        xml('\n//]]>\n')], ctx)
 def cruftifyMultipleSpaces(text):
     """Replace multiple spaces with &nbsp; such that they are rendered as we want."""
     if text.startswith(' '):
         yield tags.xml('&#160;')
         text = text[1:]
     chunks = text.split('  ')
     for i in SpacePreservingStringRenderer.intersperse(
             tags.xml(' &#160;'), chunks):
         yield i
Beispiel #11
0
 def test_serializeString(self):
     self.assertEqual(ten.flatten('one'), u'one')
     self.assertEqual(type(ten.flatten('<>')), tags.raw)
     self.assertEqual(ten.flatten('<abc&&>123'),
                      u'&lt;abc&amp;&amp;&gt;123')
     self.assertEqual(ten.flatten(tags.xml('<>&')), u'<>&')
     self.assertEqual(
         ten.flatten(tags.xml(u'\xc2\xa3')).encode('utf-8'),
         b'\xc3\x82\xc2\xa3')
Beispiel #12
0
def inlineJSSerializer(original, ctx):
    from nevow import livepage
    from nevow.tags import script, xml
    theJS = livepage.js(original.children)
    new = livepage.JavascriptContext(ctx, invisible[theJS])
    return serialize(
        script(type="text/javascript")[xml('\n//<![CDATA[\n'),
                                       serialize(theJS, new),
                                       xml('\n//]]>\n')], ctx)
 def render_distantResultsDiv(self, context, data):
     if self.onlyDistant:
         return tags.xml(
             '<span class="selectedDistantResults">distant results</span>')
     else:
         return tags.xml(
             '<span class="distantResults">'
             '<a href="javascript: onlyDistantResults();">distant results</a></span>'
         )
 def render_localResultsDiv(self, context, data):
     if self.onlyLocal:
         return tags.xml(
             '<span class="selectedLocalResults">local results</span>')
     else:
         return tags.xml(
             '<span class="localPublicResults">'
             '<a href="javascript: onlyLocalResults();">local results</a></span>'
         )
Beispiel #15
0
    def head(self, request, website):
        def styleSheetLink(href):
            return tags.link(rel='stylesheet', type='text/css', href=href)

        root = website.cleartextRoot(request.getHeader('host'))
        styles = root.child('Eridanus').child('static').child('styles')

        yield styleSheetLink(styles.child('eridanus.css'))
        yield tags.xml(u'<!--[if IE 6]>'), styleSheetLink(styles.child('eridanus-ie6.css')), tags.xml(u'<![endif]-->')
        yield tags.xml(u'<!--[if IE 7]>'), styleSheetLink(styles.child('eridanus-ie7.css')), tags.xml(u'<![endif]-->')
Beispiel #16
0
    def head(self, request, website):
        def styleSheetLink(href):
            return tags.link(rel='stylesheet', type='text/css', href=href)

        root = website.cleartextRoot(request.getHeader('host'))
        styles = root.child('Eridanus').child('static').child('styles')

        yield styleSheetLink(styles.child('eridanus.css'))
        yield tags.xml(u'<!--[if IE 6]>'), styleSheetLink(
            styles.child('eridanus-ie6.css')), tags.xml(u'<![endif]-->')
        yield tags.xml(u'<!--[if IE 7]>'), styleSheetLink(
            styles.child('eridanus-ie7.css')), tags.xml(u'<![endif]-->')
 def render_next(self, context, data):
     """computes 'Next' link"""
     localCount, distantCount = self.querier.countResults(self.qid)
     if self.onlyDistant:
         resultsCount = distantCount
     elif self.onlyLocal:
         resultsCount = localCount
     else:
         resultsCount = localCount + distantCount
     offset = self.query.offset
     if (offset + 15) < resultsCount:
         return tags.xml('<a href="javascript: browseResults(%s);">Next</a>' % (offset + 15))
     return tags.xml('<span class="selectedCriterium">Next</span>')
Beispiel #18
0
    def head(self, request, website):
        def styleSheetLink(href):
            return tags.link(rel='stylesheet', type='text/css', href=href)

        root = website.rootURL(request)
        styles = root.child('static').child('Methanal').child('styles')

        yield styleSheetLink(styles.child('methanal.css'))
        yield (tags.xml(u'<!--[if IE 6]>'),
               styleSheetLink(styles.child('methanal-ie6.css')),
               tags.xml(u'<![endif]-->'))
        yield (tags.xml(u'<!--[if IE 7]>'),
               styleSheetLink(styles.child('methanal-ie7.css')),
               tags.xml(u'<![endif]-->'))
Beispiel #19
0
    def render_item(self, ctx, data):
        u = url.URL.fromContext(ctx)
        u = url.URL(u.scheme, u.netloc, self.page[0].split('/')[1:])
        ctx.tag.fillSlots('path', self.page[0])
        ctx.tag.fillSlots('href', u)
        ctx.tag.fillSlots('title', self.page[1])
        q = ctx.arg('q')
        if q.lower() in self.page[3].lower():
            highspan = 50
            lowspan = 180
            wrapper = '<strong>%s</strong>'
            offset = self.page[3].lower().find(q.lower())
    
            import re
            cre=re.compile(q,re.IGNORECASE)
            if offset-lowspan <0:
                lower = 0
            else:
                lower = offset-lowspan
            if offset+highspan > len(self.page[3]):
                higher = len(self.page[3])
            else:
                higher = offset+highspan
            out = cre.sub(wrapper%q,self.page[3][lower:higher])
            ctx.tag.fillSlots('summary', T.xml(out))
        else:
            ctx.tag.fillSlots('summary', self.page[2])

        return ctx.tag
Beispiel #20
0
 def render_comment(self, ctx, comment):
     tag = ctx.tag
     tag.fillSlots("id", comment.id)
     tag.fillSlots("posted", comment.posted)
     tag.fillSlots("authorName", comment.authorName)
     if comment.authorName == 'David Ward':
         tag.fillSlots("isOwner", 'owner')
     else:
         tag.fillSlots("isOwner", '')
     tag.fillSlots("authorEmail", comment.authorEmail)
     tag.fillSlots("comment", T.xml(markdown.markdown(comment.comment)))
     tag.fillSlots("relatesToCommentId",comment.relatesToCommentId)
     if hasattr(comment, 'relatesToComment') and comment.relatesToComment is not None:
         tag.fillSlots("relatesToCommentName",comment.relatesToComment.authorName)
     else:
         tag.fillSlots("relatesToCommentName",'main blog entry')
     if hasattr(comment,'followUpComments') and comment.followUpComments is not None:
         fTag = T.span(class_='followUps')
         for f in comment.followUpComments:
             fTag[ T.a(href="#comment-%s"%f.id,rel='inspires')[ f.authorName ],', ' ]
         tag.fillSlots("followUpComments",fTag)
     else:
         tag.fillSlots("followUpComments",'None')
         
     return tag
Beispiel #21
0
    def _renderTag(self, ctx, key, value, readonly):
        html = []
        tag = T.textarea(name=key,
                         id=render_cssid(key),
                         cols=self.cols,
                         rows=self.rows)[value or '']
        if readonly:
            tag(class_='readonly', readonly='readonly')
        html.append(tag)
        if self.values is None:
            return html

        def renderOptions(ctx, options):
            for value, label in options:
                yield T.option(value=value)[label]

        selecttrigger = T.select(name='%s__selecttrigger' % key,
                                 data=self.values)[renderOptions]

        form = iformal.IForm(ctx)
        js = T.xml(
            "var x = document.getElementById('%(form)s');x.%(key)s.value += x.%(key)s__selecttrigger.options[x.%(key)s__selecttrigger.options.selectedIndex].value + &quot;\\n&quot;;"
            % {
                'key': key,
                'form': form.name
            })
        aonclick = T.a(onclick=js)['add']
        html.append(T.div(class_="add")[selecttrigger, aonclick])
        return html
Beispiel #22
0
 def render_basket_item(self, ctx, basketItem):
     ctx.tag.fillSlots('code', basketItem.code or '')
     ctx.tag.fillSlots('description', T.xml(basketItem.description) or '')
     ctx.tag.fillSlots('quantity_ordered', basketItem.quantity_ordered)
     ctx.tag.fillSlots('unit_price', basketItem.unit_price)
     ctx.tag.fillSlots('total_price', basketItem.total_price)
     return ctx.tag
Beispiel #23
0
class TestFramework(athena.LivePage):
    addSlash = True
    docFactory = loaders.stan([
        tags.xml(DOCTYPE_XHTML),
        tags.html[
            tags.head(render=tags.directive('liveglue'))[
                tags.link(rel='stylesheet', href='livetest.css'),
                tags.directive('head')],
            tags.body[
                tags.invisible(render=tags.directive('runner'))]]])

    def __init__(self, testSuite):
        super(TestFramework, self).__init__()
        self.testSuite = testSuite
        self.children = {
            'livetest.css': static.File(util.resource_filename('nevow.livetrial', 'livetest.css')),
        }


    def beforeRender(self, ctx):
        self.runner = TestRunner(self.testSuite)


    def render_runner(self, ctx, data):
        self.runner.setFragmentParent(self)
        return self.runner


    def render_head(self, ctx, data):
        return self.runner.gatherHead()
Beispiel #24
0
class SVGUI_HMI(website.PLCHMI):
    jsClass = u"LiveSVGPage.LiveSVGWidget"

    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveElement'))[
            tags.xml(loaders.xmlfile(os.path.join(NS.WorkingDir, svgfile))), ])

    def HMIinitialisation(self):
        gadgets = []
        for gadget in svguiWidgets.values():
            gadgets.append(
                text(
                    json.dumps(gadget, default=get_object_init_state,
                               indent=2), 'ascii'))
        d = self.callRemote('init', gadgets)
        d.addCallback(self.HMIinitialised)

    def sendData(self, data):
        if self.initialised:
            return self.callRemote(
                'receiveData',
                text(
                    json.dumps(data,
                               default=get_object_current_state,
                               indent=2), 'ascii'))
        return None

    def setattr(self, id, attrname, value):
        svguiWidgets[id].setinput(attrname, value)
    def render_item_template_js(self, ctx, data):
        html = T.script(type="text/javascript", language="javascript" )

        js = """function getTemplates(plugin) {
                %(pluginTemplates)s
            }
            """

        fragment = """ if(plugin == "%(plugin)s") {
                return new Array(%(templates)s);
            }
            """

        fragments = []

        for plugin in self._typesList(ctx):
            templates = ','.join( ['["%s","%s"]'%(t[0],t[1]) for t in plugin.listTemplates])
            fragments.append(fragment%{'plugin':plugin.contentItemClass.__typename__,
                'templates':templates})

        fragments.append( """ { return new Array(); } """)

        pluginTemplates = ' else '.join(fragments)
        js = js%{'pluginTemplates': pluginTemplates}
        return html[T.xml(js)]
Beispiel #26
0
    def render_htmlizer(self, ctx, path):
        from twisted.python import htmlizer
        from StringIO import StringIO

        output = StringIO()
        htmlizer.filter(open(path), output, writer=htmlizer.SmallerHTMLWriter)
        return tags.xml(output.getvalue())
Beispiel #27
0
 def render_basket_item(self, ctx, basketItem): 
     #ctx.tag.fillSlots('thumbnail', T.img(src='/system/ecommerce/%s/mainImage?size=95x150&sharpen=1.0x0.5%%2b0.8%%2b0.1'%basketItem.original.product.id, class_='thumbnail'))
     ctx.tag.fillSlots('description', T.xml(basketItem.description))
     ctx.tag.fillSlots('unit_price', basketItem.unit_price)
     ctx.tag.fillSlots('quantity_ordered', basketItem.quantity_ordered)
     ctx.tag.fillSlots('total_price', basketItem.total_price)
     return ctx.tag
Beispiel #28
0
 def render_head(self, ctx, data):
     if self.db[0] == "FIRSTRUN":
         return ctx.tag[tags.link(rel="stylesheet",
                                  type="text/css",
                                  href="/css/login.css")]
     return ctx.tag[tags.xml(
         '<meta http-equiv="refresh" content="0;url=auth/"/>')]
Beispiel #29
0
        def gotMail(mail):
            print mail
            attachments, hdrs, data = mail
            uFrom, uDate, uSubject = hdrs

            toolbar = [("/mail/Mail/##%s" % self.params[0], 'Inbox',
                        "/images/inbox.png"),
                       ("/mail/New/##%s.%s" % self.params, 'Reply',
                        "/images/inbox.png")]

            return ctx.tag[tags.div(
                id="mailViewHolder")[
                    tags.ul(
                        id="mailTools")[[
                            tags.li[tags.a(href=link)[tags.div[tags.img(
                                src=image)], name]]
                            for link, name, image in toolbar
                        ]],
                    tags.table(
                        id="mailViewHeaders"
                    )[tags.tr[tags.td["From:"],
                              tags.td[uFrom]], tags.tr[tags.td["Date:"],
                                                       tags.td[uDate]],
                      tags.tr[tags.td["Subject:"], tags.td[uSubject]],
                      tags.tr[tags.td["Attachments:"], tags.td[[[
                          tags.a(href="/mail/mdata/%s/%s" %
                                 (self.avatarId.username, v[0]))[tags.img(
                                     src="/images/attachment.png"), " ", k],
                          " (%0.2f KB)" % (v[1] / 1024.0), tags.br
                      ] for k, v in attachments.items()]]], ],
                    tags.div(id="mailViewContentBox")[tags.xml(data)], ]]
Beispiel #30
0
class RenderFactory(object):
    __implements__ = inevow.IRendererFactory,

    def renderer(self, context, name):
        """Return a renderer with the given name.
        """

        # The named renderer can be parameterised, i.e. 'renderIt one,two,three'
        args = []
        if name.find(' ') != -1:
            name, args = name.split(None, 1)
            args = [arg.strip() for arg in args.split(',')]

        callable = getattr(self, 'render_%s' % name, None)
        if callable is None:
            callable = lambda context, data: context.tag[
                "The renderer named '%s' was not found in %r." % (name, self)]

        if args:
            return callable(*args)

        return callable

    render_sequence = lambda self, context, data: sequence(context, data)
    render_mapping = lambda self, context, data: mapping(context, data)
    render_string = lambda self, context, data: string(context, data)
    render_xml = lambda self, context, data: context.tag.clear()[tags.xml(data)
                                                                 ]
    render_data = lambda self, context, data_: data(context, data_)
Beispiel #31
0
class RenderFactory(object):
    implements(inevow.IRendererFactory)

    def renderer(self, context, name):
        """Return a renderer with the given name.
        """

        # The named renderer can be parameterised, i.e. 'renderIt one,two,three'
        args = []
        if name.find(' ') != -1:
            name, args = name.split(None, 1)
            args = [arg.strip() for arg in args.split(',')]

        callable = getattr(self, 'render_%s' % name, None)
        if callable is None:
            warnings.warn(
                "Renderer %r missing on %s will result in an exception." %
                (name, qual(type(self))),
                category=DeprecationWarning,
                stacklevel=1)
            callable = lambda *a, **kw: context.tag[
                "The renderer named '%s' was not found in %r." % (name, self)]

        if args:
            return callable(*args)

        return callable

    render_sequence = lambda self, context, data: sequence(context, data)
    render_mapping = lambda self, context, data: mapping(context, data)
    render_string = lambda self, context, data: string(context, data)
    render_xml = lambda self, context, data: context.tag.clear()[tags.xml(data)
                                                                 ]
    render_data = lambda self, context, data_: data(context, data_)
Beispiel #32
0
 def render_interfaces(self, ctx, data):
     ifaces = self.getIFStat().keys()
     ifaces.sort()
     return ctx.tag[[[
         tags.h3['Network Load:', iface], tags.div[tags.xml(
             '<canvas id="graph%s" height="128" width="256"/>' % iface)]
     ] for iface in ifaces]]
Beispiel #33
0
def flattenIText(orig, ctx):
    assert orig.dom.nodeType == orig.dom.ELEMENT_NODE
    assert orig.dom.namespaceURI == 'http://www.w3.org/1999/xhtml'
    assert orig.dom.nodeName == 'div'

    for node in orig.dom.childNodes:
        yield tags.xml(node.toxml())
Beispiel #34
0
    def render_footnotes(self, ctx, data):
        """renders the footnotes as a definition list.
		"""
        return T.dl(class_="footnotes")[[
            T.xml(note.getContent(targetFormat="html"))
            for note in sorted(self.footnotes, key=lambda n: n.tag)
        ]]
Beispiel #35
0
def fillReply(ctx, d):
    ctx.tag.fillSlots('id', d.get('pid'))
    ctx.tag.fillSlots('edit', '/edit.xhtml')
    ctx.tag.fillSlots('title', d.get('ttitle'))
    ctx.tag.fillSlots('body', t.xml(d.get('pparsed_body')))
    ctx.tag.fillSlots('userpref', url.root.clear().child('user').child(str(d.get('ulogin'))))
    ctx.tag.fillSlots('owner', d.get('powner'))
    ctx.tag.fillSlots('when', pptime(d.get('pmodification')))
Beispiel #36
0
	def render_tableBody(self, ctx, data):
		"""returns HTML-rendered table rows in chunks of rowsPerDivision.

		We don't use stan here since we can concat all those tr/td much faster
		ourselves.
		"""
		rowAttrsIterator = itertools.cycle([' class="data"', ' class="data even"'])
		formatRow = self._getRowFormatter()
		rendered = []
		yield T.xml("<tbody>")
		for row in self.table:
			rendered.append(formatRow(row, rowAttrsIterator.next()))
			if len(rendered)>=self.rowsPerDivision:
				yield T.xml("\n".join(rendered))
				yield self.headCellsStan
				rendered = []
		yield T.xml("\n".join(rendered)+"\n</tbody>")
Beispiel #37
0
 def block(context, data):
     client = IClientHandle(context)
     if identifier is None:
         iden = client.events.nextId()
     else:
         iden = identifier
     client.events.subscribe(iden, callit)
     return tags.xml(ctsTemplate % (iden, argstr, postlude ))
Beispiel #38
0
    def renderHTTP(self, ctx):

        self.setup()

        #ensure that we are delivered with the correct content type header
        inevow.IRequest(ctx).setHeader("Content-Type",
            "application/vnd.mozilla.xul+xml; charset=%s" % (self.charset,))

        #Do something a bit magical.. glue css/js stuff into the window before
        #any other widgets so they get read first.
        if self.css is not None:
            self.window.children.insert(0,
                htmlns.style(type="text/css")[self.css])
        self.css = None

        for css in self.cssIncludes:
            self.window.children.insert(0,
                htmlns.style(type="text/css", src=css))
        self.cssIncludes = []

        if self.js is not None:
            self.window.children.insert(0,
                htmlns.script(type="text/javascript")[self.js])
        self.js = None

        for js in self.jsIncludes:
            self.window.children.insert(0,
                htmlns.script(type="text/javascript", src=js))
        self.jsIncludes = []

        #We want to have javascript included in this order:
        #   preLiveglue.js
        #   liveglue.js
        #   postLiveglue.ps

        if not self.glueInstalled:

            self.window.children.insert(0, htmlns.script(
                type="text/javascript", src=url.here.child(
                    'javascript').child('postLiveglue.js')))

            self.window.children.insert(0, T.invisible(
                render=T.directive('liveglue')))

            self.window.children.insert(0, htmlns.script(
                type="text/javascript", src=url.here.child(
                    'javascript').child('preLiveglue.js')))

            self.glueInstalled = True

        #.. end magical

        #make sure our XUL tree is loaded and our correct doc type is set
        self.docFactory = loaders.stan([
            T.xml("""<?xml version="1.0"?><?xml-stylesheet href="chrome://global/skin/" type="text/css"?>"""),
            self.window])
        #return our XUL
        return athena.LivePage.renderHTTP(self, ctx)
Beispiel #39
0
 def enterValue(self, value):
     val = value.getContent("html", self.macroPackage)
     if val:
         self.resultTree[-1].append(T.xml(val))
     # for meta items rendering their children themselves (which return
     # in IncludesChildren object), do not fold in rendered children
     # (the None sentinel is handed in endKey)
     if isinstance(val, meta.IncludesChildren):
         self.resultTree[-1].append(None)
class ReSTPreview(rend.Page):
    def __init__(self, ctx, restWriter, key, srcId):
        self.restWriter = restWriter

        form = iformal.IForm(ctx)
        u = widgetResourceURLFromContext(
            ctx, form.name).child(key).child(srcId).child('_submit')
        self.destId = srcId + '-dest'
        formId = srcId + '-form'

        stan = T.html(
        )[T.head()[T.script(type="text/javascript")["""
                function ReSTTranslate() {
                    dest = document.getElementById('%(destId)s');
                    form = document.getElementById('%(formId)s');
                    src = parent.document.getElementById('%(srcId)s');
                    dest.value = src.value;
                    form.submit(); 
                }    

                """ %
                                                    {
                                                        'srcId': srcId,
                                                        'destId': self.destId,
                                                        'formId': formId
                                                    }]],
          T.body(
          )[T.form(id=formId, method="POST", action=u
                   )[T.input(type="hidden", name=self.destId, id=self.destId)],
            T.script(type="text/javascript")["ReSTTranslate();"], ], ]

        self.docFactory = loaders.stan(stan)

    def child__submit(self, ctx):
        args = inevow.IRequest(ctx).args
        value = args.get(self.destId, [''])[0]

        from docutils.utils import SystemMessage

        try:
            if self.restWriter:
                restValue = self._html_fragment(value, writer=self.restWriter)
            else:
                restValue = self._html_fragment(value, writer_name='html')
        except SystemMessage, e:
            restValue = str(e)

        stan = T.html()[T.head()[T.style(type="text/css")["""
                
                    .system-message {border: 1px solid red; background-color: #FFFFDD; margin: 5px; padding: 5px;}
                    .system-message-title { font-weight: bold;}
                """]],
                        T.body()[T.div()[T.xml(restValue)]], ]

        self.docFactory = loaders.stan(stan)

        return self
Beispiel #41
0
 def renderImmutable(self, ctx, key, args, errors):
     value = iformal.IStringConvertible(self.original).fromType(args.get(key))
     if value:
         value=T.xml(value)
     else:
         value=''
     return T.div(id=key, class_="readonly-textarea-container") [
         T.div(class_='readonly-textarea readonly')[value]
     ]
Beispiel #42
0
	def render_footnotes(self, ctx, data):
		"""renders the footnotes as a definition list.
		"""
		if self.serManager.notes:
			yield T.hr(class_="footsep")
			yield T.dl(class_="footnotes")[[
				T.xml(note.getContent(targetFormat="html", 
					macroPackage=self.serManager.table.tableDef))
				for tag, note in sorted(self.serManager.notes.items())]]
Beispiel #43
0
 def renderImmutable(self, ctx, key, args, errors):
     value = iformal.IStringConvertible(self.original).fromType(
         args.get(key))
     if value:
         value = T.xml(value)
     else:
         value = ''
     return T.div(id=key, class_="readonly-textarea-container")[T.div(
         class_='readonly-textarea readonly')[value]]
Beispiel #44
0
    def applyTable(self, page):
        headings, rows = self.getTable()
        headings.append(('', ''))

        mrows = self.jsData(headings, rows)
        newRows = self.formatTable(headings, rows)

        return [
            tags.xml("""
            <script type="text/javascript">
            function editElm%(name)s(index){
                var exRows = %(rows)s;
                var heads = %(headings)s;
                getElement('add%(name)s-editIndexNode').value=index;
                var c = 0;
                forEach(heads, function(el){
                    try {
                        var input = getElement('add%(name)s-'+el);
                        if (input.nodeName == "INPUT"){
                            if (input.type == "checkbox"){
                                var newVal = exRows[index][c].toLowerCase();
                                input.checked = (newVal == "yes") || (newVal == "true");
                            }
                            else {
                                input.value = exRows[index][c];
                            }
                        }
                        else if (input.nodeName == "SELECT") {
                            var inc = 0
                            forEach(input.options, function(opt){
                                if (opt.value == exRows[index][c]){
                                        input.selectedIndex = inc;
                                }
                                inc ++;
                            });
                        };
                    }
                    catch (dc) {}; // Ignore colums which are unparsable - look at PPP config for why ;)
                    %(extra)s
                    c++;
                });
                hideElement('addHead%(name)s');
                showElement('editHead%(name)s');
            }
            </script>
            """ % {
                'name': self.name,
                'rows': mrows, 
                'headings': map(lambda _:_[1].encode('ascii', 'replace') ,headings[:-1]), 
                'extra': self.extraJs()
            }),
            dataTable(map(lambda _:_[0] ,headings), newRows, sortable = True),
            tags.br,
            tags.h3(id='addHead%s' % self.name)["Add %s" % self.description],
            tags.h3(id='editHead%s' % self.name, style='display: none;')["Edit %s" % self.description],
            tags.directive('form add%s' % self.name)
        ]
Beispiel #45
0
 def render_rdmeta(self, ctx, data):
     # rdmeta: Meta info at the table's rd (since there's ownmeta)
     metaKey = ctx.tag.children[0]
     ctx.tag.clear()
     htmlBuilder = common.HTMLMetaBuilder(self.describingRD)
     try:
         return ctx.tag[T.xml(
             self.describingRD.buildRepr(metaKey, htmlBuilder))]
     except base.NoMetaKey:
         return ""
 def render_fragmentTemplate(self,ctx,data):
     sess = util.getStoreSession(ctx)
     items = yield sess.getItems(fragmenttype.FragmentType)
     for item in items:
         if item.name == self.original.protectedObject.type:
             fragmentType = item
             break
     template = fragmentType.template
     from genshi.template import NewTextTemplate as TextTemplate
     tmpl = TextTemplate(fragmentType.template)
     output = tmpl.generate(**self.original.protectedObject.data)
     returnValue(T.xml(output.render('text')))
Beispiel #47
0
 def render_topicHead(self, ctx, data):
     link = url.root.clear().child('topic').child(data['tid']).child('')
     title = data['ttitle']
     if len(title) > 20 and len(title.split()) < 2:
         title = title[:20]+"&hellip;"
     elif len(title.split()) >= 2 and len(title) > 35:
         title = title[:35]+"&hellip;"
     ctx.tag.fillSlots('title', t.a(href=link)[t.xml(title)])
     ctx.tag.fillSlots('posts_num', int(data['posts_num'])-1)
     ctx.tag.fillSlots('author', data['towner'])
     ctx.tag.fillSlots('section', data['stitle'])
     ctx.tag.fillSlots('modification', pptime(data['tmodification']))
     return ctx.tag
 def render_row(self, context, data):
     document = data
     words = self.query.split()
     context.fillSlots('mime_type', re.sub("/", "_", document.mime_type))
     context.fillSlots('doctitle',
                       tags.xml(boldifyText(document.title, words)))
     # XXX abstract attribute should be a unicode string
     try:
         abstract = makeAbstract(document.text, words)
         abstract = normalize_text(unicode(abstract))
     except Exception, exc:
         import traceback
         traceback.print_exc()
         print exc
         abstract = u'No abstract available for this document [%s]' % exc
Beispiel #49
0
def flattenHandler(handler, ctx):
    client = IClientHandle(ctx)
    iden = handler.identifier
    if iden is None:
        iden = client.nextId()
    iden = '--handler-%s' % (iden, )
    ## TODO this should be the IHandlerFactory instead of IResource
    setattr(IHandlerFactory(ctx), 'handle_%s' % (iden, ), handler.callme)
    isAttrib = not handler.outsideAttribute
    new = JavascriptContext(ctx, tags.invisible[handler.args], isAttrib=isAttrib)

    rv = flat.flatten(
        js.nevow_clientToServerEvent(*(iden, this, '') + handler.args),
        new)
    rv += handler.postlude
    return tags.xml(rv)
Beispiel #50
0
 def rend(self, ctx, data):
     return (tags.span(
         _class="collapser-line",
         onclick=(
             "collapse(this, '",
             self.headCollapsed,
             "', '",
             self.headExpanded,
             "');"))[
         tags.img(_class="visibilityImage", src="/images/outline-%s.png" % self.collapsed),
         tags.span(_class="headText", style="color: blue; text-decoration: underline; cursor: pointer;")[
             self.collapsed == 'collapsed' and self.headCollapsed or self.headExpanded ]
     ],
     tags.xml('&nbsp;'),
     tags.div(_class=self.collapsed)[
         self.body
     ])
Beispiel #51
0
 def render_breadcrumb(self,ctx,data):
     nodes = [self.facet]
     for segment in self.node.path.split('.')[1:]:
         node = nodes[-1].findChildBySegment(segment)
         nodes.append(node)
     nodes.reverse()
     u = None
     tags = []
     for node in nodes:
         if u is None:
             u = url.here
         else:
             u = u.up()
         tags.append(T.xml('&nbsp;&gt;&nbsp;'))
         tags.append(T.a(href=u)[node.label])
     tags.reverse()
     tags = tags[:-1]
     return ctx.tag.clear()[tags]
Beispiel #52
0
 def renderHTTP(self, ctx):
     # Call user-defined setup, so self.window becomes available.
     self.setup()
     # Ensure that we are delivered with the correct content type
     # header.
     inevow.IRequest(ctx).setHeader(
         "Content-Type",
         "application/vnd.mozilla.xul+xml; charset=%s" % (self.charset,))
     # Apply user-defined and required glue.
     self.applyAllGlue()
     # Make sure our XUL tree is loaded and our correct doc type is
     # set.
     self.docFactory = loaders.stan([
         T.xml('<?xml version="1.0"?>'
               '<?xml-stylesheet href="chrome://global/skin/" '
               'type="text/css"?>'),
         self.window,
         ])
     # Return our XUL.
     return athena.LivePage.renderHTTP(self, ctx)
Beispiel #53
0
 def rend(self, ctx, data):
     renderPrice = ctx.locate(p_basket.IPriceRenderer)
     # Product page link
     for c in self.original.categories:
         if c.startswith('gallery'):
             cat = c.split('.')[-1]
             break
         
     ctx.tag.fillSlots('url', url.URL.fromString('/gallery/%s/%s'%(cat,self.original.code)))        
     ctx.tag.fillSlots('id', self.original.id)
     ctx.tag.fillSlots('thumbnail', T.img(src='/system/ecommerce/%s/mainImage?size=95x150&sharpen=1.0x0.5%%2b0.8%%2b0.1'%self.original.productRef.product.id, class_='thumbnail'))
     ctx.tag.fillSlots('uid', self.original.uid)
     ctx.tag.fillSlots('item', self.original.item)
     if self.original.quantity > 1:
         ctx.tag.fillSlots('quantity', T.xml('x%s @ &pound;%0.2f each'%(self.original.quantity,self.original.unitPrice)))
     else:
         ctx.tag.fillSlots('quantity', '')
         
     ctx.tag.fillSlots('unitPrice', renderPrice(self.original.unitPrice))
     ctx.tag.fillSlots('totalPrice', renderPrice(self.original.quantity*self.original.unitPrice))
     return ctx.tag
Beispiel #54
0
    def render_breadcrumb(self,ctx,data):
        rootnode, u = ICurrentNodeInfo(ctx)
#        u = u.child('nav')

        ctx.tag.clear()
        breadcrumb = ctx.tag
        breadcrumb[ T.invisible()[ ('http:// ',T.a(href=u)[url.URL.fromContext(ctx).netloc],T.xml('&nbsp;/&nbsp;')) ] ]
        top = rootnode
        for segment in self.original.path.split('.')[1:]:
            if segment != top.name:
                for node in top.children:
                    if node.name == segment:
                        label = node.name
                        top = node
                        break
            else:
                label = top.name
            u = u.child(segment)
            if segment != self.original.name:
                breadcrumb[ ( ( T.a(href=u)[label], T.xml('&nbsp;/&nbsp;') ) ) ]
            else:
                breadcrumb[ label ]
        return breadcrumb
Beispiel #55
0
    def _renderTag(self, ctx, key, value, readonly):
        html = []
        tag=T.textarea(name=key, id=render_cssid(key), cols=self.cols, rows=self.rows)[value or '']
        if readonly:
            tag(class_='readonly', readonly='readonly')
        html.append(tag)
        if self.values is None:
            return html
        
        def renderOptions(ctx,options):
            for value,label in options:
                yield T.option(value=value)[label] 

            
        selecttrigger = T.select(name='%s__selecttrigger'%key, data=self.values)[ renderOptions ]


            
        form = iformal.IForm( ctx )
        js = T.xml("var x = document.getElementById('%(form)s');x.%(key)s.value += x.%(key)s__selecttrigger.options[x.%(key)s__selecttrigger.options.selectedIndex].value + &quot;\\n&quot;;"%{'key':key,'form':form.name})
        aonclick = T.a(onclick=js)[ 'add' ]
        html.append(T.div(class_="add")[selecttrigger,aonclick])
        return html