from sugar.activity import activity

from Csound import *
from CsoundServer import *


import random
import sys, os
import gtk

import gobject
import time




class CSRecorderActivity(activity.Activity):
    orchestra = """
    nchnls = 2
	
ga1 init 0
ga2 init 0

giBuffer  ftgen 0, 0, 524288, 7, 0, 524288, 0 ;create an f-table with 10 seconds of silence

instr 1
        aIn1, aIn2  ins     

    iLen = ftlen(giBuffer)

    iRate = 1.0 / (iLen / sr)

    aPhase  phasor  iRate
    aPhase = aPhase * iLen

            tablew  aIn1, aPhase, giBuffer   
endin    

instr 2 ; reverse

    iDur    = p3

    iLen = ftlen(giBuffer)
    iRate = 1.0 / (iLen / sr)

    aPhase  phasor iRate
    aPhase = (iDur * sr) - aPhase * iLen

    aOut    tab     aPhase, giBuffer
	
    		vincr 	ga1, aOut*.43
    		vincr 	ga2, aOut*.43

        outs    aOut, aOut

endin

instr 3 ; forward

    iDur    = p3

    iLen = ftlen(giBuffer)
    iRate = 1.0 / (iLen / sr)

    aPhase  phasor iRate
    aPhase = aPhase * iLen

    aOut    tab     aPhase, giBuffer
	
    		vincr 	ga1, aOut*.43
    		vincr 	ga2, aOut*.43
    
		    outs    aOut, aOut

endin

		instr	99	
		denorm 	ga1, ga2
alin	buthp	ga1, 111
arin	buthp	ga2, 111
aL,aR  	reverbsc alin, arin, 0.850, 8000, sr, 0.5, 1
kgate   linenr	1, .2, 1, 1
		outs 	aL*kgate, aR*kgate
		clear 	ga1, ga2
		endin

    """

    def destroy(self, data=None):
        self.csound.shutdownServer()
        activity.Activity.destroy(self)

    def __init__(self, handle):
        print "Activity"
        activity.Activity.__init__(self, handle)
                       
        self.set_title('CSRecorder')
                
        # Creates the Toolbox. It contains the Activity Toolbar, which is the
        # bar that appears on every Sugar window and contains essential
        # functionalities, such as the 'Collaborate' and 'Close' buttons.
        toolbox = activity.ActivityToolbox(self)
        self.set_toolbox(toolbox)
        toolbox.show()
        
        print "buttons"
        
        self.recordButton = gtk.Button("Record")
        self.recordButton.set_size_request(100, 40)
        self.recordButton.connect("clicked", self.record)

        self.playButton = gtk.Button("Play")
        self.playButton.set_size_request(100, 40)
        self.playButton.connect("clicked", self.play)

        self.reverse = gtk.CheckButton("Reverse Playback")
        self.reverse.set_active(True)
        
        self.reverb = gtk.CheckButton("Add Reverb")
        self.reverb.connect("clicked", self.reverbOn)
        
        self.pbar = gtk.ProgressBar()
        self.pbar.set_size_request(330, 40)
            
        self.layout = gtk.Layout()
        self.layout.put(self.recordButton, 10, 10)
        self.layout.put(self.playButton, 230, 10)
        self.layout.put(self.pbar, 10, 60)
        self.layout.put(self.reverse, 10, 120)
        self.layout.put(self.reverb, 10, 170)
        self.layout.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#C0C0C0"))        
        self.layout.show_all()
        
                                                
        server = CsoundServer()
        fd = server.launch()
        if fd != None:
            gobject.io_add_watch(fd.fileno(), gobject.IO_IN, self.serverMessages, fd)
        
        self.set_canvas(self.layout)

        # Create our instance        
        self.csound = Csound("Recorder")
        self.csound.setMessageCallback(self.csoundMessages)
        self.csound.setupOrchestraAsString(self.orchestra)        
        self.csound.initialize()
        self.csound.perform()
        
                
    def progress_timeout(self, pbobj):        
        new_val = pbobj.pbar.get_fraction() + 0.01
        pbobj.pbar.set_text( str(new_val * 10.0) )
        
        if self.stop == True:
            return False
            
        if new_val > 1.0:
            new_val = 0.0
            self.stopRecording()            
            return False
            
        pbobj.pbar.set_fraction(new_val)
            
        return True
                    
    def serverMessages(self, source, condition, userData = None):
        print "SERVER:", userData.readline(),
        return True
                
    def record(self, widget, data=None):        
        if self.recordButton.get_label() == "Record":
            self.startRecording()
        else:
            self.stopRecording()
            
    def reverbOn(self, widget, data=None):
        if self.reverb.get_active():
            self.csound.playEvent('i', [99, 0, -1])
        else:
            self.csound.playEvent('i', [-99, 0, 2])
            
    def startRecording(self):    
        self.timer = gobject.timeout_add(100, self.progress_timeout, self)
        self.pbar.set_fraction(0.0)
        
        self.stop = False
        
        self.csound.playEvent('i', [1, 0, -1])

        self.recordButton.set_label("Stop")

    def stopRecording(self):
        self.csound.playEvent('i', [-1, 0, 1])

        self.stop = True

        self.recordButton.set_label("Record")

    def play(self, widget, data=None):
        dur = self.pbar.get_fraction() * 10.0
        if self.reverse.get_active():
            self.csound.playEvent('i', [2, 0, dur])
        else:
            self.csound.playEvent('i', [3, 0, dur])

                
    def csoundMessages(self, message):
        message.display("Csound")

