Exemplo n.º 1
0
 def getWidgets(self):
     widgets = []
     f = athena.LiveFragment(docFactory=loaders.stan(tags.div[widgets]))
     f.setFragmentParent(self)
     for i in xrange(5):
         widgets.append(athena.LiveFragment(docFactory=loaders.stan(tags.span(render=tags.directive('liveFragment')))))
         widgets[-1].setFragmentParent(f)
     return f
def renderOnce(fragmentClass):
    """
    Create L{DEPTH} LiveFragments, each nested within the next, and then render
    the result.
    """
    rname = fragmentClass.__name__[0].lower() + fragmentClass.__name__[1:]
    innerFragment = fragmentClass(docFactory=stan(p(render=directive(rname))["Hello, world."]))
    for i in xrange(DEPTH - 1):
        outerFragment = fragmentClass(docFactory=stan(p(render=directive(rname))[innerFragment]))
        innerFragment.setFragmentParent(outerFragment)
        innerFragment = outerFragment
    render(outerFragment)
	def render_head_tag(self, ctx, data):
		ctx.fillSlots('meta_tags', "")

		## CSS
		stylesheets = []
		color_option = self._get_color_option(ctx)
		global_css_includes = self.global_css_includes + ['zoto_%s.css' % color_option]
		for file in global_css_includes + self.local_css_includes:
			stylesheets += [T.link(type="text/css", rel="stylesheet", href=self.make_css_path(file)), '\n']
		ctx.fillSlots('css_includes', loaders.stan(T.invisible[stylesheets]))

		## alternate links - rss, atom, etc.
		feed_links= [] 
		for feed_url in self.global_feed_includes + self.local_feed_includes:
			feed_links += [T.link(type="application/%s+xml"%feed_url['type'], rel="alternate", href=feed_url['uri']), '\n']
		ctx.fillSlots('feed_includes', loaders.stan(T.invisible[feed_links]))

		## Javascript
		scripts = []
		if aztk_config.setup.get('site', 'environment') in ["sandbox", "development"]:
			for script in self.global_js_includes + self.local_js_includes:
				if script == "core.js":
					for script in js.core_js.scripts:
						scripts += [T.script(type="text/javascript", src=self.make_js_path(script)), '\n']
				elif script == "site.js":
					for script in js.site_js.scripts:
						scripts += [T.script(type="text/javascript", src=self.make_js_path(script)), '\n']
				elif script == "managers.js":
					for script in js.managers_js.scripts:
						scripts += [T.script(type="text/javascript", src=self.make_js_path(script)), '\n']
				elif script == "mochikit.js":
					scripts += [
						T.script(type="text/javascript", src=self.make_js_path("third_party/MochiKit/MochiKit.js")), '\n',
						T.script(type="text/javascript", src=self.make_js_path("third_party/MochiKit/DragAndDrop.js")), '\n',
						T.script(type="text/javascript", src=self.make_js_path("third_party/MochiKit/Sortable.js")), '\n'
					]
				else:
					scripts += [T.script(type="text/javascript", src=self.make_js_path(script)), '\n']
			if self.page_manager_js:
				scripts += [T.script(type="text/javascript", src=self.make_js_path(self.page_manager_js)), '\n']
			ctx.fillSlots('js_includes', loaders.stan(T.invisible[scripts]))
		else:
			for script in self.global_js_includes + self.local_js_includes:
				if script == "mochikit.js":
					scripts += [T.script(type="text/javascript", src=self.make_js_path("third_party/MochiKit/packed/MochiKit.js")), '\n']
				else:
					scripts += [T.script(type="text/javascript", src=self.make_js_path(script)), '\n']
			if self.page_manager_js:
				scripts += [T.script(type="text/javascript", src=self.make_js_path(self.page_manager_js)), '\n']
			ctx.fillSlots('js_includes', loaders.stan(T.invisible[scripts]))

		return ctx
Exemplo n.º 4
0
        def _renderPage():
            page = MantissaLivePage(FakeWebSite())
            element = LiveElement(stan(tags.span(render=tags.directive('liveElement'))))
            element.setFragmentParent(page)
            element.jsClass = u'Mantissa.Test.Dummy.DummyWidget'
            page.docFactory = stan([tags.span(render=tags.directive('liveglue')), element])

            ctx = WovenContext()
            req = FakeRequest(headers={'host': self.hostname})
            ctx.remember(req, IRequest)
            page.beforeRender(ctx)
            page.renderHTTP(ctx)
            page._messageDeliverer.close()
	def render_content(self, ctx, data):
		request = inevow.IRequest(ctx)
		
		ctx.fillSlots('header_bar', self.anon_header) 
		ctx.fillSlots('top_bar', T.div(id="top_bar"))
		ctx.fillSlots('main_content', loaders.stan(T.div(id="manager_hook")))
		return ctx.tag
    def test_reusedDocFactory(self):
        """
        Test that a docFactory which is used more than once behaves properly
        both times.
        """
        class Page(rend.Page):
            docFactory = loaders.stan(div[invisible(render=directive('included'))])

            def __init__(self, included):
                self.included = included
                rend.Page.__init__(self)

            def render_included(self, context, data):
                return self.included

        p1 = Page(loaders.stan('first'))
        p2 = Page(loaders.xmlstr('<p>second</p>'))

        d = deferredRender(p1)
        def rendered(result):
            self.assertEqual(result, '<div>first</div>')
            return deferredRender(p2)
        d.addCallback(rendered)

        def renderedAgain(result):
            self.assertEqual(result, '<div><p>second</p></div>')
        d.addCallback(renderedAgain)

        return d
