def getData(self, ctx): rows = [] for cmdN3, d in [ ('cmd:BabyKick', { 'label': 'kick', 'marker': T.raw('⬖') }), ('cmd:BabyStart', { 'label': 'start', 'marker': T.raw('+') }), ('cmd:BabyStop', { 'label': 'stop', 'marker': T.raw('-') }), ]: for row in self.graph.queryd(""" SELECT DISTINCT ?t WHERE { [ cl:command %s; dcterms:created ?t ; a cl:IssuedCommand ] } ORDER BY ?t""" % cmdN3): t = time.mktime(parse(row['t']).timetuple()) rows.append((t, None, d)) print "found rows", rows return stripchart.Events(rows)
def render_tempSection(self, ctx, data): try: temps = dict.fromkeys(["ariBedroom", "downstairs", "livingRoom", "bedroom", "KSQL"]) temps.update(getAllTemps()) return T.raw(render.tempsection(temps=temps)) except Exception, e: return T.div["Error creating temperature graph: %s" % e]
class WebInterface(athena.LivePage): docFactory = loaders.stan([tags.raw(xhtml_header), tags.html(xmlns="http://www.w3.org/1999/xhtml")[ tags.head(render=tags.directive('liveglue')), tags.body[ tags.div[ tags.div( render = tags.directive( "MainPage" )) ]]]]) MainPage = MainPage() PLCHMI = PLCHMI def __init__(self, plcState=False, *a, **kw): super(WebInterface, self).__init__(*a, **kw) self.jsModules.mapping[u'WebInterface'] = util.sibpath(__file__, 'webinterface.js') self.plcState = plcState self.MainPage.setPLCState(plcState) def getHMI(self): return self.MainPage.getHMI() def LoadHMI(self, hmi, jsmodules): for name, path in jsmodules.iteritems(): self.jsModules.mapping[name] = os.path.join(WorkingDir, path) self.MainPage.setPLCStartedHMI(hmi) def UnLoadHMI(self): self.MainPage.resetPLCStartedHMI() def PLCStarted(self): self.plcState = True self.MainPage.setPLCState(True) def PLCStopped(self): self.plcState = False self.MainPage.setPLCState(False) def renderHTTP(self, ctx): """ Force content type to fit with SVG """ req = inevow.IRequest(ctx) req.setHeader('Content-type', 'application/xhtml+xml') return super(WebInterface, self).renderHTTP(ctx) def render_MainPage(self, ctx, data): f = self.MainPage f.setFragmentParent(self) return ctx.tag[f] def child_(self, ctx): self.MainPage.detachFragmentChildren() return WebInterface(plcState=self.plcState) def beforeRender(self, ctx): d = self.notifyOnDisconnect() d.addErrback(self.disconnected) def disconnected(self, reason): self.MainPage.resetHMI()
def render_pics(self, ctx, data): rows = [] d = URIRef(ctx.arg('dir')) for i, (pic, filename) in enumerate(sorted(picsInDirectory(self.graph, d))[:]): img = T.img(src=[localSite(pic), '?size=thumb'], # look these up in the graph width=75, height=56, onclick='javascript:photo.showLarge("%s")' % (localSite(pic) + "?size=large")) tableRow = T.table(class_="picRow")[T.tr[ T.td[T.a(href=localSite(pic))[filename]], T.td[img], T.td[ T.div["Depicts: ", T.input(type="text", class_="tags")], T.div["Comment: ", T.input(type="text")], ], ]] toCopy = "protoSectionSplitter" if i ==0: toCopy = "protoSectionBreak" rows.append([T.raw('<script type="text/javascript">document.write(document.getElementById("%s").innerHTML);</script>' % toCopy), tableRow]) return rows
def render_tempSection(self, ctx, data): try: temps = dict.fromkeys( ['ariBedroom', 'downstairs', 'livingRoom', 'bedroom', 'KSQL']) temps.update(getAllTemps()) return T.raw(render.tempsection(temps=temps)) except Exception, e: return T.div["Error creating temperature graph: %s" % e]
def divBar(text, width, fraction, barColor): fraction = min(1, max(0, fraction)) sp = T.raw(" ") return T.div(class_="bar", style="width: %spx;" % width)[ T.div(class_="fill", style="width: %dpx; background: %s" % (width * fraction, barColor))[sp], T.div(class_="txt")[text], sp, ]
def render_liveglue(self, ctx): return [ tags.script(type='text/javascript')[tags.raw(""" var nevow_livepageId = '%s'; """ % self.clientID)], tags.script(type='text/javascript', src=url.here.child("mochikit.js")), tags.script(type='text/javascript', src=url.here.child("athena.js")), ]
def __init__(self, *files): s = "" for f in files: try: s += open(f).read() + '\n' except: print "failed to open file: %s" % f self.docFactory = loaders.stan(tags.raw(s))
def divBar(text, width, fraction, barColor): fraction = min(1, max(0, fraction)) sp = T.raw(' ') return T.div(class_="bar", style="width: %spx;" % width)[T.div(class_="fill", style="width: %dpx; background: %s" % (width * fraction, barColor))[sp], T.div(class_="txt")[text], sp]
def test_attributeRaw(self): """ An instance of L{raw} is flattened with " quoting if C{True} is passed for C{inAttribute}. L{raw} instances are expected to have already had &, <, and > quoted. L{raw} support is primarily for backwards compatibility. """ self.assertStringEqual("".join(flatten(None, raw('"&<>'), True, True)), '"&<>')
def test_attributeRaw(self): """ An instance of L{raw} is flattened with " quoting if C{True} is passed for C{inAttribute}. L{raw} instances are expected to have already had &, <, and > quoted. L{raw} support is primarily for backwards compatibility. """ self.assertStringEqual( "".join(flatten(None, raw('"&<>'), True, True)), '"&<>')
def getImportStan(self, moduleName): var = '' if '.' not in moduleName: var = 'var ' moduleDef = '%s%s = {};' % (var, moduleName) return [ tags.script(type='text/javascript')[tags.raw(moduleDef)], tags.script(type='text/javascript', src=self.getJSModuleURL(moduleName)) ]
def iterflatten(stan, ctx, writer, shouldYieldItem=None): """This is the main meat of the nevow renderer. End-user programmers should instead use either flatten or precompile. """ # 'rest' is a list of generators. # initialize as one-element list of a one-element generator of rest = [ iter([partialflatten(ctx, stan)]) ] straccum = [] while rest: gen = rest.pop() for item in gen: if isinstance(item, bytes): straccum.append(item) elif isinstance(item, str): straccum.append(item.encode('utf8')) elif isinstance(item, (list, types.GeneratorType)): # stop iterating this generator and put it back on the stack # and start iterating the new item instead. rest.append(gen) rest.append(iter(item)) break else: if straccum: writer(util.toBytes(tags.raw(b''.join(straccum)))) straccum=[] if shouldYieldItem is not None and shouldYieldItem(item): replacement = [] yield item, replacement.append rest.append(gen) rest.append(iter([replacement])) break else: if ctx.precompile: ## We're precompiling and this is an item which can't be calculated until render time ## add it to the list in 'precompile' writer(item) else: rest.append(gen) rest.append(iter([partialflatten(ctx, item)])) break if straccum: writer(tags.raw(b''.join([i for i in straccum])))
def iterflatten(stan, ctx, writer, shouldYieldItem=None): """This is the main meat of the nevow renderer. End-user programmers should instead use either flatten or precompile. """ # 'rest' is a list of generators. # initialize as one-element list of a one-element generator of rest = [iter([partialflatten(ctx, stan)])] straccum = [] while rest: gen = rest.pop() for item in gen: if isinstance(item, str): straccum.append(item) elif isinstance(item, unicode): straccum.append(item.encode('utf8')) elif isinstance(item, (list, types.GeneratorType)): # stop iterating this generator and put it back on the stack # and start iterating the new item instead. rest.append(gen) rest.append(iter(item)) break else: if straccum: writer(tags.raw(''.join(straccum))) del straccum[:] if shouldYieldItem is not None and shouldYieldItem(item): replacement = [] yield item, replacement.append rest.append(gen) rest.append(iter([replacement])) break else: if ctx.precompile: ## We're precompiling and this is an item which can't be calculated until render time ## add it to the list in 'precompile' writer(item) else: rest.append(gen) rest.append(iter([partialflatten(ctx, item)])) break if straccum: writer(tags.raw(''.join(straccum)))
def render(self): defs = [] elements = [] for maker in [ self.makeSpeedGrid, self.makePosGrid, self.makeSpeedCurves, self.makeDirections, ]: d, e = maker() defs.extend(d) elements.append(T.Tag('g')[e]) return flat.flatten(T.Tag('svg')(xmlns="http://www.w3.org/2000/svg", style="background: #ddd;", width=self.width, height=self.height, **{'xmlns:xlink':"http://www.w3.org/1999/xlink"})[ T.Tag('style')[T.raw(self.style)], T.Tag('defs')[defs, T.raw(self.staticDefs)], elements])
def flatten(stan, ctx=None): """Given the stan and the optional context, return a string containing the representation of the tree in the given context. """ if ctx is None: from nevow.context import RequestContext, PageContext ctx = PageContext(tag=None, parent=RequestContext(tag=testutil.FakeRequest())) ctx.remember(None, inevow.IData) result = [] list(iterflatten(stan, ctx, result.append)) return tags.raw(''.join(result))
def render_pastebin(self, ctx, data): p = lambda s: ctx.tag.onePattern(s)() ctx.tag.fillSlots('sheetTemplate', CHARSHEET_T) if self.doc is not None: displayDoc = p("displayDoc") displayDoc.fillSlots('displayDoc', T.raw(self.body.encode('utf-8'))) return ctx.tag[p("miniTitle"), p("form"), displayDoc] else: return ctx.tag[p("mainTitle"), p("form")]
def flatten(stan, ctx=None): """Given the stan and the optional context, return a string containing the representation of the tree in the given context. """ if ctx is None: from nevow.context import RequestContext, PageContext from nevow.testutil import FakeRequest ctx = PageContext(tag=None, parent=RequestContext(tag=FakeRequest())) ctx.remember(None, inevow.IData) result = [] list(iterflatten(stan, ctx, result.append)) return tags.raw(''.join(result))
def mapHtml(): width = 600 height = 900 dots = [] for measurement in UpdatingMeasurements().measurements: try: speed = float(measurement['speed']) except ValueError: print "no speed", measurement continue color = "#%02x%02x%02x" % (interp(speed, 50, 0, 0, 255), interp(speed, 40, 80, 0, 255), 0) pos = (interp(float(measurement['longitude']), -122.72, -121.50, 0, width), interp(float(measurement['latitude']), 38.41, 36.93, 0, height)) dotText = u'\u2739' if random.random() > .9: dotText += ' %d' % speed dots.append( T.div(style="color: %s; position: absolute; left: %spx; top: %spx" % (color, pos[0], pos[1]))[dotText]) page = [T.raw('''<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'''), T.html(xmlns="http://www.w3.org/1999/xhtml")[ T.head[T.style[T.raw(''' * { font-size: 90%; } ''')]], T.body[ T.div(style="width: %spx; height: %spx" % (width, height))[ dots ]]]] return flat.flatten(page)
def getData(self, ctx): rows = [] for cmdN3, d in [ ("cmd:BabyKick", {"label": "kick", "marker": T.raw("⬖")}), ("cmd:BabyStart", {"label": "start", "marker": T.raw("+")}), ("cmd:BabyStop", {"label": "stop", "marker": T.raw("-")}), ]: for row in self.graph.queryd( """ SELECT DISTINCT ?t WHERE { [ cl:command %s; dcterms:created ?t ; a cl:IssuedCommand ] } ORDER BY ?t""" % cmdN3 ): t = time.mktime(parse(row["t"]).timetuple()) rows.append((t, None, d)) print "found rows", rows return stripchart.Events(rows)
def mapHtml(): width = 600 height = 900 dots = [] for measurement in UpdatingMeasurements().measurements: try: speed = float(measurement['speed']) except ValueError: print "no speed", measurement continue color = "#%02x%02x%02x" % (interp( speed, 50, 0, 0, 255), interp(speed, 40, 80, 0, 255), 0) pos = (interp(float(measurement['longitude']), -122.72, -121.50, 0, width), interp(float(measurement['latitude']), 38.41, 36.93, 0, height)) dotText = u'\u2739' if random.random() > .9: dotText += ' %d' % speed dots.append( T.div( style="color: %s; position: absolute; left: %spx; top: %spx" % (color, pos[0], pos[1]))[dotText]) page = [ T.raw('''<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'''), T.html(xmlns="http://www.w3.org/1999/xhtml")[T.head[T.style[T.raw(''' * { font-size: 90%; } ''')]], T.body[T.div(style="width: %spx; height: %spx" % (width, height))[dots]]] ] return flat.flatten(page)
def render(self): defs = [] elements = [] for maker in [ self.makeSpeedGrid, self.makePosGrid, self.makeSpeedCurves, self.makeDirections, ]: d, e = maker() defs.extend(d) elements.append(T.Tag('g')[e]) return flat.flatten( T.Tag('svg')(xmlns="http://www.w3.org/2000/svg", style="background: #ddd;", width=self.width, height=self.height, **{ 'xmlns:xlink': "http://www.w3.org/1999/xlink" })[T.Tag('style')[T.raw(self.style)], T.Tag('defs')[defs, T.raw(self.staticDefs)], elements])
def iterflatten(stan, ctx, writer, shouldYieldItem=None): """This is the main meat of the nevow renderer. End-user programmers should instead use either flatten or precompile. """ rest = [ iter([partialflatten(ctx, stan)]) ] straccum = [] while rest: gen = rest.pop() for item in gen: if isinstance(item, str): straccum.append(item) elif isinstance(item, unicode): straccum.append(item.encode('utf8')) elif isinstance(item, (list, types.GeneratorType)): rest.append(gen) rest.append(iter(item)) break else: if straccum: writer(tags.raw(''.join(straccum))) del straccum[:] if shouldYieldItem is not None and shouldYieldItem(item): replacement = [] yield item, replacement.append rest.append(gen) rest.append(iter([replacement])) break else: if ctx.precompile: writer(item) else: rest.append(gen) rest.append(iter([partialflatten(ctx, item)])) break if straccum: writer(tags.raw(''.join(straccum)))
def render_liveglue(self, ctx, data): return ctx.tag[ # Hit jsDeps.getModuleForName to force it to load some plugins :/ # This really needs to be redesigned. [ self.getImportStan(jsDeps.getModuleForName(name).name) for name in self.BOOTSTRAP_MODULES ], tags.script(type='text/javascript')[tags.raw( """ Divmod._location = '%(baseURL)s'; Nevow.Athena.livepageId = '%(clientID)s'; """ % { 'clientID': self.clientID, 'baseURL': flat.flatten(self.transportRoot, ctx) })]]
def render_followup_uri(self, ctx, data): request = inevow.IRequest(ctx) if request.args.has_key('followupuri'): followup = '"%s"' % request.args['followupuri'][0] else: followup = 'null' if request.args.has_key('quick'): quick = '1' else: quick = '0' tmp = 'activation_followup_uri = %s;\n' % followup tmp += 'activation_is_quick = %s;\n' % quick str = textwrap.dedent(""" // <![CDATA[ %s // ]]> """) % tmp # raw string required for JS CDATA hack ctx.tag[T.raw(str)] return ctx.tag
errs = [e.__class__.__name__ + ': ' + str(e)] if errs: reportErrors(source, errs) return boringDocstring(doc, summary), errs pdoc, fields = pdoc.split_fields() if pdoc is not None: try: crap = de_p( pdoc.to_html(_EpydocLinker(getattr(obj, 'docsource', obj)))) except Exception, e: reportErrors(source, [e.__class__.__name__ + ': ' + str(e)]) return (boringDocstring(doc, summary), [e.__class__.__name__ + ': ' + str(e)]) else: crap = '' if isinstance(crap, unicode): crap = crap.encode('utf-8') if summary: if not crap: return (), [] s = tags.span()[tags.raw(crap)] else: if not crap and not fields: return (), [] s = tags.div()[tags.raw(crap)] fh = FieldHandler(obj) for field in fields: fh.handle(Field(field, obj)) s[fh.format()] return s, []
def test_raw(self): """ An instance of L{raw} is flattened to itself. """ self.assertStringEqual( self.flatten(raw('bytes<>^&"\0')), 'bytes<>^&"\0')
new = JavascriptContext(ctx, tags.invisible[theJS]) return flat.serialize(theJS._children, new) flat.registerFlattener(flattenJS, _js) js = _js() document = _js('document') get = document.getElementById window = _js('window') this = _js('this') self = _js('self') server = _js('server') alert = _js('alert') stop = _js('; return false;') eol = tags.raw('\n') set = js.nevow_setNode append = js.nevow_appendNode prepend = js.nevow_prependNode insert = js.nevow_insertNode def assign(where, what): """Assign what to where. Equivalent to where = what; """ return _js([where, stan.raw(" = "), what]) setq = assign # hee
class BabyTable(rend.Page): addSlash = True docFactory = loaders.stan(T.html[T.head[ T.title["Baby event table"], T.style(type="text/css")[T.raw(''' body { width: 1000px; font-family: sans-serif; color: #333; } table { border-collapse: collapse; } td { white-space: nowrap; padding: 0 3px; } div.bar { position: relative; background: #eee; } div.bar .fill { position:absolute; } div.bar .txt { position:absolute; } ''')], T. meta(name="viewport", content= "width=500; initial-scale=1.0; minimum-scale: .01; user-scalable=yes" ), ], T.body[T.h1['Baby events'], T.directive('table')]]) def __init__(self, graph): self.graph = graph rend.Page.__init__(self) def render_table(self, ctx, data): rows = [] for row in self.graph.queryd(""" SELECT DISTINCT ?cmd ?t WHERE { { ?iss cl:command cmd:BabyStart . } UNION { ?iss cl:command cmd:BabyStop . } ?iss dcterms:created ?t ; cl:command ?cmd ; a cl:IssuedCommand . FILTER ( ?t > "2009-07-25T00:00:00Z"^^xs:dateTime ) } ORDER BY ?t"""): t = time.mktime(parse(row['t']).timetuple()) rows.append((t, row['cmd'], row['t'])) label = {CMD.BabyStart: 'start', CMD.BabyStop: 'stop'} def cleanTime(isot): m = re.match(r"^(....-..-..)T(..:..:..)", isot) return "%s %s" % (m.group(1), m.group(2)) def prettyElapsed(sec): return "%.1f min" % (sec / 60) trs = [] lastStart = None lastStop = None for row in rows: t, cmd, isot = row if cmd == CMD.BabyStart: if lastStart is not None: period = t - lastStart[0] cols = [ T.td[cleanTime(isot)], T.td[divBar("%s since prev" % prettyElapsed(period), 200, period / 600, "#f88")], ] if lastStop is not None: dur = lastStop[0] - lastStart[0] cols.append(T.td[divBar( "duration %s" % prettyElapsed(dur), 150, dur / 200, "#8c3")]) trs.append(T.tr[cols]) lastStart = row lastStop = None if cmd == CMD.BabyStop: lastStop = row return T.table[trs]
def flattenJS(theJS, ctx): new = JavascriptContext(ctx, tags.invisible[theJS]) return flat.serialize(theJS._children, new) flat.registerFlattener(flattenJS, _js) js = _js() document = _js('document') get = document.getElementById window = _js('window') this = _js('this') self = _js('self') server = _js('server') alert = _js('alert') stop = _js('; return false;') eol = tags.raw('\n') set = js.nevow_setNode append = js.nevow_appendNode prepend = js.nevow_prependNode insert = js.nevow_insertNode def assign(where, what): """Assign what to where. Equivalent to where = what; """ return _js([where, stan.raw(" = "), what]) setq = assign # hee
class Main(rend.Page): docFactory = loaders.stan([ T.raw('''<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">'''), T.html(xmlns="http://www.w3.org/1999/xhtml")[T.head[T.style[T.raw(''' * { font-family: sans-serif; } table { border-collapse: collapse; } table, td, th { border: 1px solid gray; padding: 3px; } .timing { margin-top: 1em; border: 1px solid #ccc; width: 30em; } .timing table, .timing td { border: 0; } .credit { margin-top: 1em; border: 1px solid #ccc; padding: .3em; background: #eee; } .dir-N { background: #cfc; } .dir-S { background: #fcf; } ''')]], T.body[ #T.directive('table'), T.directive('hist'), T.directive('timing'), T.div(class_="credit")[T.a(href="http://pems.dot.ca.gov/" )["Data from PeMS, Caltrans"]], ]] ]) def renderHTTP(self, ctx): req = inevow.IRequest(ctx) req.setHeader('Content-type', 'application/xhtml+xml') return rend.Page.renderHTTP(self, ctx) def render_table(self, ctx, data): import segment_report reload(segment_report) return segment_report.table(latestMeas) def render_timing(self, ctx, data): return T.div(class_="timing")[T.table[ T.tr[T.td["Data timestamp says "], T.td[datetime.datetime.fromtimestamp(latestMeas.lastDataTime). isoformat()]], T.tr[T.td["Last fetched at "], T.td[datetime.datetime.fromtimestamp(latestMeas.lastFtpTime). isoformat()]], T.tr[T.td["Page generated at "], T.td[datetime.datetime.fromtimestamp(int(time.time())). isoformat()]], ]] def render_hist(self, ctx, data): import route_history_report reload(route_history_report) D = route_history_report.Diagram shadows = True if ctx.arg('shadow') == 'off': shadows = False return [ T.div[T.h2['Southbound'], D(shadows=shadows, freewayDir='S').render()], T.div[T.h2['Northbound'], D(shadows=shadows, freewayDir='N').render()], T.div[T.a(href="?shadow=off")["(turn off shadows)"]] ]
def test_raw(self): """ An instance of L{raw} is flattened to itself. """ self.assertStringEqual(self.flatten(raw('bytes<>^&"\0')), 'bytes<>^&"\0')
def coder(data): if data: return T.raw(data) return ""
def render_loadtree(self,ctx,data): return T.script(type='text/javascript')[T.raw(""" addLoadEvent(function() { Numbler.apidoc.loadTree('%s'); }); """ % json.serialize(list(self.stripfiles(self.displayTree))))]
except Exception, e: errs = [e.__class__.__name__ +': ' + str(e)] if errs: reportErrors(source, errs) return boringDocstring(doc, summary), errs pdoc, fields = pdoc.split_fields() if pdoc is not None: try: crap = de_p(pdoc.to_html(_EpydocLinker(getattr(obj, 'docsource', obj)))) except Exception, e: reportErrors(source, [e.__class__.__name__ +': ' + str(e)]) return (boringDocstring(doc, summary), [e.__class__.__name__ +': ' + str(e)]) else: crap = '' if isinstance(crap, unicode): crap = crap.encode('utf-8') if summary: if not crap: return (), [] s = tags.span()[tags.raw(crap)] else: if not crap and not fields: return (), [] s = tags.div()[tags.raw(crap)] fh = FieldHandler(obj) for field in fields: fh.handle(Field(field, obj)) s[fh.format()] return s, []
def __init__(self, field, obj): self.tag = field.tag() self.arg = field.arg() self.body = tags.raw(de_p(field.body().to_html(_EpydocLinker(obj))))