#!bin/python """ now launches like this: % bin/curvecalc http://light9.bigasterisk.com/show/dance2007/song1 todo: curveview should preserve more objects, for speed maybe """ from __future__ import division from twisted.internet import gtk2reactor gtk2reactor.install() from twisted.internet import reactor import time, textwrap, os, optparse, urllib2, gtk, gobject, linecache import louie as dispatcher from twisted.python.util import sibpath from rdflib import URIRef from rdflib import Graph import rdflib import logging log = logging.getLogger() import run_local from light9 import showconfig, prof from light9.curvecalc.zoomcontrol import Zoomcontrol from light9.curvecalc.curve import Curveset from light9.curvecalc import curveview from light9.curvecalc.musicaccess import Music, currentlyPlayingSong from light9.wavelength import wavelength from light9.uihelpers import toplevelat from light9.namespaces import L9 from light9.curvecalc.subterm import read_all_subs, savekey, graphPathForSubterms from light9.curvecalc.subtermview import add_one_subterm from light9.curvecalc.output import Output def makeGraph(): graphOrig = showconfig.getGraph() graph = Graph() # a copy, since we're going to add subs into it for s in graphOrig: graph.add(s) read_all_subs(graph) return graph class Main(object): def __init__(self, graph, opts, song, curveset, subterms, music): self.graph = graph self.music = music wtree = gtk.Builder() wtree.add_from_file(sibpath(__file__, "../light9/curvecalc/curvecalc.glade")) mainwin = wtree.get_object("MainWindow") mainwin.connect("destroy", gtk.main_quit) wtree.connect_signals(self) mainwin.show_all() mainwin.connect("delete-event", lambda *args: reactor.crash()) mainwin.set_title("curvecalc - %s" % graph.label(song)) self.add_subterms_for_song(song, curveset, subterms, wtree.get_object("subterms") ) def refreshCurveView(): m = os.path.getmtime(curveview.__file__.replace('.pyc', '.py')) if not hasattr(self, 'curvesetView') or self.curvesetView._mtime != m: print "reload curveview.py" curvesVBox = wtree.get_object("curves") [curvesVBox.remove(c) for c in curvesVBox.get_children()] try: linecache.clearcache() reload(curveview) # mem problem somewhere; need to hold a ref to this self.curvesetView = curveview.Curvesetview( curvesVBox, curveset) self.curvesetView._mtime = m # curvesetview must already exist, since this # makes 'add_curve' signals for all the initial # curves curveset.load(basename=os.path.join( showconfig.curvesDir(), showconfig.songFilenameFromURI(song)), skipMusic=opts.skip_music) # this is scheduled after some tk shuffling, to # try to minimize the number of times we redraw # the curve at startup. If tk is very slow, it's # ok. You'll just get some wasted redraws. self.curvesetView.goLive() except Exception, e: print "reload failed:", e reactor.callLater(1, refreshCurveView) refreshCurveView() self.makeStatusLines(wtree.get_object("status")) #zc = Zoomcontrol(root) def onPlayPause(self, item): # since the X coord in a curveview affects the handling, one # of them may be able to pick this up results = dispatcher.send("onPlayPause") times = [t for listener, t in results if t is not None] self.music.playOrPause(t=times[0] if times else None) def onSave(self, *args): savekey(song, subterms, curveset) def add_subterms_for_song(self, song, curveset, subterms, master): for st in self.graph.objects(song, L9['subterm']): log.info("song %s has subterm %s", song, st) add_one_subterm(self.graph, self.graph.value(st, L9['sub']), curveset, subterms, master, self.graph.value(st, L9['expression'])) master.show_all() def makeStatusLines(self, master): """various labels that listen for dispatcher signals""" for row, (signame, textfilter) in enumerate([ ('input time', lambda t: "%.2fs"%t), ('output levels', lambda levels: textwrap.fill("; ".join(["%s:%.2f"%(n,v) for n,v in levels.items()[:5] if v>0]),70)), ('update period', lambda t: "%.1fms"%(t*1000)), ('update status', lambda x: str(x)), ]): key = gtk.Label("%s:" % signame) value = gtk.Label("") master.resize(row + 1, 2) master.attach(key, 0, 1, row, row + 1) master.attach(value, 1, 2, row, row + 1) key.set_alignment(1, 0) value.set_alignment(0, 0) dispatcher.connect(lambda val, value=value, tf=textfilter: value.set_text(tf(val)), signame, weak=False) master.show_all() def onReloadSubs(self): # wants to be ctrl-r too dispatcher.send('reload all subs') def onAddSubterm(self): uri = L9['sub/%s' % newname.get()] graph.add((uri, RDF.type, L9.Subterm)) graph.add((uri, RDFS.label, Literal(newname.get()))) add_one_subterm(graph, uri, curveset, subterms, ssv, None) if evt.state & 4: # control key modifier curveset.new_curve(newname.get()) newname.set('') def main(): startTime = time.time() parser = optparse.OptionParser() parser.set_usage("%prog [opts] [songURI]") parser.add_option("--sliders", action='store_true', help='use hardware sliders') parser.add_option("--skip-music", action='store_true', help="ignore music and smooth_music curve files") parser.add_option("--debug", action="store_true", help="log at DEBUG") parser.add_option("--startup-only", action='store_true', help="quit after loading everything (for timing tests)") opts, args = parser.parse_args() logging.basicConfig(format="%(asctime)s %(levelname)-5s %(name)s %(filename)s:%(lineno)d: %(message)s") log.setLevel(logging.DEBUG if opts.debug else logging.INFO) log.debug("startup: music %s", time.time() - startTime) try: song = URIRef(args[0]) except IndexError: song = currentlyPlayingSong() music=Music() graph = makeGraph() curveset = Curveset(sliders=opts.sliders) subterms = [] subtermPath = graphPathForSubterms(song) try: graph.parse(subtermPath, format='n3') except urllib2.URLError, e: if e.reason.errno != 2: raise log.info("%s not found, starting with empty graph" % subtermPath) log.debug("startup: output %s", time.time() - startTime) out = Output(subterms, music) musicfilename = showconfig.songOnDisk(song) maxtime = wavelength(musicfilename) dispatcher.connect(lambda: maxtime, "get max time", weak=False) start = Main(graph, opts, song, curveset, subterms, music) dispatcher.send("max time", maxtime=maxtime) dispatcher.send("show all") if opts.startup_only: log.debug("quitting now because of --startup-only") return reactor.run() main()