Exemplo n.º 7
0
    def test_docFactoryInStanTree(self):

        class Page(rend.Page):

            def __init__(self, included):
                self.included = included
                rend.Page.__init__(self)

            def render_included(self, context, data):
                return self.included
            
            docFactory = loaders.stan(div[invisible(render=directive('included'))])

        doc = '<p>fum</p>'
        temp = self.mktemp()
        f = file(temp, 'w')
        f.write(doc)
        f.close()

        result = deferredRender(Page(loaders.stan(p['fee'])))
        self.assertEquals(result, '<div><p>fee</p></div>')
        result = deferredRender(Page(loaders.htmlstr('<p>fi</p>')))
        self.assertEquals(result, '<div><p>fi</p></div>')
        result = deferredRender(Page(loaders.xmlstr('<p>fo</p>')))
        self.assertEquals(result, '<div><p>fo</p></div>')
        result = deferredRender(Page(loaders.htmlfile(temp)))
        self.assertEquals(result, '<div><p>fum</p></div>')
        result = deferredRender(Page(loaders.xmlfile(temp)))
        self.assertEquals(result, '<div><p>fum</p></div>')
Exemplo n.º 8
0
    def test_simple(self):

        doc = div[p['foo'],p['bar']]
        result = unittest.deferredResult(
            rend.Page(docFactory=loaders.stan(doc)).renderString()
            )
        self.assertEquals(result, '<div><p>foo</p><p>bar</p></div>')
Exemplo n.º 9
0
    def doRendering(self, fragmentClass):
        """
        Verify that the given fragment class will render without raising an
        exception.
        """
        siteStore = Store()

        loginSystem = LoginSystem(store=siteStore)
        installOn(loginSystem, siteStore)
        p = Product(
            store=siteStore, types=["xmantissa.webadmin.LocalUserBrowser", "xmantissa.signup.SignupConfiguration"]
        )
        account = loginSystem.addAccount(u"testuser", u"localhost", None)
        p.installProductOn(account.avatars.open())
        f = fragmentClass(None, u"testuser", account)

        p = LivePage(docFactory=stan(html[head(render=directive("liveglue")), body(render=lambda ctx, data: f)]))
        f.setFragmentParent(p)

        ctx = WovenContext()
        req = FakeRequest()
        ctx.remember(req, IRequest)

        d = p.renderHTTP(ctx)

        def rendered(ign):
            p.action_close(None)

        d.addCallback(rendered)
        return d
Exemplo n.º 10
0
 def speed(self, speed):
     return rend.Page(
         docFactory=loaders.stan(
             tags.html[
                 tags.body(id='body')[
                     "Thanks for taking our survey! You said: %r %r %r" % (
                         self.original[0], self.original[1], speed)]]))
Exemplo n.º 11
0
    def test_blogsRenderer(self):
        """
        Test that L{hyperbola_view.BlogListFragment.blogs} renders a list of blogs.
        """
        site = self.siteStore.findUnique(SiteConfiguration)
        site.hostname = u'blogs.renderer'
        blog1 = self._shareAndGetProxy(self._makeBlurb(FLAVOR.BLOG))
        blog2 = self._shareAndGetProxy(self._makeBlurb(FLAVOR.BLOG))
        blf = hyperbola_view.BlogListFragment(
            athena.LivePage(), self.publicPresence)
        blf.docFactory = loaders.stan(
            tags.div(pattern='blog')[
                tags.span[tags.slot('title')],
                tags.span[tags.slot('link')],
                tags.span[tags.slot('post-url')]])
        tag = tags.invisible
        markup = flat.flatten(tags.div[blf.blogs(None, tag)])
        doc = minidom.parseString(markup)
        blogNodes = doc.firstChild.getElementsByTagName('div')
        self.assertEqual(len(blogNodes), 2)

        for (blogNode, blog) in zip(blogNodes, (blog1, blog2)):
            (title, blogURL, postURL) = blogNode.getElementsByTagName('span')
            blogURL = blogURL.firstChild.nodeValue
            expectedBlogURL = str(websharing.linkTo(blog))
            self.assertEqual(blogURL, expectedBlogURL)
            postURL = postURL.firstChild.nodeValue
            self.assertEqual(
                postURL, 'https://blogs.renderer' + expectedBlogURL + '/post')
Exemplo n.º 12
0
 def test_patterned(self):
     """Test fetching a specific part (a pattern) of the document.
     """
     doc = t.div[t.p[t.span(pattern='inner')['something']]]
     df = loaders.stan(doc, pattern='inner')
     self.assertEquals(df.load()[0].tagName, 'span')
     self.assertEquals(df.load()[0].children[0], 'something')
Exemplo n.º 13
0
        def __init__(self, ctx, restWriter, key, srcId):
            self.restWriter = restWriter

            form = iformal.IForm( ctx )
            u = formal_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)
Exemplo n.º 14
0
 def test_synchronousFlatten(self):
     """
     Flattening a L{Element} with no Deferreds using the old synchronous
     flattener API returns a value synchronously.
     """
     element = Element()
     element.docFactory = stan(["hello, world"])
     self.assertEqual(synchronousFlatten(element), "hello, world")
Exemplo n.º 15
0
 def setUp(self):
     self.d = Deferred()
     self.d2 = Deferred()
     self.r = rend.Page(docFactory=loaders.stan(
         tags.html(data=self.data_later)[
             'Hello ', str, ' and '
             'goodbye ',str,
             tags.span(data=self.data_later2, render=str)]))
