view bin/curvecalc @ 901:0dacbba70d06 last-2012

remove some broken profiler attempts Ignore-this: 3d50124a16807ee922e85911d510ce58
author Drew Perttula <drewp@bigasterisk.com>
date Mon, 10 Jun 2013 00:09:17 +0000
parents db265102f7b5
children bca2e8d754aa
line wrap: on
line source

#!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, gtk, linecache, signal, traceback, json
from urlparse import parse_qsl
import louie as dispatcher 
from rdflib import URIRef, Literal, RDF, RDFS
import logging

from run_local import log
from light9 import showconfig, networking
from light9.rdfdb import clientsession
from light9.curvecalc.curve import Curveset
from light9.curvecalc import curveview 
from light9.curvecalc.musicaccess import Music
from light9.wavelength import wavelength
from light9.namespaces import L9
from light9.curvecalc.subterm import Subterm
from light9.curvecalc.subtermview import add_one_subterm
from light9.curvecalc.output import Output
from light9.gtkpyconsole import togglePyConsole
from light9.rdfdb.syncedgraph import SyncedGraph
from light9.rdfdb.patch import Patch
from light9.editchoicegtk import EditChoice
from light9.observable import Observable

class SubtermExists(ValueError):
    pass

class Main(object):
    def __init__(self, graph, opts, session, curveset, music):
        self.graph, self.opts, self.session = graph, opts, session
        self.curveset, self.music = curveset, music
        self.lastSeenInputTime = 0

        wtree = self.wtree = gtk.Builder()
        wtree.add_from_file("light9/curvecalc/curvecalc.glade")
        mainwin = wtree.get_object("MainWindow")
        
        mainwin.connect("destroy", self.onQuit)
        wtree.connect_signals(self)
        gtk.rc_parse("theme/marble-ice/gtk-2.0/gtkrc")
        gtk.rc_parse_string("""style "default" {font_name = "sans 7"}""")
        if self.opts.reload:
            self.refreshTheme()
        mainwin.show_all()

        mainwin.connect("delete-event", lambda *args: reactor.crash())
        def updateTitle():
            mainwin.set_title("curvecalc - %s" %
                              graph.label(
                                  graph.value(session, L9['currentSong'])))
        graph.addHandler(updateTitle)
        mainwin.parse_geometry("1x1-0+0")

        # this is the only one i found that would set the size right,
        # but it's a minimum size, which i don't really want
        mainwin.set_size_request(1678, 922)

        songChoice = Observable(None) # to be connected with the session song

        def setSong():
            songChoice(graph.value(session, L9['currentSong']))
        graph.addHandler(setSong)
        # next here, watch songChoice and patch the graph
        
        ec = EditChoice(graph, songChoice, label="Editing song:")
        wtree.get_object("currentSongEditChoice").add(ec)
        ec.show()
        
        wtree.get_object("subterms").connect("add", self.onSubtermChildAdded)
        

        self.refreshCurveView()       
        
        self.makeStatusLines(wtree.get_object("status"))

        def connect(w):
            w.drag_dest_set(flags=gtk.DEST_DEFAULT_ALL,
                            targets=[('text/uri-list', 0, 0)],
                            actions=gtk.gdk.ACTION_COPY)
            w.connect("drag-data-received", self.onDataReceived)
        #connect(mainwin)
        # that's not enough- deeper windows don't accept the
        # event. 
        #mainwin.forall(connect) # not very effective

        wtree.get_object("newSubZone").drag_dest_set(flags=gtk.DEST_DEFAULT_ALL,
                            targets=[('text/uri-list', 0, 0)],
                            actions=gtk.gdk.ACTION_COPY)
        
        # this probably isn't rerunning often enough to catch new data
        #connect(wtree.get_object("subterms")) # works for that area

        # may not work
        wtree.get_object("paned1").set_position(600)

    def onDataReceived(self, widget, context, x, y, selection,
                       targetType, time):
        data = selection.data.strip()
        if '?' in data:
            self.handleSubtermDrop(data)
            return
        uri = URIRef(data)
        subName = self.graph.label(uri)
        
        try:
            self.makeSubterm(subName, withCurve=True)
        except SubtermExists:
            pass
        curveView = self.curvesetView.row(subName).curveView
        t = self.lastSeenInputTime # curveView.current_time() # new curve hasn't heard the time yet. this has gotten too messy- everyone just needs to be able to reach the time source
        print "time", t
        curveView.add_points([(t - .5, 0),
                              (t, 1)])

    def onDragDataInNewSubZone(self, widget, context, x, y, selection,
                       targetType, time):
        self.makeSubterm(newname="cx", withCurve=True,
                         sub=URIRef(selection.data.strip()))
        
    def handleSubtermDrop(self, data):
        params = parse_qsl(data.split('?')[1])
        flattened = dict(params)
        self.makeSubterm(flattened['subtermName'],
                         expr=flattened['subtermExpr'])

        for cmd, name in params:
            if cmd == 'curve':
                self.curveset.new_curve(name)

    def onNewCurve(self, *args):
        dialog = self.wtree.get_object("newCurve")
        entry = self.wtree.get_object("newCurveName")
        # if you don't have songx, that should be the suggested name
        entry.set_text("")
        if dialog.run() == 1:
            self.curveset.new_curve(entry.get_text())
        dialog.hide()
        
    def onSubtermsMap(self, *args):
        # if this was called too soon, like in __init__, the gtktable
        # would get its children but it wouldn't lay anything out that
        # I can see, and I'm not sure why. Waiting for map event is
        # just a wild guess.
        self.graph.addHandler(self.set_subterms_from_graph)
        
    def onNewSubterm(self, *args):
        dialog = self.wtree.get_object("newSubterm")
        # the plan is to autocomplete this on existing subterm names
        # (but let you make one up, too)
        entry = self.wtree.get_object("newSubtermName").get_children()[0]
        entry.set_text("")
        entry.grab_focus()
        if dialog.run() == 1:
            newname = entry.get_text()
            wc = self.wtree.get_object("newSubtermMakeCurve").get_active()
            self.makeSubterm(newname, withCurve=wc)
        dialog.hide()

    def currentSong(self, current=None):
        def fin(current):
            return current.value(self.session, L9['currentSong'])
        if current is None:
            with self.graph.currentState() as current:
                return fin(current)
        else:
            return fin(current)

    def songSubtermsContext(self, current=None):
        return self.currentSong(current=current)

    def makeSubterm(self, newname, withCurve=False, expr=None, sub=None):
        with self.graph.currentState() as current:
            song = self.currentSong(current=current)
            for i in range(1000):
                uri = song + "/subterm/%d" % i
                if (uri, None, None) not in current:
                    break
            else:
                raise ValueError("can't pick a name for the new subterm")

        ctx = self.songSubtermsContext()
        quads = [
            (uri, RDF.type, L9.Subterm, ctx),
            (uri, RDFS.label, Literal(newname), ctx),
            (self.currentSong(), L9['subterm'], uri, ctx),
            ]
        if sub is not None:
            quads.append((uri, L9['sub'], sub, ctx))
        if expr is not None:
            quads.append((uri, L9['expression'], Literal(expr), ctx))
        self.graph.patch(Patch(addQuads=quads))
            
        if withCurve:
            self.curveset.new_curve(newname)
        return uri
                         
    def set_subterms_from_graph(self):
        master = self.wtree.get_object("subterms")
        log.info("removing subterm widgets")
        [master.remove(c) for c in master.get_children()]

        song = self.graph.value(self.session, L9['currentSong'])
        
        for st in set(self.graph.objects(song, L9['subterm'])):
            log.info("song %s has subterm %s", song, st)
            term = Subterm(self.graph, st, self.songSubtermsContext(), self.curveset)
            add_one_subterm(term, self.curveset, master)

        master.show_all()
        log.info("%s table children showing" % len(master.get_children()))
        
    def refreshTheme(self):
        gtk.rc_reparse_all()
        reactor.callLater(1, self.refreshTheme)

    def onSubtermChildAdded(self, subtermsTable, *args):
        # this would probably work, but isn't getting called
        log.info("onSubtermChildAdded")
        v = subtermsTable.get_parent().props.vadjustment
        v.props.value = v.props.upper

    def onQuit(self, *args):
        reactor.crash()
        # there's a hang after this, maybe in sem_wait in two
        # threads. I don't know whose they are.
        # This fix affects profilers who want to write output at the end.
        os.kill(os.getpid(), signal.SIGKILL)

    def onCollapseAll(self, *args):
        self.curvesetView.collapseAll()

    def onCollapseNone(self, *args):
        self.curvesetView.collapseNone()

    def onDelete(self, *args):
        self.curvesetView.onDelete()

    def onPythonConsole(self, item):
        ns = dict()
        ns.update(globals())
        ns.update(self.__dict__)
        togglePyConsole(self, item, ns)
        
    def onSeeCurrentTime(self, item):
        dispatcher.send("see time")

    def onSeeTimeUntilEnd(self, item):
        dispatcher.send("see time until end")

    def onZoomAll(self, item):
        dispatcher.send("show all")

    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):
        with self.graph.currentState() as g:
            song = g.value(self.session, L9['currentSong'])

            log.info("saving curves for %r", song)
            self.curveset.save(basename=os.path.join(
                showconfig.curvesDir(),
                showconfig.songFilenameFromURI(song)))
            log.info("saved")

    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()[:2]
                                                     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)
        dispatcher.connect(lambda val: setattr(self, 'lastSeenInputTime', val),
                           'input time', weak=False)
        master.show_all()

    def refreshCurveView(self):
        wtree = self.wtree
        mtimes = [os.path.getmtime(f) for f in [
            'light9/curvecalc/curveview.py',
            'light9/curvecalc/zoomcontrol.py',
            ]]

        if (not hasattr(self, 'curvesetView') or
            self.curvesetView._mtimes != mtimes):
            print "reload curveview.py"
            curvesVBox = wtree.get_object("curves")
            zoomControlBox = wtree.get_object("zoomControlBox")
            [curvesVBox.remove(c) for c in curvesVBox.get_children()]
            [zoomControlBox.remove(c) for c in
             zoomControlBox.get_children()]
            try:
                linecache.clearcache()
                reload(curveview)

                # old ones are not getting deleted right
                if hasattr(self, 'curvesetView'):
                    self.curvesetView.live = False

                # mem problem somewhere; need to hold a ref to this
                self.curvesetView = curveview.Curvesetview(
                    curvesVBox, zoomControlBox, self.curveset)
                self.curvesetView._mtimes = mtimes

                # 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:
                print "reload failed:"
                traceback.print_exc()
        if self.opts.reload:
            reactor.callLater(1, self.refreshCurveView)


