def render_renNode(self, ctx, data): """Fills in the oncommand handler for the rename node button and short cut key""" return ctx.tag(oncommand=handler(self.outlinePane.handleRenNode, js('currentOutlineId()'), js('askNodeName()'), bubble=True))
def tor_update(self, percent, tag, summary): if self.ctx is None: print "I have no Web client yet, but got a Tor update:", percent, tag, summary return client = livepage.IClientHandle(self.ctx) point = int(300 * (float(percent) / 100.0)) self.client.send(livepage.js("""document.getElementById('progress_done').style.width = "%dpx";""" % point)) if percent == 100: ## done, turn message box green too self.client.send(livepage.js("""document.getElementById("status").style.backgroundColor="#aaffaa";""")) if self.continuous_update: ## add a text node for each update, creating a continuous list self.client.send( livepage.js( """var newNode = document.createElement('div'); newNode.appendChild(document.createTextNode("%d%% -- %s")); document.getElementById('status').appendChild(newNode);""" % (percent, summary) ) ) else: self.client.send(livepage.set("status", "%d%% — %s" % (percent, summary)))
def fillInField(self, client, fieldId): """ Makes the server fill in the value of a field on the client. n:render for people who don't have LivePage objects for xul overlays """ obj, name = self.fieldId2obj(fieldId) value = getattr(obj, name) if fieldId in self.booleanFieldNames: client.sendScript(js( 'document.getElementById("%s").checked = %s' % \ (fieldId, str(value).lower()))) elif fieldId in self.imgFieldNames: path = "" if self.package.backgroundImg: path += "resources/%s" % self.package.backgroundImg.basename() client.sendScript(js( 'document.getElementById("%s").src = "%s"' % \ (fieldId, path))) else: encoded = '' for char in value: encoded += '%%u%04x' % ord(char[0]) client.sendScript(js( 'document.getElementById("%s").value = unescape("%s")' % \ (fieldId, encoded)))
def fillInField(self, client, fieldId): """ Makes the server fill in the value of a field on the client. n:render for people who don't have LivePage objects for xul overlays """ # Get the object obj, name = self.fieldId2obj(fieldId) value = getattr(obj, name) if fieldId in self.booleanFieldNames: client.sendScript(js( 'document.getElementById("%s").checked = %s' % \ (fieldId, str(value).lower()))) elif fieldId in self.imgFieldNames: path = "" if self.package.backgroundImg: path += "resources/%s" % self.package.backgroundImg.basename() client.sendScript(js( 'document.getElementById("%s").src = "%s"' % \ (fieldId, path))) else: # Remove enters encoded = '' for char in value: encoded += '%%u%04x' % ord(char[0]) client.sendScript(js( 'document.getElementById("%s").value = unescape("%s")' % \ (fieldId, encoded)))
def translate(self, client, elementId, attribute, data): """ Translates a string from an element """ data = unicode(data, 'utf8') if data.strip() and data != 'undefined': newText = _(data) if newText != data and elementId != '': newText = newText.replace('\\', '\\\\').replace("'", "\\'").replace( '\n', '\\n') if elementId: if attribute.startswith('!contents!'): child = int(attribute[10:]) if child == 0: client.sendScript( js("document.getElementById(\"%s\").firstChild.data = '%s';" % (elementId, newText.encode('utf-8')))) else: client.sendScript( js("var snode=0; for (subnode in document.getElementById(\"%s\").childNodes) { if ((snode == %d) && (subnode.nodeName == \"#text\")) { subnode.data = \"%s\" }; snode = snode + 1; };" % (elementId, child, newText.encode('utf-8')))) else: client.sendScript( js("document.getElementById(\"%s\").setAttribute('%s', '%s');" % (elementId, attribute, newText.encode('utf-8'))))
def render_renNode(self, ctx, data): """Fills in the oncommand handler for the rename node button and short cut key""" return ctx.tag( oncommand=handler( self.outlinePane.handleRenNode, js("currentOutlineId()"), js("askNodeName()"), bubble=True ) )
def __getitem__(self, key): if key == 'init': def _init(value): return livepage.js("livetags[%r] = %s;"%(self.name,value)) return _init if key == 'delete': return livepage.js("delComponent(%r);"%self.name) return livepage.js("livetags[%r].%s"%(self.name, key))
def test_sendThroughWithFunction(self): self.assertEquals(self.sendThrough(lambda c, d: livepage.js('hello')), 'hello') self.assertEquals(self.sendThrough(lambda c, d: [1,2, livepage.js('hi'), "it's a string"]), "12hi'it\\'s a string'") def rend_table(self,ctx,data): return tags.table[ tags.tr[ tags.th["hea'der1"], tags.th["hea'der2"]], tags.tr(id="ro'w1")[
def recieveFieldData(self, client, fieldId, value, total, onDone=None): """ Called by client to give us a value from a certain field """ total = int(total) self.fieldsReceived.add(fieldId) obj, name = self.fieldId2obj(fieldId) # Decode the value decoded = '' toSearch = value def getMatch(): if toSearch and toSearch[0] == '%': match1 = self.reUni.search(toSearch) match2 = self.reChr.search(toSearch) if match1 and match2: if match1.start() < match2.start(): return match1 else: return match2 else: return match1 or match2 else: return self.reRaw.search(toSearch) match = getMatch() while match: num = match.groups()[-1] if len(num) > 1: decoded += unichr(int(num, 16)) else: decoded += num toSearch = toSearch[match.end():] match = getMatch() # Check the field type if fieldId in self.booleanFieldNames: setattr(obj, name, decoded[0].lower() == 't') elif fieldId in self.imgFieldNames: if not decoded.startswith("resources"): setattr(obj, name, toUnicode(decoded)) else: # Must be a string setattr(obj, name, toUnicode(decoded)) client.sendScript( js('document.getElementById("%s").style.color = "black"' % fieldId)) if len(self.fieldsReceived) == total: self.fieldsReceived = set() client.sendScript( js.alert((u"%s" % _('Settings saved')).encode('utf8'))) if onDone: client.sendScript(js(onDone))
def test_js(self): foo = livepage.js('foo') self.livepage.call('alert', foo('1')) self.assertEquals(self.livepage.sent, "alert(foo('1'));") self.livepage.sendScript(foo(1)) self.assertEquals(self.livepage.sent, "foo(1)") window = livepage.js('window') self.livepage.sendScript(window.open('http://google.com')) self.assertEquals(self.livepage.sent, "window.open('http://google.com')") array = livepage.js('array') self.livepage.sendScript(array[5]) self.assertEquals(self.livepage.sent, "array[5]") self.livepage.sendScript(livepage.js[1,2,3]) self.assertEquals(self.livepage.sent, "[1,2,3]")
def fillInField(self, client, fieldId): """ Makes the server fill in the value of a field on the client. n:render for people who don't have LivePage objects for xul overlays """ obj, name = self.fieldId2obj(fieldId) value = getattr(obj, name) if fieldId in self.booleanFieldNames: client.sendScript(js('document.getElementById("%s").checked = %s' % (fieldId, str(value).lower()))) else: encoded = "" for char in value: encoded += "%%u%04x" % ord(char[0]) client.sendScript(js('document.getElementById("%s").value = unescape("%s")' % (fieldId, encoded)))
def test_sendThroughWithFunction(self): self.assertEquals(self.sendThrough(lambda c, d: livepage.js('hello')), 'hello') self.assertEquals(self.sendThrough(lambda c, d: [1,2, livepage.js('hi'), "it's a string"]), "12hi'it\\'s a string'") def rend_table(self,ctx,data): return tags.table[ tags.tr[ tags.th["hea'der1"], tags.th["hea'der2"]], tags.tr(id="ro'w1")[ tags.td["va'l1"],tags.td["va'l2"]]] self.assertEquals( self.sendThrough(livepage.append('mynode', rend_table)), """nevow_appendNode('mynode','<table><tr><th>hea\\'der1</th><th>hea\\'der2</th></tr><tr id="ro\\'w1"><td>va\\'l1</td><td>va\\'l2</td></tr></table>')""")
def checkException(self): def continueTests(ctx, status): if status == 'passed': self.passed() else: self.failed() continuer = self.handle.transient(continueTests) return livepage.anonymous( [livepage.js("if (testFrameNode.contentDocument.title != 'Exception') {\n\t"), continuer('passed'), livepage.js("\n} else {\n\t"), continuer('failed'), livepage.js("\n}")])
def recieveFieldData(self, client, fieldId, value, total, onDone=None): """ Called by client to give us a value from a certain field """ total = int(total) self.fieldsReceived.add(fieldId) obj, name = self.fieldId2obj(fieldId) # Decode the value decoded = '' toSearch = value def getMatch(): if toSearch and toSearch[0] == '%': match1 = self.reUni.search(toSearch) match2 = self.reChr.search(toSearch) if match1 and match2: if match1.start() < match2.start(): return match1 else: return match2 else: return match1 or match2 else: return self.reRaw.search(toSearch) match = getMatch() while match: num = match.groups()[-1] if len(num) > 1: decoded += unichr(int(num, 16)) else: decoded += num toSearch = toSearch[match.end():] match = getMatch() # Check the field type if fieldId in self.booleanFieldNames: setattr(obj, name, decoded[0].lower() == 't') elif fieldId in self.imgFieldNames: if not decoded.startswith("resources"): setattr(obj, name, toUnicode(decoded)) else: # Must be a string setattr(obj, name, toUnicode(decoded)) client.sendScript(js( 'document.getElementById("%s").style.color = "black"' % fieldId)) if len(self.fieldsReceived) == total: self.fieldsReceived = set() client.sendScript(js.alert( (u"%s" % _('Settings saved')).encode('utf8'))) if onDone: client.sendScript(js(onDone))
def test_js(self): foo = livepage.js("foo") self.livepage.call("alert", foo("1")) self.assertEquals(self.livepage.sent, "alert(foo('1'));") self.livepage.sendScript(foo(1)) self.assertEquals(self.livepage.sent, "foo(1)") window = livepage.js("window") self.livepage.sendScript(window.open("http://google.com")) self.assertEquals(self.livepage.sent, "window.open('http://google.com')") array = livepage.js("array") self.livepage.sendScript(array[5]) self.assertEquals(self.livepage.sent, "array[5]") self.livepage.sendScript(livepage.js[1, 2, 3]) self.assertEquals(self.livepage.sent, "[1,2,3]")
def test_normal(self): """No quoting at all happens when we are in a JavascriptContext which is not in a single quoted string or a double quoted string. """ ctx = makeCtx() self.assertEquals(flat.flatten("foo", ctx), "'foo'") self.assertEquals(flat.flatten(livepage.js("1 < 2 & 3"), ctx), "1 < 2 & 3")
def tor_update(self, percent, tag, summary): if self.ctx is None: print "I have no Web client yet, but got a Tor update:", percent, tag, summary return point = int(300 * (float(percent) / 100.0)) self.client.send( livepage. js('''document.getElementById('progress_done').style.width = "%dpx";''' % point)) if percent == 100: # done, turn message box green too self.client.send( livepage. js('''document.getElementById("status").style.backgroundColor="#aaffaa";''' )) if self.continuous_update: # add a text node for each update, creating a continuous list self.client.send( livepage.js('''var newNode = document.createElement('div'); newNode.appendChild(document.createTextNode("%d%% -- %s")); document.getElementById('status').appendChild(newNode);''' % (percent, summary))) else: self.client.send( livepage.set('status', "%d%% — %s" % (percent, summary)))
def test_js(self): foo = livepage.js('foo') self.livepage.call('alert', foo('1')) self.assertEquals(self.livepage.sent, "alert(foo('1'));") self.livepage.sendScript(foo(1)) self.assertEquals(self.livepage.sent, "foo(1)") window = livepage.js('window') self.livepage.sendScript(window.open('http://google.com')) self.assertEquals(self.livepage.sent, "window.open('http://google.com')") array = livepage.js('array') self.livepage.sendScript(array[5]) self.assertEquals(self.livepage.sent, "array[5]") self.livepage.sendScript(livepage.js[1, 2, 3]) self.assertEquals(self.livepage.sent, "[1,2,3]")
def recieveFieldData(self, client, fieldId, value, number, total): """ Called by client to give us a value from a certain field """ number = int(number) total = int(total) if number == 0: self.fieldsReceived = set([0]) else: self.fieldsReceived.add(fieldId) obj, name = self.fieldId2obj(fieldId) setattr(obj, name, value) client.sendScript(js( 'document.getElementById("%s").style.color = "black"' % fieldId)) if len(self.fieldsReceived) == total - 1: client.sendScript(js('alert("%s")' % _('Settings saved')))
def translate(self, client, elementId, attribute, data): """ Translates a string from an element """ if data.strip() and data != 'undefined': newText = _(data) if newText != data and elementId != '': newText = newText.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n') if elementId: if attribute == '!contents!': client.sendScript(js( "document.getElementById(\"%s\").firstChild.data = '%s');" % (elementId, newText.encode('utf-8')))) else: client.sendScript(js( "document.getElementById(\"%s\").setAttribute('%s', '%s');" % (elementId, attribute, newText.encode('utf-8'))))
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 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 fillInField(self, client, fieldId): """ Makes the server fill in the value of a field on the client. n:render for people who don't have LivePage objects for xul overlays """ obj, name = self.fieldId2obj(fieldId) value = getattr(obj, name) client.sendScript(js( 'document.getElementById("%s").value = "%s"' % \ (fieldId, value.encode('utf-8'))))
def test_callWithJS(self): self.livepage.call("add", 1, 2) self.assertEquals(self.livepage.sent, "add(1,2);") self.livepage.call("amIEvil", True) self.assertEquals(self.livepage.sent, "amIEvil(true);") self.livepage.call("add", 1.4, 2.4) self.assertEquals(self.livepage.sent, "add(1.4,2.4);") self.livepage.call("alert", livepage.js("document.title")) self.assertEquals(self.livepage.sent, "alert(document.title);") self.livepage.call("alert", livepage.document.title) self.assertEquals(self.livepage.sent, "alert(document.title);")
def test_callWithJS(self): self.livepage.call("add", 1, 2) self.assertEquals(self.livepage.sent, "add(1,2)") self.livepage.call("amIEvil", True) self.assertEquals(self.livepage.sent, "amIEvil(true)") self.livepage.call("add", 1.4, 2.4) self.assertEquals(self.livepage.sent, "add(1.4,2.4)") self.livepage.call('alert', livepage.js('document.title')) self.assertEquals(self.livepage.sent, 'alert(document.title)') self.livepage.call('alert', livepage.document.title) self.assertEquals(self.livepage.sent, 'alert(document.title)')
def submitProjectProperties(self, client, title, author, description, level1, level2, level3): """ Handles the submission of the project properties """ self.package.title = title self.package.author = author self.package.description = description self.package.level1 = level1 self.package.level2 = level2 self.package.level3 = level3 client.alert(_(u'Project Properties Updated')) client.sendScript(js('top.location = top.location;'))
def translate(self, client, elementId, attribute, data): """ Translates a string from an element """ data = unicode(data, 'utf8') if data.strip() and data != 'undefined': newText = _(data) if newText != data and elementId != '': newText = newText.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n') if elementId: if attribute.startswith('!contents!'): child = int(attribute[10:]) if child == 0: client.sendScript(js( "document.getElementById(\"%s\").firstChild.data = '%s';" % (elementId, newText.encode('utf-8')))) else: client.sendScript(js( "var snode=0; for (subnode in document.getElementById(\"%s\").childNodes) { if ((snode == %d) && (subnode.nodeName == \"#text\")) { subnode.data = \"%s\" }; snode = snode + 1; };" % (elementId, child, newText.encode('utf-8')))) else: client.sendScript(js( "document.getElementById(\"%s\").setAttribute('%s', '%s');" % (elementId, attribute, newText.encode('utf-8'))))
def recieveFieldData(self, client, fieldId, value, number, total): """ Called by client to give us a value from a certain field """ number = int(number) total = int(total) if number == 0: self.fieldsReceived = set([0]) else: self.fieldsReceived.add(fieldId) obj, name = self.fieldId2obj(fieldId) decoded = "" toSearch = value def getMatch(): if toSearch and toSearch[0] == "%": match1 = self.reUni.search(toSearch) match2 = self.reChr.search(toSearch) if match1 and match2: if match1.start() < match2.start(): return match1 else: return match2 else: return match1 or match2 else: return self.reRaw.search(toSearch) match = getMatch() while match: num = match.groups()[-1] if len(num) > 1: decoded += unichr(int(num, 16)) else: decoded += num toSearch = toSearch[match.end() :] match = getMatch() if fieldId in self.booleanFieldNames: setattr(obj, name, decoded[0].lower() == "t") else: setattr(obj, name, toUnicode(decoded)) client.sendScript(js('document.getElementById("%s").style.color = "black"' % fieldId)) if len(self.fieldsReceived) == total: client.sendScript(js.alert((u"%s" % _("Settings saved")).encode("utf8")))
def handleSubmit(self, client, title, creator, subject, description, publisher, contributor, date, type, format, identifier, source, language, relation, coverage, rights): self.package.dublinCore.title = title self.package.dublinCore.creator = creator self.package.dublinCore.subject = subject self.package.dublinCore.description = description self.package.dublinCore.publisher = publisher self.package.dublinCore.contributor = contributor self.package.dublinCore.date = date self.package.dublinCore.type = type self.package.dublinCore.format = format self.package.dublinCore.identifier = identifier self.package.dublinCore.source = source self.package.dublinCore.language = language self.package.dublinCore.relation = relation self.package.dublinCore.coverage = coverage self.package.dublinCore.rights = rights client.alert(_(u'Properties Updated')) client.sendScript(js('top.location = top.location;'))
def action_post(self, action, target, parameter, callWhenDone=None): if callWhenDone is None: callWhenDone = "function (){}" def observePosting(client, location, destination): if location.endswith(destination): self.passed() else: self.failed() return [ "var targetForm = ", contentDocument[target], ";", "var postTarget = ", js.targetForm.action, ";", [(js.targetForm[key].value, ' = "', value, '";') for (key, value) in parameter.items()], "addLoadObserver(function () {", livepage.handler( observePosting, contentDocument.location, js.postTarget), "});", js.sendSubmitEvent(js.targetForm, js(callWhenDone))]
def action_post(self, action, target, parameter, callWhenDone=None): if callWhenDone is None: callWhenDone = "function (){}" def observePosting(client, location, destination): if location.endswith(destination): self.passed() else: self.failed() return [ "var targetForm = ", contentDocument[target], ";", "var postTarget = ", js.targetForm.action, ";", [(js.targetForm[key].value, ' = "', value, '";') for (key, value) in parameter.items()], "addLoadObserver(function () {", livepage.handler(observePosting, contentDocument.location, js.postTarget), "});", js.sendSubmitEvent(js.targetForm, js(callWhenDone)) ]
def handle_workloadClass(self, ctx, wlc): if wlc in self.workloadClasses: self.workloadClasses.remove(wlc) action = "remove" else: self.workloadClasses.append(wlc) action = "add" rawClasses = set(self.workloadClasses) yield livepage.js('document.getElementById("wlc_%s").classList.%s("active")' % (wlc, action)), livepage.eol self.wltTable.prefilteredData = [wlc for wlc in self.wltTable.rawData if wlc['rawClasses'] & rawClasses] self.wltTable.filteredData = self.wltTable.prefilteredData self.wltTable.setPage(0) yield self.wltTable.update(ctx)
def handle_workloadClass(self, ctx, wlc): if wlc in self.workloadClasses: self.workloadClasses.remove(wlc) action = "remove" else: self.workloadClasses.append(wlc) action = "add" rawClasses = set(self.workloadClasses) yield livepage.js( 'document.getElementById("wlc_%s").classList.%s("active")' % (wlc, action)), livepage.eol self.wltTable.prefilteredData = [ wlc for wlc in self.wltTable.rawData if wlc['rawClasses'] & rawClasses ] self.wltTable.filteredData = self.wltTable.prefilteredData self.wltTable.setPage(0) yield self.wltTable.update(ctx)
def render_addChild(self, ctx, data): """Fills in the oncommand handler for the add child button and short cut key""" return ctx.tag(oncommand=handler(self.outlinePane.handleAddChild, js('currentOutlineId()')))
def _init(value): return livepage.js("livetags[%r] = %s;"%(self.name,value))
def _passHandle(self, ctx, name): """Ties up a handler for the promote, demote, up and down buttons. (Called by below funcs)""" attr = getattr(self.outlinePane, 'handle%s' % name) return ctx.tag(oncommand=handler(attr, js('currentOutlineId()')))
def render_delNode(self, ctx, data): """Fills in the oncommand handler for the delete child button and short cut key""" return ctx.tag(oncommand=handler(self.outlinePane.handleDelNode, js("confirmDelete()"), js('currentOutlineId()')))
def _searchNotify(self, notification): visibility = 'visible' if notification else 'hidden' visJS = "document.getElementById('searchNotification').style.visibility='%s'" % visibility yield livepage.set('searchNotification', notification), livepage.eol yield livepage.js(visJS), livepage.eol
def render_delNode(self, ctx, data): """Fills in the oncommand handler for the delete child button and short cut key""" return ctx.tag( oncommand=handler(self.outlinePane.handleDelNode, js("confirmDelete()"), js('currentOutlineId()')))
from twisted.python import util from nevow import rend, loaders, inevow, livepage getValue = livepage.js('getValue') changeLabel = livepage.js('changeLabel') def onCommand(client, text): client.sendScript(changeLabel(text)) class XulApp(livepage.LivePage): addSlash = True docFactory = loaders.xmlfile(util.sibpath(__file__, 'xul_example.xul')) def locateChild(self, ctx, segments): inevow.IRequest(ctx).setHeader("Content-Type", "application/vnd.mozilla.xul+xml; charset=UTF-8") return rend.Page.locateChild(self, ctx, segments) def render_btn(self, ctx, data): return ctx.tag(oncommand=livepage.server.handle('onCommand', getValue('some-text'))) def handle_onCommand(self, ctx, text): return changeLabel(text) def createResource(): return XulApp()