Exemplo n.º 16
0
 def test_simpleStanRendering(self):
     """
     Test that a Element with a simple, static stan document factory
     renders correctly.
     """
     f = Element(docFactory=stan(p["Hello, world."]))
     return self._render(f).addCallback(
         self.assertEqual, "<p>Hello, world.</p>")
Exemplo n.º 17
0
 def test_stanPreprocessors(self):
     """
     Test that the stan loader properly passes uncompiled documents to
     preprocessors it is given.
     """
     factory = loaders.stan(
         t.div[t.span['Hello'], t.span['world']])
     return self._preprocessorTest(factory)
Exemplo n.º 18
0
 def setUp(self):
     self.d = Deferred()
     self.d2 = Deferred()
     self.r = rend.Page(
         docFactory=loaders.stan(
             html(data=self)["Hello ", invisible[invisible[invisible[invisible[deferit]]]], deferdot]
         )
     )
Exemplo n.º 19
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)
Exemplo n.º 20
0
 def _render(self, fragment, request=None):
     """
     Test helper which tries to render the given fragment.
     """
     ctx = WovenContext()
     if request is None:
         request = FakeRequest()
     ctx.remember(request, IRequest)
     return Page(docFactory=stan(fragment)).renderString(ctx)
Exemplo n.º 21
0
def renderPlainFragment(fragment):
    """
    same as L{render}, but expects an L{nevow.rend.Fragment} or any
    other L{nevow.inevow.IRenderer}
    """
    page = Page(docFactory=stan(fragment))
    (request, context) = _makeContext()
    page.renderHTTP(context)
    return request.v
Exemplo n.º 22
0
 def test_synchronousFlattenError(self):
     """
     If the old flattener encounters an exception while flattening an
     L{IRenderable}, the exception is raised to the caller of the flattener
     API.
     """
     element = Element()
     element.docFactory = stan(invisible(render=directive('foo')))
     self.assertRaises(FlattenerError, synchronousFlatten, element)
Exemplo n.º 23
0
 def offerings():
     for p in self.offeringPlugins.itervalues():
         data = {'name': p.name, 'description': p.description}
         if p.name not in self.installedOfferings:
             f = UninstalledOfferingFragment(data, self.original, p, docFactory=loaders.stan(uninstalled()))
             f.page = self.page
         else:
             f = rend.Fragment(data, docFactory=loaders.stan(installed()))
         yield f
Exemplo n.º 24
0
 def _instaString(self, x):
     """
     Convert a new-style-renderable thing into a string, raising an
     exception if any deferred rendering took place.
     """
     e = Element(docFactory=stan(x))
     l = []
     d = deferflatten(None, e, False, False, l.append)
     return ''.join(l)
Exemplo n.º 25
0
 def _doubleLiveSerialization(self, cls, renderer):
     livePage = DummyLivePage()
     liveFragment = cls(
         docFactory=loaders.stan(
             [tags.div(render=tags.directive(renderer))['Hello'],
              tags.div(render=tags.directive('foo'))]))
     liveFragment.setFragmentParent(livePage)
     self.assertEqual(
         json.serialize(liveFragment),
         json.serialize(liveFragment))
Exemplo n.º 26
0
 def setUp(self):
     self.d = Deferred()
     self.d2 = Deferred()
     self.r = rend.Page(
         docFactory=loaders.stan(
             html(data=self.data_later)[
                 "Hello ", str, " and " "goodbye ", str, span(data=self.data_later2, render=str)
             ]
         )
     )
Exemplo n.º 27
0
 def convertFragments(self, data):
     result = []
     if not data:
         return []
     for column, value, sort in data:
         result.append((column,
                        FragmentMixIn(self.dbpool,
                                      docFactory=loaders.stan(value)),
                        sort))
     return result
Exemplo n.º 28
0
 def test_deferredProperty(self):
     class IDeferredProperty(formless.TypedInterface):
         d = formless.String()
     from nevow import util
     deferred = util.Deferred()
     deferred.callback('the default value')
     class Implementation(object):
         __implements__ = IDeferredProperty,
         d = deferred
     result = deferredRender(rend.Page(Implementation(), docFactory=loaders.stan(html[freeform.renderForms('original')])))
     self.assertIn('value="the default value"', result)
Exemplo n.º 29
0
 def setUp(self):
     self.d = Deferred()
     self.d2 = Deferred()
     self.r = rend.Page(
         docFactory=loaders.stan(
             tags.html(data=self)[
                 'Hello ', tags.invisible[tags.invisible[tags.invisible[tags.invisible[deferit]]]],
                 deferdot,
                 ]
             )
         )
Exemplo n.º 30
0
 def test_reusedDeferredSupport(self):
     """
     Two occurrences of a particular slot are each replaced with the
     result of the Deferred which is used to fill that slot.
     """
     doc = tags.html[
         tags.slot('foo'), tags.slot('foo')]
     doc.fillSlots('foo', defer.succeed(tags.span['Foo!!!']))
     self.r = rend.Page(docFactory=loaders.stan(doc))
     req = self.renderIt()
     self.assertEqual(req.v, '<html><span>Foo!!!</span><span>Foo!!!</span></html>')