class MaxTime(object):
    """
    looks up the time in seconds for the session's current song
    """
    def __init__(self, graph, session):
        self.graph, self.session = graph, session
        graph.addHandler(self.update)

    def update(self):
        song = self.graph.value(self.session, L9['currentSong'])
        if song is None:
            self.maxtime = 0
            return
        musicfilename = showconfig.songOnDisk(song)
        self.maxtime = wavelength(musicfilename)
        log.info("new max time %r", self.maxtime)
        dispatcher.send("max time", maxtime=self.maxtime)

    def get(self):
        return self.maxtime

def launch(args, graph, session, opts, startTime, music):

    try:
        song = URIRef(args[0])
        graph.patchObject(context=session,
                          subject=session,
                          predicate=L9['currentSong'],
                          newObject=song)
    except IndexError:
        pass

    curveset = Curveset(sliders=opts.sliders)

    def curvesetReload():
        # not sure if this clears right or not yet
        song = graph.value(session, L9['currentSong'])
        if song is None:
            return
        curveset.load(basename=os.path.join(
            showconfig.curvesDir(),
            showconfig.songFilenameFromURI(song)),
                      skipMusic=opts.skip_music)
    graph.addHandler(curvesetReload)
        
    log.debug("startup: output %s", time.time() - startTime)
    out = Output(graph, session, music, curveset)

    mt = MaxTime(graph, session)
    dispatcher.connect(lambda: mt.get(), "get max time", weak=False)

    start = Main(graph, opts, session, curveset, music)

    dispatcher.send("show all")
        
    if opts.startup_only:
        log.debug("quitting now because of --startup-only")
        return

    from twisted.web import server, resource
    class Hover(resource.Resource):
        isLeaf = True
        def render_GET(self, request):
            if request.path == '/hoverTime':
                results = dispatcher.send("onPlayPause")
                times = [t for listener, t in results if t is not None]
                if not times:
                    request.setResponseCode(404)
                    return "not hovering over any time"
                with graph.currentState() as g:
                    song = g.value(session, L9['currentSong'])
                    return json.dumps({"song": song, "hoverTime" : times[0]})
            raise NotImplementedError()

    reactor.listenTCP(networking.curveCalc.port,
                      server.Site(Hover()))

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("--reload", action="store_true",
                      help="live reload of themes and code")
    parser.add_option("--startup-only", action='store_true',
                      help="quit after loading everything (for timing tests)")
    clientsession.add_option(parser)
    opts, args = parser.parse_args()

    log.setLevel(logging.DEBUG if opts.debug else logging.INFO)

    log.debug("startup: music %s", time.time() - startTime)


    session = clientsession.getUri('curvecalc', opts)

    music = Music()
    graph = SyncedGraph("curvecalc")

    graph.initiallySynced.addCallback(
        lambda _: launch(args, graph, session, opts, startTime, music))

    reactor.run()

main()