Exemplo n.º 31
0
        class FormPage(rend.Page):
            bind_test1 = [('foo', annotate.String()), ('bar', annotate.Integer())]
            bind_test2 = annotate.MethodBinding('test2', annotate.Method(
                arguments=[annotate.Argument('foo', annotate.String())]))

            bind_test3 = annotate.Property('test3', annotate.Integer())
            
            def bind_test4(self, ctx):
                return ([('foo', annotate.String()), ('bar', annotate.Integer())])
            
            def bind_test5(self, ctx):
                return annotate.MethodBinding('test5', annotate.Method(
                    arguments=[annotate.Argument('foo', annotate.String()),
                               annotate.Argument('bar', annotate.Integer())]))

            docFactory = loaders.stan(html[freeform.renderForms()])
 def makeDocFactory(self):
     return loaders.stan([
         T.div(render=T.directive("meta"), class_="warning")["_warning"],
         T.table(
             class_="keyvalue",
             render=rend.mapping,
             data=T.directive("firstrow"))[[[
                 T.tr[T.th(data=colDef,
                           render=T.directive("headCell"),
                           class_="thHorizontal"), td],
                 T.tr(class_="keyvaluedesc")[T.td(
                     colspan=2)[colDef.description]]
             ] for colDef, td in zip(self.serManager.table.tableDef.columns,
                                     self.defaultTds)]],
         T.invisible(render=T.directive("footnotes")),
     ])
Exemplo n.º 33
0
class StatsTestCase(testcase.TestCase):
    jsClass = u'Mantissa.Test.StatsTest'
    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveTest'))[tags.invisible(
            render=tags.directive('start'))])

    def render_start(self, ctx, data):
        self.testfragment = AdminStatsTestBase()
        self.testfragment.setFragmentParent(self)
        return self.testfragment

    def run(self):
        self.testfragment.statUpdate(extime.Time(), [(u'graph1', 43)])
        self.testfragment.queryStatUpdate(extime.Time(), [(u'beans', 2)])

    athena.expose(run)
Exemplo n.º 34
0
class VirtualHostList(rend.Page):
    def __init__(self, nvh):
        rend.Page.__init__(self)
        self.nvh = nvh

    stylesheet = """
    body { border: 0; padding: 0; margin: 0; background-color: #efefef; }
    h1 {padding: 0.1em; background-color: #777; color: white; border-bottom: thin white dashed;}
"""

    def getStyleSheet(self):
        return self.stylesheet

    def data_hostlist(self, context, data):
        return self.nvh.hosts.keys()

    def render_hostlist(self, context, data):
        host = data
        req = context.locate(inevow.IRequest)
        proto = req.clientproto.split('/')[0].lower()
        port = req.getHeader('host').split(':')[1]

        link = "%s://%s" % (proto, host)

        if port != 80:
            link += ":%s" % port

        link += req.path

        return context.tag[tags.a(href=link)[host]]

    def render_title(self, context, data):
        req = context.locate(inevow.IRequest)
        proto = req.clientproto.split('/')[0].lower()
        host = req.getHeader('host')
        return context.tag["Virtual Host Listing for %s://%s" % (proto, host)]

    def render_stylesheet(self, context, data):
        return tags.style(type="text/css")[self.getStyleSheet()]

    docFactory = loaders.stan(tags.html[tags.head[
        tags.title(render=render_title),
        tags.directive('stylesheet'), ], tags.body[
            tags.h1(render=render_title),
            tags.ul(data=directive("hostlist"), render=directive("sequence")
                    )[tags.li(pattern="item", render=render_hostlist)]]])
Exemplo n.º 35
0
class Tester(livepage.LivePage):
    addSlash = True
    child_css = static.File(os.path.join(resourceDirectory, 'livetest.css'))
    child_scripts = static.File(os.path.join(resourceDirectory, 'livetest.js'))
    child_postscripts = static.File(
        os.path.join(resourceDirectory, 'livetest-postscripts.js'))
    docFactory = loaders.stan(tags.html[
        tags.head[tags.script(src="scripts"),
                  tags.link(rel="stylesheet", type="text/css", href="css")],
        tags.body[tags.table(id="testprogress")[
            tags.tr[tags.th["Tests"], tags.th["Pass"], tags.th["Fail"]], tags.
            tr[tags.td(id="test-status")["Running"],
               tags.td(id="test-passes", _class="test-passes")[entities.nbsp],
               tags.td(id="test-failures", _class="test-failures")[entities.
                                                                   nbsp]]],
                  tags.
                  table(id="testresults", render=tags.directive('table')
                        )[tags.
                          tr(pattern="item", render=tags.directive('test'))[
                              tags.td[tags.slot('action')],
                              tags.td[tags.slot('target')],
                              tags.td[tags.slot('parameter')]]],
                  tags.iframe(id="testframe", src="asdf"),
                  tags.script(src="postscripts"), livepage.glue]])

    def render_table(self, ctx, suite):
        self.testId = 0
        driver = Driver(suite)
        handle = livepage.IClientHandle(ctx)
        driver.notifyWhenTestsComplete().addCallback(self.testsComplete,
                                                     handle)
        driver.setHandle(handle)
        driver.nextTest()
        return rend.sequence(ctx, suite)

    def render_test(self, ctx, test):
        ctx.tag(id=("test-", self.testId))
        action, target, parameter = test
        ctx.fillSlots('action', action)
        ctx.fillSlots('target', str(target))
        ctx.fillSlots('parameter', parameter)
        self.testId += 1
        return ctx.tag

    def testsComplete(self, results, handle):
        handle.set('test-status', 'Complete')
Exemplo n.º 36
0
class SubheadingFieldFragment(form.FieldFragment):
    docFactory = loaders.stan(
        T.div(id=T.slot('fieldId'),
              _class=T.slot('fieldClass'),
              render=T.directive('field'))[
          T.div(_class='formal-subheading-field')[ T.slot('fieldContents') ]
          ])
          
    def render_field(self, ctx, data):
        # No fancy widget-stuff here

        ourform = iformal.IForm(ctx)
        classes = ['field', 'subheading-field']
        ctx.tag.fillSlots('fieldId', '%s-%s-field' % (ourform.name, self.field.name))  # XXX: unused...
        ctx.tag.fillSlots('fieldClass', ' '.join(classes))
        ctx.tag.fillSlots('fieldContents', self.field.label)
        return ctx.tag
Exemplo n.º 37
0
class ChildPage(rend.Page):
    def __init__(self, name):
        rend.Page.__init__(self)
        self.name = name

    def child_childOfChild(self, context):
        return ChildOfChildPage(self.name)

    def render_name(self, context, data):
        return self.name

    docFactory = loaders.stan(
        T.html[T.body[T.h1['ChildPage'], T.p['My name is: ',
                                             T.span(id="name")[render_name]],
                      T.p['I have child too: ',
                          T.a(id="child", href=url.here.child('childOfChild')
                              )['my child']], ]])
Exemplo n.º 38
0
 def test_oldFlattenableInAttribute(self):
     """
     Flattening a L{Element} as the value of an attribute of a L{Tag} XML
     attribute escapes the element's flattened document.
     """
     result = []
     element = Element()
     element.docFactory = stan(['"&<>'])
     request = FakeRequest()
     context = WovenContext()
     context.remember(request)
     finished = oldFlatten(p(foo=element), context, result.append,
                           lambda ign: ign)
     finished.addCallback(lambda ign: "".join(result))
     finished.addCallback(self.assertEqual,
                          '<p foo="&quot;&amp;&lt;&gt;"></p>')
     return finished
Exemplo n.º 39
0
class CalendarElement(LiveElement):

    docFactory = stan(div[
            "It's a calendar!",
            div(render="appointments"),
            div(render="appointmentForm")])

    def __init__(self, calendar):
        LiveElement.__init__(self)
        self.calendar = calendar


    @renderer
    def appointments(self, request, tag):
        appointments = self.calendar.getAppointments()
        for appointment in appointments:
            appDiv = div[
                "Appointment with ",
                appointment.withWhomUsername, "@",
                appointment.withWhomDomain, " at ",
                appointment.when.asHumanly()]
            if appointment.failed is not None:
                appDiv[" (Rejected: ", appointment.failed, ")"]
            elif appointment.remoteID is None:
                appDiv[" (Pending confirmation)"]
            tag[appDiv]
        return tag


    def _requestAppointment(self, whom):
        local, domain = whom.split(u"@")
        target = self.calendar.calendarIDFor(local, domain)
        self.calendar.requestAppointmentWith(target, Time() + timedelta(days=2))


    @renderer
    def appointmentForm(self, request, tag):
        form = LiveForm(
            self._requestAppointment,
            [Parameter(u"whom", TEXT_INPUT, unicode, u"Whom:",
                       u"The username of the person with whom "
                       u"to create an appointment (user@domain).",
                       None)],
            "Request An Appointment")
        form.setFragmentParent(self)
        return form
Exemplo n.º 40
0
class ElementRenderingLivePage(LivePage):
    """
    Trivial LivePage which renders an instance of a particular element class.
    """
    docFactory = stan(html[head(render=directive('liveglue'))[title(
        render=directive('title'))], body[div(render=directive('element'))]])

    def __init__(self, element):
        LivePage.__init__(self)
        self.element = element

    def render_title(self, ctx, data):
        return ctx.tag[self.element.__class__.__name__]

    def render_element(self, ctx, data):
        self.element.setFragmentParent(self)
        return ctx.tag[self.element]
Exemplo n.º 41
0
    def makePage(self, content):
        _ = i18n.Translator(translator=mockTranslator)
        page = rend.Page(
            docFactory=loaders.stan(tags.invisible(render=tags.directive('i18n'))[content]))
        page.render_i18n = i18n.render(_)
        doc = page.docFactory.load()
        ctx = context.WovenContext(context.PageContext(tag=page),
                                   tags.invisible[doc])
        page.rememberStuff(ctx)

        io = StringIO()
        writer = io.write

        def finisher(result):
            return io.getvalue()

        return page.flattenFactory(doc, ctx, writer, finisher)
Exemplo n.º 42
0
 def test_renderAttributeNestedInPrecompiledSlot(self):
     """
     A L{Tag} with a renderer which is used as the value of a
     L{_PrecompiledSlot} which was returned by L{IRenderable.render} is
     replaced with the result of the named renderer on the L{IRenderable}
     which returned the L{_PrecompiledSlot}.
     """
     result = "quux"
     renders = []
     request = object()
     outer = invisible[stan(div[slot("bar")]).load()]
     inner = div(render="foo")
     outer.fillSlots("bar", inner)
     renderable = RenderRenderable(renders, "foo", outer, result)
     self.assertStringEqual(self.flatten(renderable, request),
                            "<div>quux</div>")
     self.assertEqual(renders, [(renderable, request)])
Exemplo n.º 43
0
 def flattenList(self, data):
     result = []
     errors = []
     for (success, value) in data:
         if success:
             for r in value:
                 result.append(r)
         else:
             print "While getting details for %s, port %d:" % (self.ip,
                                                               self.index)
             value.printTraceback()
             errors.append(
                 T.span(_class="error")["%s" % value.getErrorMessage()])
     if errors:
         result.append(
             ("Errors", rend.Fragment(docFactory=loaders.stan(errors))))
     return result
Exemplo n.º 44
0
    def test_deferredProperty(self):
        class IDeferredProperty(formless.TypedInterface):
            d = formless.String()

        from nevow import util
        deferred = util.Deferred()
        deferred.callback('the default value')

        @implementer(IDeferredProperty)
        class Implementation(object):
            d = deferred

        return deferredRender(
            rend.Page(
                Implementation(),
                docFactory=loaders.stan(html[freeform.renderForms(
                    'original')]))).addCallback(lambda result: self.assertIn(
                        'value="the default value"', result))
Exemplo n.º 45
0
 def test_elementContainingDynamicElement(self):
     """
     Test that directives in the document factory of a Element returned from a
     render method of another Element are satisfied from the correct object:
     the "inner" Element.
     """
     class OuterElement(Element):
         def outerMethod(self, request, tag):
             return tag[InnerElement(docFactory=stan(directive("innerMethod")))]
         renderer(outerMethod)
     class InnerElement(Element):
         def innerMethod(self, request, tag):
             return "Hello, world."
         renderer(innerMethod)
     f = OuterElement(
         docFactory=stan(p(render=directive('outerMethod'))))
     return self._render(f).addCallback(
         self.assertEqual, "<p>Hello, world.</p>")
Exemplo n.º 46
0
class Page(rend.Page):

    addSlash = True

    def render_one(self, ctx, data):
        return IFullView(random.choice(objs))

    docFactory = loaders.stan(
        T.html[
            T.body[
                T.ul(data=objs, render=rend.sequence)[
                T.li(pattern='item')[lambda c,d: ISummaryView(d)]
                    ],
                T.hr,
                render_one,
                ],
            ]
        )
Exemplo n.º 47
0
class ImagePage(rend.Page):
    """A simple page that renders a list of images. We registered an adapter
    earlier so that the data= directives inside the pattern can look inside
    Image instances.
    """

    addSlash = True

    def render_images(self, ctx, data):
        """Render a list of images.
        """
        tag = T.div(data=images, render=rend.sequence)[T.div(pattern='item')[
            T.p(data=T.directive('filename'), render=T.directive('data')),
            T.ul(data=T.directive('comments'), render=rend.sequence)[
                T.li(pattern='item', render=T.directive('data')), ], ], ]
        return tag

    docFactory = loaders.stan(T.html[T.body[T.directive('images')]])
Exemplo n.º 48
0
    def test_peopleMessageListRendering(self):
        mlister = MessageLister(store=self.substore)
        installOn(mlister, self.substore)

        p = Person(store=self.substore, name=u'Bob')

        EmailAddress(store=self.substore, person=p, address=u'bob@internet')

        for i in xrange(5):
            testMessageFactory(store=self.substore,
                               subject=unicode(str(i)),
                               receivedWhen=Time(),
                               spam=False,
                               sender=u'bob@internet')

        self.assertEqual(len(list(mlister.mostRecentMessages(p))), 5)
        return renderPage(
            rend.Page(docFactory=loaders.stan(MessageList(mlister, p))))
Exemplo n.º 49
0
    def getWidgetWithCSSDependencies(self):
        """
        Return a widget which depends on some CSS.
        """
        self.page.cssModules = self._makeCSSRegistry()

        element = athena.LiveElement()
        element.cssModule = 'TestCSSModuleDependencies.Dependor'
        element.setFragmentParent(self)
        element.docFactory = loaders.stan(
            tags.div(render=tags.directive('liveElement')))

        return (element, [
            str(self.page.getCSSModuleURL(n))
            for n in ('TestCSSModuleDependencies',
                      'TestCSSModuleDependencies.Dependee',
                      'TestCSSModuleDependencies.Dependor')
        ])
Exemplo n.º 50
0
class SearchVlan(rend.Fragment, RenderMixIn):

    docFactory = loaders.stan(
        T.span(render=T.directive("nvlan"), data=T.directive("nvlan")))

    def __init__(self, dbpool, vlan):
        self.vlan = vlan
        self.dbpool = dbpool
        rend.Fragment.__init__(self)

    def data_nvlan(self, ctx, data):
        return self.dbpool.runQueryInPast(
            ctx, "SELECT e.name, p.name "
            "FROM vlan_full v, port_full p, equipment_full e "
            "WHERE v.equipment=e.ip "
            "AND p.equipment=e.ip "
            "AND v.port=p.index "
            "AND v.vid=%(vid)s "
            "AND v.type=%(type)s "
            "AND v.deleted='infinity' "
            "AND p.deleted='infinity' "
            "AND e.deleted='infinity' "
            "ORDER BY v.vid, p.index", {
                'vid': self.vlan,
                'type': self.type
            })

    def render_nvlan(self, ctx, results):
        if not results:
            return ctx.tag["This VLAN is not known %sly." % self.type]
        ports = {}
        for equip, port in results:
            if equip not in ports:
                ports[equip] = []
            if port not in ports[equip]:
                ports[equip].append(port)
        return ctx.tag["This VLAN can be found %sly on:" % self.type, T.ul[[
            T.
            li[T.invisible(data=equip, render=T.directive("hostname")),
               T.small[
                   " (on port%s " % (len(ports[equip]) > 1 and "s: " or ""),
                   T.invisible(data=ports[equip], render=T.directive("ports")),
                   ")"]] for equip in ports
        ]]]
Exemplo n.º 51
0
class EquipmentVlansResource(rend.Page, RenderMixIn):
    """Give the list of vlans for a given equipment (as an HTML table)"""

    docFactory = loaders.stan(
        T.span(render=T.directive("vlans"), data=T.directive("vlans")))
    addSlash = True

    def __init__(self, ip, dbpool):
        self.dbpool = dbpool
        self.ip = ip
        rend.Page.__init__(self)

    def render_vlans(self, ctx, data):
        if not data:
            return ctx.tag["No VLAN information available for this host."]
        vlans = {}
        for row in data:
            if (row[0], row[1]) not in vlans:
                vlans[row[0], row[1]] = []
            vlans[row[0], row[1]].append(row[2])
        r = []
        i = 0
        vlans = list(vlans.iteritems())
        vlans.sort()
        for (vid, name), ports in vlans:
            r.append(
                T.tr(_class=(i % 2) and "odd" or "even")
                [T.td[T.span(data=vid, render=T.directive("vlan"))],
                 T.td[name],
                 T.td(render=T.directive("ports"), data=ports)])
            i += 1
        return T.table(_class="vlan")[T.thead[T.td["VID"], T.td["Name"],
                                              T.td["Ports"]], r]

    def data_vlans(self, ctx, data):
        return self.dbpool.runQueryInPast(
            ctx, "SELECT v.vid, v.name, p.name "
            "FROM vlan_full v, port_full p "
            "WHERE v.equipment=%(ip)s AND v.type='local' "
            "AND v.port = p.index "
            "AND p.equipment = v.equipment "
            "AND p.deleted='infinity' AND v.deleted='infinity' "
            "ORDER BY v.vid, p.index", {'ip': str(self.ip)})
Exemplo n.º 52
0
def renderLiveFragment(fragment):
    """
    Render the given fragment in a LivePage.

    This can only work for fragments which can be rendered synchronously.
    Fragments which involve Deferreds will be silently rendered incompletely.

    @type fragment: L{nevow.athena.LiveFragment} or L{nevow.athena.LiveElement}
    @param fragment: The page component to render.

    @rtype: C{str}
    @return: The result of rendering the fragment.
    """
    page = LivePage(docFactory=stan(fragment))
    fragment.setFragmentParent(page)
    (request, context) = _makeContext()
    page.renderHTTP(context)
    page.action_close(context)
    return request.v
Exemplo n.º 53
0
class Page(rend.Page):

    addSlash = True

    def locateChild(self, ctx, segments):

        # Handle the form post
        if segments[0] == SUBMIT:
            # Just print out the name
            print('*** name:', ctx.arg('name'))
            # Redirect away from the POST
            return url.URL.fromContext(ctx), ()

        return rend.Page.locateChild(self, ctx, segments)

    docFactory = loaders.stan(
        T.html[T.body[T.form(action=url.here.child(SUBMIT), method="post")[
            T.label['Name:'],
            T.input(type="text", name="name"), ], ], ])
Exemplo n.º 54
0
        class R(rend.Page):
            def data_numbers(context, data):
                return [
                    ['one', 'un/une'],
                    ['two', 'deux'],
                    ['three', 'trois'],
                ]

            def render_row(context, data):
                context.fillSlots('english', data[0])
                context.fillSlots('french', data[1])
                return context.tag

            tags = table(data=data_numbers, render=directive('sequence'))[
                tr(pattern='header')[th['English'], th['French']],
                tr(pattern='item', render=render_row)[td[slot('english')],
                                                      td[slot('french')]], ]

            docFactory = loaders.stan(tags)
Exemplo n.º 55
0
class Canvas(rend.Page):
    """A page which can embed canvases. Simplest usage is to subclass and
    override width, height and onload. Then, putting render_canvas in the
    template will output that canvas there.
    
    You can also embed more than one canvas in a page using the canvas
    helper function, canvas(width, height, onload). The resulting stan
    will cause a canvas of the given height and width to be embedded in
    the page at that location, and the given onload callable to be called
    with a CanvasSocket when the connection is established.
    """
    addSlash = True
    def __init__(self, original=None, width=None, height=None, onload=None, 
    onMouseMove=None, onMouseDown=None, onMouseUp=None, 
    onKeyDown=None, onKeyUp=None, **kw):
        rend.Page.__init__(self, original, **kw)
        if width: self.width = width
        if height: self.height = height
        if onload: self.onload = onload
        if onMouseMove: self.onMouseMove = onMouseMove
        if onMouseDown: self.onMouseDown = onMouseDown
        if onMouseUp: self.onMouseUp = onMouseUp
        if onKeyDown: self.onKeyDown = onKeyDown
        if onKeyUp: self.onKeyUp = onKeyUp

    def child_canvas_socket(self, ctx):
        return CanvasSocket()

    width = 1000
    height = 500

    onload = None
    onMouseDown = None
    onMouseUp = None
    onMouseMove = None
    onKeyUp = None
    onKeyDown = None

    def render_canvas(self, ctx, data):
        return canvas(
            self.width, self.height, self)

    docFactory = loaders.stan(tags.html[render_canvas])
Exemplo n.º 56
0
class MenuFragment(athena.LiveElement, log.Loggable):
    logCategory = 'webui_menu_fragment'
    jsClass = u'Coherence.Base'
    fragmentName = 'coherence-menu'

    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveElement'))
        [tags.div(id="coherence_menu_box", class_="coherence_menu_box")[""], ])

    def __init__(self, page):
        super(MenuFragment, self).__init__()
        self.setFragmentParent(page)
        self.page = page
        self.coherence = page.coherence
        self.tabs = []

    def going_live(self):
        self.info("add a view to the MenuFragment")
        d = self.page.notifyOnDisconnect()
        d.addCallback(self.remove_me)
        d.addErrback(self.remove_me)
        if len(self.tabs):
            return self.tabs
        else:
            return {}

    athena.expose(going_live)

    def add_tab(self, title, active, id):
        self.info("add tab %s to the MenuFragment" % title)
        new_tab = {
            u'title': unicode(title),
            u'active': unicode(active),
            u'athenaid': u'athenaid:%d' % id
        }
        for t in self.tabs:
            if t[u'title'] == new_tab[u'title']:
                return
        self.tabs.append(new_tab)
        self.callRemote('addTab', new_tab)

    def remove_me(self, result):
        self.info("remove view from MenuFragment")
Exemplo n.º 57
0
class TestTests(rend.Page):
    addSlash = True
    docFactory = loaders.stan(tags.html[tags.a(href="/testtests/tests/")["Run tests"]])
    child_foo = '<html><body><div id="body">foo</div><form method="POST", name="theForm" action="postTarget"><input name="blah" /></form></body></html>'
    child_bar = "bar"
    child_baz = '<html><body onclick="alert(event.clientX);alert( event.clientY);"><div id="body">toot</div><a id="nextPage" href="foo" onclick="alert(\'clicked\')">Foo</a></body></html>'

    child_clickHandler = """<html>
    <body>
        <a id="theClicker" onclick="this.innerHTML='Clicked'">Click me!</a>
    </body>
</html>"""

    def child_postTarget(self, ctx):
        return rend.Page(
            docFactory=loaders.stan(
                tags.html[tags.body(id="body")[str(ctx.arg('blah'))]]))

    def child_testtests(self, ctx):
        return self

    def child_xpath(self, ctx):
        ## print 'lkfjasldkjasd!!!!!!!!'
        return ChildXPath()

    child_tests = Tester([
    ('visit', '/testtests/xpath', ''),
    ('assert', xpath('/html/body/div/span/div[@id="target-node-identifier"]'), 'expected content'),
    ('visit', '/testtests/foo', ''),
    ('visit', '/testtests/bar', ''),
    ('visit', '/testtests/baz', ''),
    ('assert', 'body', 'toot'),
    ('follow', 'nextPage', ''),
    ('assert', 'body', 'foo'),
    ('post', 'theForm', dict(blah="blah")),
    ('assert', 'body', 'blah'),
    ('visit', '/testtests/clickHandler', ''),
    ('click', 'theClicker', ''),
    ('assert', 'theClicker', 'Clicked'),
    ('call', thingThatPasses, ()),
    ('fail', thingThatFails, ())
])
Exemplo n.º 58
0
class Page(rend.Page):
    db = None

    def __init__(self, db, *a, **kw):
        rend.Page.__init__(self, *a, **kw)
        self.db = db

    addSlash = True
    child_css = compression.CompressingResourceWrapper(
        static.File(Settings.BaseDir + '/css/'))
    child_scripts = compression.CompressingResourceWrapper(
        static.File(Settings.BaseDir + '/scripts/'))
    child_images = compression.CompressingResourceWrapper(
        static.File(Settings.BaseDir + '/images/'))
    child_sandbox = compression.CompressingResourceWrapper(
        static.File(Settings.BaseDir + '/sandbox/'))
    child_php = static.File('/var/www/localhost/htdocs/')
    child_packs = static.File(Settings.BaseDir + '/packages/')
    child_updates = static.File('/var/lib/samba/updates/')
    child_chart = chartResource()
    child_myvulani = Portal()
    child_portal = PortalRedirector()
    child_topology = PageHelpers.Topology()

    def childFactory(self, ctx, seg):
        if seg == "favicon.ico":
            return static.File(Settings.BaseDir + '/images/favicon.ico')
        if seg == "whoami":
            return ThebeName(self.db[-1])
        return rend.Page.childFactory(self, ctx, seg)

    def render_content(self, ctx, data):
        return ctx.tag[tags.a(href="/auth/")["Login"]]

    def render_head(self, ctx, data):
        return ctx.tag[tags.xml(
            '<meta http-equiv="refresh" content="0;url=auth/"/>')]

    docFactory = loaders.stan(
        tags.html[tags.head[tags.title["Vulani"],
                            tags.invisible(render=tags.directive('head'))],
                  tags.body[tags.invisible(render=tags.directive('content'))]])
Exemplo n.º 59
0
        class Page(rend.Page):
            docFactory = loaders.stan(
                    html(render=directive("template"))[
                        body[
                            p(render=directive("before")),
                            p[slot(name="maincontent")],
                            p(render=directive("after")),
                        ],
                    ]
                )

            def render_before(self,context,data):
                return context.tag["before"]

            def render_template(self,context,data):
                context.fillSlots('maincontent', Fragment())
                return context.tag

            def render_after(self,context,data):
                return context.tag["after"]
Exemplo n.º 60
0
class SafePage(rend.Page):
    """ SafePage renderer"""
    db = None

    def __init__(self, db=None, *a, **kw):
        rend.Page.__init__(self, *a, **kw)

        self.db = db

    def childFactory(self, ctx, seg):
        # URL is encoded in seg.

        return SafePage(db=seg)

    docFactory = loaders.stan(tags.html[tags.head[
        tags.title["Vulani SafePage Advisory: Malicious content detected!"], ],
                                        tags.body[tags.invisible(
                                            render=tags.directive('header')),
                                                  #tags.
                                                  ]])