Пример #1
0
    def __init__( self ):
        self.instrumentDB = InstrumentDB.getRef()
        self.noteD = {}     # bins containing all the notes by page, track, and id
                            # structure self.noteD[pageId][trackIndex][noteId]

        self.noteS = {}     # bins containing all the notes by page and track
                            # first sorted by onset then by pitch (for drum hits)
                            # structure self.noteS[pageId][trackIndex][noteIndex]

        self.pages = {}     # dict of Pages indexed by pageId

        self.tune = []      # list of pageIds ordered by tune

        #self.beatsBefore = {}     # count of beats on previous pages indexed by page id

        self.listeners = []       # complete list of listeners
        self.pageListeners = []   # list of listeners who want page notifications
        self.noteListeners = []   # list of listeners who want note notifications
        self.parasiteList = {}    # dict of parasites indexed by listener

        self.parasiteD = {}       # bin of parasites indexed by listener
        self.parasiteS = {}       # parasites sorted as in self.noteS,

        self.nextId = 0     # base id, first page will be 1

        self.clipboard = [] # stores copied cs notes
        self.clipboardArea = [] # stores the limits and tracks for each page in the clipboard
Пример #2
0
    def __init__(self):
        self.instrumentDB = InstrumentDB.getRef()
        self.noteD = {}  # bins containing all the notes by page, track, and id
        # structure self.noteD[pageId][trackIndex][noteId]

        self.noteS = {}  # bins containing all the notes by page and track
        # first sorted by onset then by pitch (for drum hits)
        # structure self.noteS[pageId][trackIndex][noteIndex]

        self.pages = {}  # dict of Pages indexed by pageId

        self.tune = []  # list of pageIds ordered by tune

        #self.beatsBefore = {}     # count of beats on previous pages indexed by page id

        self.listeners = []  # complete list of listeners
        self.pageListeners = [
        ]  # list of listeners who want page notifications
        self.noteListeners = [
        ]  # list of listeners who want note notifications
        self.parasiteList = {}  # dict of parasites indexed by listener

        self.parasiteD = {}  # bin of parasites indexed by listener
        self.parasiteS = {}  # parasites sorted as in self.noteS,

        self.nextId = 0  # base id, first page will be 1

        self.clipboard = []  # stores copied cs notes
        self.clipboardArea = [
        ]  # stores the limits and tracks for each page in the clipboard
    def init_csound(self):
        if self.platform == "windows":
            self.hasCSound = False
            self.csa = CSoundAgent(self, None, grid_width, grid_height)
        else:
            import common.Config as Config
            from common.Generation.GenerationConstants import GenerationConstants
            from common.Util.NoteDB import Note
            from common.Util import NoteDB
            from common.Util.CSoundNote import CSoundNote
            from common.Util.CSoundClient import new_csound_client
            from common.Util import InstrumentDB
            import Musicpainter_Orchestra
            self.instrumentDB = InstrumentDB.getRef()
            self.csound = new_csound_client()
            time.sleep(0.01)
            for i in range(21):
                self.csound.setTrackVolume(100, i)
            self.load_instruments()
            self.csound.setTempo(90)

            self.noteDB = NoteDB.NoteDB()
            first_page = self.noteDB.addPage(
                -1, NoteDB.Page(4, self.instrument_list))
            self.hasCSound = True
            self.csa = CSoundAgent(self, self.csound, grid_width, grid_height)
Пример #4
0
    def __init__(self, owner, data):
        Block.__init__(self, owner, data)
        self.instrumentDB = InstrumentDB.getRef()
        self.type = Drum

        self.canSubstitute = True

        if not "page" in self.data.keys():
            self.data["page"] = -1
        if not "volume" in self.data.keys():
            self.data["volume"] = 0.5
        if not "reverb" in self.data.keys():
            self.data["reverb"] = 0.0
        if not "beats" in self.data.keys():
            self.data["beats"] = 4  # random.randint(2, 12)
        if not "regularity" in self.data.keys():
            self.data["regularity"] = 0.8  # random.random()
        if "key" not in self.data.keys():
            self.data["key"] = None

        self.owner.mapKey(self.data["key"], self)
        self.keyImage = [self.owner.getKeyImage(self.data["key"], False),
                          self.owner.getKeyImage(self.data["key"], True)]

        self.img = [self.owner.getInstrumentImage(self.data["id"], False),
                     self.owner.getInstrumentImage(self.data["id"], True)]

        if self.data["page"] == -1:
            self.regenerate()
Пример #5
0
    def __init__(self, owner, data):
        Block.__init__(self, owner, data)
        self.instrumentDB = InstrumentDB.getRef()
        self.type = Drum

        self.canSubstitute = True

        if not "page" in self.data.keys():
            self.data["page"] = -1
        if not "volume" in self.data.keys():
            self.data["volume"] = 0.5
        if not "reverb" in self.data.keys():
            self.data["reverb"] = 0.0
        if not "beats" in self.data.keys():
            self.data["beats"] = 4  #random.randint(2, 12)
        if not "regularity" in self.data.keys():
            self.data["regularity"] = 0.8  #random.random()
        if "key" not in self.data.keys():
            self.data["key"] = None

        self.owner.mapKey(self.data["key"], self)
        self.keyImage = [
            self.owner.getKeyImage(self.data["key"], False),
            self.owner.getKeyImage(self.data["key"], True)
        ]

        self.img = [
            self.owner.getInstrumentImage(self.data["id"], False),
            self.owner.getInstrumentImage(self.data["id"], True)
        ]

        if self.data["page"] == -1:
            self.regenerate()
Пример #6
0
 def __init__( self, beat, volume ):
     self.instrumentDB = InstrumentDB.getRef()
     self.notesDict = {}
     self.notesList = []
     self.beat = beat
     self.volume = volume
     self.id = 4000
     self.csnd = new_csound_client()
Пример #7
0
    def __init__(self, owner, filter=None):
        Picker.__init__(self, owner, filter)

        self.type = Drum

        self.instrumentDB = InstrumentDB.getRef()

        for inst in self.instrumentDB.getSet("percussions"):
            if self.instrumentDB.instNamed[inst.name].kit:
                self.addBlock(inst.instrumentId)
Пример #8
0
    def __init__(self, owner, filter=None):
        Picker.__init__(self, owner, filter)

        self.type = Drum

        self.instrumentDB = InstrumentDB.getRef()

        for inst in self.instrumentDB.getSet("percussions"):
            if self.instrumentDB.instNamed[inst.name].kit:
                self.addBlock(inst.instrumentId)
Пример #9
0
    def __init__(self, owner):
        gtk.EventBox.__init__(self)

        self.instrumentDB = InstrumentDB.getRef()
        self.owner = owner

        self.drawingArea = gtk.DrawingArea()
        self.add(self.drawingArea)

        # take drawing setup from owner
        self.gc = owner.gc
        self.colors = owner.colors
        self.blockMask = owner.blockMask

        self.noteDB = owner.noteDB

        self.dirtyRectToAdd = gtk.gdk.Rectangle(
        )  # used by the invalidate_rect function
        self.screenBuf = None
        self.screenBufDirty = False
        self.screenBufDirtyRect = gtk.gdk.Rectangle()

        self.blocks = []  # items on the desktop
        self.activeInstrument = None

        self.loops = {}  # dict of playing loops by loop root
        self.drums = []  # list of active drums

        self.add_events(gtk.gdk.POINTER_MOTION_MASK
                        | gtk.gdk.POINTER_MOTION_HINT_MASK)

        self.connect("size-allocate", self.on_size_allocate)
        self.connect("button-press-event", self.on_button_press)
        self.connect("button-release-event", self.on_button_release)
        self.connect("motion-notify-event", self.on_motion_notify)
        self.drawingArea.connect("expose-event", self.on_expose)

        self.clickedBlock = None
        self.possibleParent = None
        self.possibleSubstitute = None
        self.dragging = False
        self.possibleDelete = False
        self.overKey = False

        #-- Popups --------------------------------------------
        self.rightClicked = False

        self.popup = {}
        self.popup[Popup.Instrument] = Popup.Instrument(
            _("Instrument Properties"), self.owner)
        self.popup[Popup.Drum] = Popup.Drum(_("Drum Kit Properties"),
                                            self.owner)
        self.popup[Popup.Loop] = Popup.Loop(_("Loop Properties"), self.owner)
        self.popup[Popup.Shortcut] = Popup.Shortcut(_("Assign Key"),
                                                    self.owner)
Пример #10
0
    def __init__(self):
        sc_initialize( Config.PLUGIN_UNIVORC, Config.PLUGIN_DEBUG,
                Config.PLUGIN_VERBOSE, Config.PLUGIN_RATE)
        self.on = False
        #self.masterVolume = 100.0
        self.periods_per_buffer = 2
        global _loop_default
        _loop_default = self.loopCreate()
        self.instrumentDB = InstrumentDB.getRef()

        self.jamesSux = {} # temporyary dictionary of loopId: loopNumTicks, while I wait for james to implement it properly
Пример #11
0
    def __init__(self):
        sc_initialize( Config.PLUGIN_UNIVORC, Config.PLUGIN_DEBUG,
                Config.PLUGIN_VERBOSE, Config.PLUGIN_RATE)
        self.on = False
        #self.masterVolume = 100.0
        self.periods_per_buffer = 2
        global _loop_default
        _loop_default = self.loopCreate()
        self.instrumentDB = InstrumentDB.getRef()

        self.jamesSux = {} # temporyary dictionary of loopId: loopNumTicks, while I wait for james to implement it properly
Пример #12
0
 def __init__( self, recordingFunction, adjustDurationFunction, getCurrentTick, getPlayState, loop ):
     self.instrumentDB = InstrumentDB.getRef()
     self.csnd = new_csound_client()
     self.recording = recordingFunction
     self.adjustDuration = adjustDurationFunction
     self.getPlayState = getPlayState
     self.key_dict = dict()
     self.onset_dict = dict()
     self.trackCount = 0
     self.instrument = 'flute'
     self.reverb = 0
     self.loop = loop
     self.loopSustain = False
     self.sustainedLoop = []
Пример #13
0
    def __init__( self, beats, color = 0, instruments = False, local = True ): # , tempo, insruments, color = 0 ):
        self.instrumentDB = InstrumentDB.getRef()
        self.beats = beats
        self.ticks = beats*Config.TICKS_PER_BEAT

        self.color = color

        if not instruments:
            self.instruments = [ self.instrumentDB.instNamed["kalimba"].instrumentId for i in range(Config.NUMBER_OF_TRACKS-1) ] + [ self.instrumentDB.instNamed["drum1kit"].instrumentId ]
        else:
            self.instruments = instruments[:]

        self.local = local # page local/global?

        self.nextNoteId = 0 # first note will be 1
 def __init__(self, recordingFunction, adjustDurationFunction,
              getCurrentTick, getPlayState, loop):
     self.instrumentDB = InstrumentDB.getRef()
     self.csnd = new_csound_client()
     self.recording = recordingFunction
     self.adjustDuration = adjustDurationFunction
     self.getPlayState = getPlayState
     self.key_dict = dict()
     self.onset_dict = dict()
     self.trackCount = 0
     self.instrument = 'flute'
     self.reverb = 0
     self.loop = loop
     self.loopSustain = False
     self.sustainedLoop = []
Пример #15
0
    def __init__( self, owner ):
        GObject.GObject.__init__( self )

        self.instrumentDB = InstrumentDB.getRef()
        self.owner = owner

        self.drawingArea = Gtk.DrawingArea()
        self.add( self.drawingArea )

        self.colors = owner.colors
        # TODO the masks are pending
        # self.blockMask = owner.blockMask

        self.noteDB = owner.noteDB

        self.dirtyRectToAdd = Gdk.Rectangle() # used by the invalidate_rect function
        self.screenBufDirty = False
        self.screenBufDirtyRect = Gdk.Rectangle()

        self.blocks = [] # items on the desktop
        self.activeInstrument = None

        self.loops = {} # dict of playing loops by loop root
        self.drums = [] # list of active drums

        self.add_events(Gdk.EventMask.POINTER_MOTION_MASK|Gdk.EventMask.POINTER_MOTION_HINT_MASK)

        self.connect( "size-allocate", self.on_size_allocate )
        self.connect( "button-press-event", self.on_button_press )
        self.connect( "button-release-event", self.on_button_release )
        self.connect( "motion-notify-event", self.on_motion_notify )
        self.drawingArea.connect("draw", self.__draw_cb)

        self.clickedBlock = None
        self.possibleParent = None
        self.possibleSubstitute = None
        self.dragging = False
        self.possibleDelete = False
        self.overKey = False

        #-- Popups --------------------------------------------
        self.rightClicked = False

        self.popup = {}
        self.popup[Popup.Instrument] = Popup.Instrument( _("Instrument Properties"), self.owner )
        self.popup[Popup.Drum] = Popup.Drum( _("Drum Kit Properties"), self.owner )
        self.popup[Popup.Loop] = Popup.Loop( _("Loop Properties"), self.owner )
        self.popup[Popup.Shortcut] = Popup.Shortcut( _("Assign Key"), self.owner )
Пример #16
0
    def __init__(self):

        sc_initialize(
            Config.PLUGIN_UNIVORC, Config.PLUGIN_DEBUG,
            Config.PLUGIN_PERIOD, Config.PLUGIN_NPERIODS,
            Config.PLUGIN_VERBOSE,
            Config.PLUGIN_KSMPS, Config.PLUGIN_RATE)
            
        self.on = False
        #self.masterVolume = 100.0
        self.periods_per_buffer = 2
        global _loop_default
        _loop_default = self.loopCreate()
        self.instrumentDB = InstrumentDB.getRef()

        self.jamesSux = {} # temporyary dictionary of loopId:
Пример #17
0
    def __init__(self,setInstrument=None):
        Gtk.EventBox.__init__(self)

        self._scrolled_window = None

        self.instrumentDB = InstrumentDB.getRef()
        self.setInstrument = setInstrument
        self.playInstrument = None
        self.micRec = None
        self.synthRec = None
        self.rowLen = None
        self.enterMode = False

        self.instDic = None

        self.loaded = False
        self.loadData = {}
Пример #18
0
    def __init__(self, setInstrument=None):
        Gtk.EventBox.__init__(self)

        self._scrolled_window = None

        self.instrumentDB = InstrumentDB.getRef()
        self.setInstrument = setInstrument
        self.playInstrument = None
        self.micRec = None
        self.synthRec = None
        self.rowLen = None
        self.enterMode = False

        self.instDic = None

        self.loaded = False
        self.loadData = {}
    def __init__(self,setInstrument = None, playInstrument = None, enterMode = False, micRec = None, synthRec = None, rowLen = 8, _instDic = None, force_load = True ):
        gtk.EventBox.__init__(self)

        self.instrumentDB = InstrumentDB.getRef()
        self.setInstrument = setInstrument
        self.playInstrument = playInstrument
        self.micRec = micRec
        self.synthRec = synthRec
        self.rowLen = rowLen
        self.enterMode = enterMode

        self.instDic = _instDic

        self.loaded = False
        self.loadData = {}
        self.loadStage = [0,0,0]
        if force_load: self.load()
Пример #20
0
    def __init__(self,
                 beats,
                 color=0,
                 instruments=False,
                 local=True):  # , tempo, insruments, color = 0 ):
        self.instrumentDB = InstrumentDB.getRef()
        self.beats = beats
        self.ticks = beats * Config.TICKS_PER_BEAT

        self.color = color

        if not instruments:
            self.instruments = [
                self.instrumentDB.instNamed["kalimba"].instrumentId
                for i in range(Config.NUMBER_OF_TRACKS - 1)
            ] + [self.instrumentDB.instNamed["jazzrock"].instrumentId]
        else:
            self.instruments = instruments[:]

        self.local = local  # page local/global?

        self.nextNoteId = 0  # first note will be 1
Пример #21
0
    def __init__(self, owner, filter=("All")):
        Picker.__init__(self, owner, filter)

        self.type = Instrument

        self.instrumentDB = InstrumentDB.getRef()

        all = []
        lab = []
        mic = []

        for i in self.instrumentDB.getSet("All"):
            if i.name.startswith("lab"):
                lab.append(i)
            elif i.name.startswith("mic"):
                mic.append(i)
            elif not i.kitStage and not i.kit:
                all.append(i)

        all += sorted(lab, key=lambda i: i.name)
        all += sorted(mic, key=lambda i: i.name)

        for inst in all:
            self.addBlock(inst.instrumentId)
Пример #22
0
    def __init__(self, owner, filter=("All")):
        Picker.__init__(self, owner, filter)

        self.type = Instrument

        self.instrumentDB = InstrumentDB.getRef()

        all = []
        lab = []
        mic = []

        for i in self.instrumentDB.getSet("All"):
            if i.name.startswith('lab'):
                lab.append(i)
            elif i.name.startswith('mic'):
                mic.append(i)
            elif not i.kitStage and not i.kit:
                all.append(i)

        all += sorted(lab, key=lambda i: i.name)
        all += sorted(mic, key=lambda i: i.name)

        for inst in all:
            self.addBlock(inst.instrumentId)
Пример #23
0
    def __init__(self,
        onset,
        pitch,
        amplitude,
        pan,
        duration,
        trackId,
        instrumentId=1, #self.instrumentDB.instNamed["flute"].instrumentId,
        attack=0.005,
        decay=0.098,
        reverbSend=0.1,
        filterType=0,
        filterCutoff=1000,
        tied=False,
        mode='edit',
        instrumentId2=-1):

        self.instrumentDB = InstrumentDB.getRef()

        self.onset = onset
        self.pitch = pitch
        self.amplitude = amplitude
        self.pan = pan
        self.duration = duration
        self.trackId = trackId
        self.instrumentId = instrumentId
        #temp: catch old code trying to pass in instrument names here
        int(instrumentId)
        self.attack = attack
        self.decay = decay
        self.reverbSend = reverbSend
        self.filterType = filterType
        self.filterCutoff = filterCutoff
        self.tied = tied
        self.mode = mode
        self.instrumentId2 = instrumentId2
Пример #24
0
    def __init__( self,
            onset,
            pitch,
            amplitude,
            pan,
            duration,
            trackId,
            instrumentId = 1, #self.instrumentDB.instNamed["flute"].instrumentId,
            attack = 0.005,
            decay = 0.098,
            reverbSend = 0.1,
            filterType = 0,
            filterCutoff = 1000,
            tied = False,
            mode = 'edit',
            instrumentId2 = -1 ):

        self.instrumentDB = InstrumentDB.getRef()

        self.onset = onset
        self.pitch = pitch
        self.amplitude = amplitude
        self.pan = pan
        self.duration = duration
        self.trackId = trackId
        self.instrumentId = instrumentId
        #temp: catch old code trying to pass in instrument names here
        int(instrumentId)
        self.attack = attack
        self.decay = decay
        self.reverbSend = reverbSend
        self.filterType = filterType
        self.filterCutoff = filterCutoff
        self.tied = tied
        self.mode = mode
        self.instrumentId2 = instrumentId2
Пример #25
0
 def __init__(self, file):
     self.file = file
     self.instrumentDB = InstrumentDB.getRef()
Пример #26
0
def generator( instrument, nbeats, density, regularity, reverbSend ):

    instrumentDB = InstrumentDB.getRef()
    makeRythm = GenRythm()

    noteDuration = GenerationConstants.DOUBLE_TICK_DUR / 2
    trackId = 5
    pan = 0.5
    attack = 0.005
    decay = 0.095
    filterType = 0
    filterCutoff = 1000
    tied = False
    mode = 'mini'

    def makePitchSequence(length, drumPitch):
        pitchSequence = []
        append = pitchSequence.append
        list = range(length)
        max = len(drumPitch) - 1
        for i in list:
            append(drumPitch[ random.randint( 0, max ) ] )
        return pitchSequence

    def makeGainSequence( onsetList ):
        gainSequence = []
        append = gainSequence.append
        for onset in onsetList:
            if onset == 0:
                gain = random.uniform(GenerationConstants.GAIN_MID_MAX_BOUNDARY, GenerationConstants.GAIN_MAX_BOUNDARY)
            elif ( onset % Config.TICKS_PER_BEAT) == 0:
                gain = random.uniform(GenerationConstants.GAIN_MID_MIN_BOUNDARY, GenerationConstants.GAIN_MID_MAX_BOUNDARY)
            else:
                gain = random.uniform(GenerationConstants.GAIN_MIN_BOUNDARY, GenerationConstants.GAIN_MID_MIN_BOUNDARY)
            append(gain)
        return gainSequence

    def pageGenerate( regularity, drumPitch ):
        barLength = Config.TICKS_PER_BEAT * nbeats

        #print 'pageGenerate drumPitch[0] ', drumPitch[0]
        currentInstrument = instrumentDB.instNamed[ instrument ].kit[ drumPitch[0] ] #.name

        rythmSequence = makeRythm.drumRythmSequence(currentInstrument, nbeats, density, regularity)
        pitchSequence = makePitchSequence(len(rythmSequence), drumPitch )
        gainSequence = makeGainSequence(rythmSequence)

        trackNotes = []
        list = range(len(rythmSequence))
        for i in list:
            trackNotes.append( CSoundNote( rythmSequence[i], pitchSequence[i], gainSequence[i],
                                           pan, noteDuration, trackId,
                                           instrumentDB.instNamed[instrument].instrumentId, attack,
                                           decay, reverbSend, filterType, filterCutoff, tied, mode))
        return trackNotes

##################################################################################
    #  begin generate()
    if regularity > 0.75:
        streamOfPitch = GenerationConstants.DRUM_COMPLEXITY1
    elif regularity > 0.5:
        streamOfPitch = GenerationConstants.DRUM_COMPLEXITY2
    elif regularity > 0.25:
        streamOfPitch = GenerationConstants.DRUM_COMPLEXITY3
    else:
        streamOfPitch = GenerationConstants.DRUM_COMPLEXITY4

    trackNotes = []
    for drumPitch in streamOfPitch:
        trackNotes.append(pageGenerate( regularity, drumPitch ))
    return trackNotes
Пример #27
0
    def __init__(self, activity):
        GObject.GObject.__init__(self)

        self.activity = activity

        self.instrumentDB = InstrumentDB.getRef()
        self.noteDB = NoteDB.NoteDB()

        #-- initial settings ----------------------------------
        self.tempo = Config.PLAYER_TEMPO
        self.beatDuration = 60.0 / self.tempo
        self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0
        self.volume = 0.5

        self.csnd = new_csound_client()
        for i in range(0, 9):
            self.csnd.setTrackVolume(100, i)
        # csnd expects a range 0-100 for now
        self.csnd.setMasterVolume(self.volume * 100)
        self.csnd.setTempo(self.tempo)

        self.muted = False

        #-- Drawing -------------------------------------------
        def darken(hex):
            hexToDec = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6,
                        "7": 7, "8": 8, "9": 9, "A": 10, "B": 11, "C": 12,
                        "D": 13, "E": 14, "F": 15, "a": 10, "b": 11, "c": 12,
                        "d": 13, "e": 14, "f": 15}
            r = int(0.7 * (16 * hexToDec[hex[1]] + hexToDec[hex[2]]))
            g = int(0.7 * (16 * hexToDec[hex[3]] + hexToDec[hex[4]]))
            b = int(0.7 * (16 * hexToDec[hex[5]] + hexToDec[hex[6]]))
            return r * 256, g * 256, b * 256

        def lighten(hex):
            hexToDec = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6,
                        "7": 7, "8": 8, "9": 9, "A": 10, "B": 11, "C": 12,
                        "D": 13, "E": 14, "F": 15, "a": 10, "b": 11, "c": 12,
                        "d": 13, "e": 14, "f": 15}
            r = 255 - int(0.7 * (255 - (
                        16 * hexToDec[hex[1]] + hexToDec[hex[2]])))
            g = 255 - int(0.7 * (255 - (
                        16 * hexToDec[hex[3]] + hexToDec[hex[4]])))
            b = 255 - int(0.7 * (255 - (
                        16 * hexToDec[hex[5]] + hexToDec[hex[6]])))
            return r * 256, g * 256, b * 256

        xoColor = profile.get_color()
        if not xoColor:
            xoColorKey = ("#8D8D8D,#FFDDEA")
            xoColor = XoColor(xoColorKey)

        # colors in Config and in XoColor are strings,
        # the colors in style are style.Color, transform all to Gdk.Color
        self.colors = {"bg": CairoUtil.get_gdk_color(Config.PANEL_BCK_COLOR),
               "black": style.COLOR_BLACK.get_gdk_color(),
               #"Picker_Bg": colormap.alloc_color("#404040"),
               #"Picker_Bg_Inactive": colormap.alloc_color("#808080"),
               "Picker_Bg": style.COLOR_TOOLBAR_GREY.get_gdk_color(),
               "Picker_Bg_Inactive": style.COLOR_BUTTON_GREY.get_gdk_color(),
               "Picker_Fg": style.COLOR_WHITE.get_gdk_color(),
               "Border_Active": \
                        CairoUtil.get_gdk_color(xoColor.get_stroke_color()),
               "Border_Inactive": CairoUtil.get_gdk_color("#8D8D8D"),
               "Border_Highlight": CairoUtil.get_gdk_color("#FFFFFF"),
               "Bg_Active": CairoUtil.get_gdk_color(xoColor.get_fill_color()),
               "Bg_Inactive": CairoUtil.get_gdk_color("#DBDBDB"),
               "Preview_Note_Fill": CairoUtil.get_gdk_color(Config.BG_COLOR),
               "Preview_Note_Border": CairoUtil.get_gdk_color(Config.FG_COLOR),
               "Preview_Note_Selected": style.COLOR_WHITE.get_gdk_color(),
                # TODO: lighten here can be removed, check if is used in other
                # places
               "Note_Fill_Active": Gdk.Color(*lighten("#590000")),
               # base "Border_Active"
               "Note_Fill_Inactive": Gdk.Color(*lighten("#8D8D8D")),
               # base "Border_Inactive"
               "Beat_Line": CairoUtil.get_gdk_color("#959595")}
        self.colors["Note_Border_Active"] = self.colors["Border_Active"]
        self.colors["Note_Border_Inactive"] = self.colors["Border_Inactive"]

        self.sampleNoteHeight = 7

        self.sampleBg = cairo.ImageSurface.create_from_png(
                imagefile('sampleBG.png'))
        self.loopPitchOffset = 4
        self.loopTickOffset = 13
        self.pitchPerPixel = float(Config.NUMBER_OF_POSSIBLE_PITCHES - 1) / \
            (Block.Loop.HEIGHT - 2 * self.loopPitchOffset - \
                 self.sampleNoteHeight)
        self.pixelsPerPitch = float(Block.Loop.HEIGHT - \
            2 * self.loopPitchOffset - self.sampleNoteHeight) / \
            (Config.MAXIMUM_PITCH - Config.MINIMUM_PITCH)
        self.pixelsPerTick = Block.Loop.BEAT / float(Config.TICKS_PER_BEAT)
        self.ticksPerPixel = 1.0 / self.pixelsPerTick

        #-- Instruments ---------------------------------------
        self.instrumentImage = {}
        self.instrumentImageActive = {}
        for inst in self.instrumentDB.getSet("All"):
            if not inst.kitStage:
                self.prepareInstrumentImage(inst.instrumentId, inst.img)
            self.csnd.load_instrument(inst.name)

        #-- Loop Images ---------------------------------------
        self.loopImage = {}  # get filled in through updateLoopImage
        self.loopImageActive = {}

        #-- Key Images ----------------------------------------
        self.keyImage = {}
        self.keyImageActive = {}
        # use hardware key codes to work on any keyboard layout (hopefully)
        self.valid_shortcuts = {18: "9", 19: "0", 20: "-", 21: "=",
                                32: "O", 33: "P", 34: "[", 35: "]",
                                47: ";", 48: "'", 51: "\\",
                                60: ".", 61: "/",
                                None: " "}
        for key in self.valid_shortcuts.keys():
            self.prepareKeyImage(key)

        #-- Toolbars ------------------------------------------

        self.jamToolbar = JamToolbar(self)
        jam_toolbar_button = ToolbarButton(label=_('Jam'),
                                           page=self.jamToolbar,
                                           icon_name='voltemp')
        self.jamToolbar.show()
        jam_toolbar_button.show()
        self.activity.toolbar_box.toolbar.insert(jam_toolbar_button, -1)

        self.beatToolbar = BeatToolbar(self)
        beat_toolbar_button = ToolbarButton(label=_('Beat'),
                                                page=self.beatToolbar,
                                                icon_name='heart')
        self.beatToolbar.show()
        beat_toolbar_button.show()
        self.activity.toolbar_box.toolbar.insert(beat_toolbar_button, -1)

        self.desktopToolbar = DesktopToolbar(self)
        desktop_toolbar_button = ToolbarButton(label=_('Desktop'),
                                              page=self.desktopToolbar,
                                              icon_name='jam-presets-list')
        self.desktopToolbar.show()
        desktop_toolbar_button.show()
        self.activity.toolbar_box.toolbar.insert(desktop_toolbar_button, -1)

        if Config.FEATURES_MIC or Config.FEATURES_NEWSOUNDS:
            self.recordToolbar = RecordToolbar(self)
            record_toolbar_button = ToolbarButton(label=_('Record'),
                                                  page=self.recordToolbar,
                                                  icon_name='microphone')
            self.recordToolbar.show()
            record_toolbar_button.show()
            self.activity.toolbar_box.toolbar.insert(record_toolbar_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = True
        separator.set_expand(False)
        self.activity.toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        common_playback_buttons(self.activity.toolbar_box.toolbar, self)

        #-- GUI -----------------------------------------------
        if True:  # GUI
            self.modify_bg(Gtk.StateType.NORMAL, self.colors["bg"])

            self.GUI = {}
            self.GUI["mainVBox"] = Gtk.VBox()
            self.add(self.GUI["mainVBox"])

            #-- Desktop -------------------------------------------
            self.desktop = self.GUI["desktop"] = Desktop(self)
            self.GUI["mainVBox"].pack_start(self.GUI["desktop"], True, True, 0)

            #-- Bank ----------------------------------------------
            separator = Gtk.Label(label=" ")
            separator.set_size_request(-1, style.TOOLBOX_SEPARATOR_HEIGHT)
            self.GUI["mainVBox"].pack_start(separator, False, True, 0)
            self.GUI["notebook"] = Gtk.Notebook()
            self.GUI["notebook"].set_scrollable(True)
            self.GUI["notebook"].modify_bg(Gtk.StateType.NORMAL,
                                           self.colors["Picker_Bg"])
            self.GUI["notebook"].modify_bg(Gtk.StateType.ACTIVE,
                                           self.colors["Picker_Bg_Inactive"])
            # TODO gtk3 no available anymore?
            #self.GUI["notebook"].props.tab_vborder = style.TOOLBOX_TAB_VBORDER
            #self.GUI["notebook"].props.tab_hborder = style.TOOLBOX_TAB_HBORDER
            self.GUI["notebook"].set_size_request(-1, scale(160))
            self.GUI["notebook"].connect("switch-page", self.setPicker)
            self.GUI["mainVBox"].pack_start(self.GUI["notebook"], False,
                    False, 0)
            self.pickers = {}
            self.pickerScroll = {}
            for type in [Picker.Instrument, Picker.Drum, Picker.Loop]:
                self.pickers[type] = type(self)

            def prepareLabel(name):
                label = Gtk.Label(label=Tooltips.categories.get(name) or name)
                label.set_alignment(0.0, 0.5)
                label.modify_fg(Gtk.StateType.NORMAL, self.colors["Picker_Fg"])
                label.modify_fg(Gtk.StateType.ACTIVE, self.colors["Picker_Fg"])
                return label

            self.GUI["notebook"].append_page(self.pickers[Picker.Drum],
                                             prepareLabel(_("Drum Kits")))
            self.GUI["notebook"].append_page(self.pickers[Picker.Loop],
                                             prepareLabel(_("Loops")))

            sets = self.instrumentDB.getLabels()[:]
            sets.sort()
            for set in sets:
                page = Gtk.HBox()
                page.set = set
                self.GUI["notebook"].append_page(page, prepareLabel(set))

            self.show_all()

            self.GUI["notebook"].set_current_page(0)

        #-- Keyboard ------------------------------------------
        self.key_dict = {}
        self.nextTrack = 2
        self.keyboardListener = None
        self.recordingNote = None

        self.keyMap = {}

        # default instrument
        self._updateInstrument(
            self.instrumentDB.instNamed["kalimba"].instrumentId, 0.5)
        self.instrumentStack = []

        # metronome
        page = NoteDB.Page(1, local=False)
        self.metronomePage = self.noteDB.addPage(-1, page)
        self.metronome = False

        #-- Drums ---------------------------------------------
        self.drumLoopId = None
        # use dummy values for now
        self.drumFillin = Fillin(
            2, 100, self.instrumentDB.instNamed["drum1kit"].instrumentId, 0, 1)

        #-- Desktops ------------------------------------------
        self.curDesktop = None
        # copy preset desktops
        path = Config.FILES_DIR + "/Desktops/"
        filelist = os.listdir(path)
        for file in filelist:
            shutil.copyfile(path + file, Config.TMP_DIR + '/' + file)

        #-- Network -------------------------------------------
        self.network = Net.Network()
        self.network.addWatcher(self.networkStatusWatcher)
        self.network.connectMessage(Net.HT_SYNC_REPLY,
                                    self.processHT_SYNC_REPLY)
        self.network.connectMessage(Net.HT_TEMPO_UPDATE,
                                    self.processHT_TEMPO_UPDATE)
        self.network.connectMessage(Net.PR_SYNC_QUERY,
                                    self.processPR_SYNC_QUERY)
        self.network.connectMessage(Net.PR_TEMPO_QUERY,
                                    self.processPR_TEMPO_QUERY)
        self.network.connectMessage(Net.PR_REQUEST_TEMPO_CHANGE,
                                    self.processPR_REQUEST_TEMPO_CHANGE)

        # sync
        self.syncQueryStart = {}
        self.syncTimeout = None
        self.heartbeatLoop = self.csnd.loopCreate()
        self.syncBeats = 4
        self.syncTicks = self.syncBeats * Config.TICKS_PER_BEAT
        self.offsetTicks = 0  # offset from the true heartbeat
        self.csnd.loopSetNumTicks(self.syncTicks * HEARTBEAT_BUFFER,
                                  self.heartbeatLoop)
        self.heartbeatStart = time.time()
        self.csnd.loopStart(self.heartbeatLoop)
        self.curBeat = 0
        self.beatWheelTimeout = GObject.timeout_add(100, self.updateBeatWheel)

        # data packing classes
        self.packer = xdrlib.Packer()
        self.unpacker = xdrlib.Unpacker("")

        # handle forced networking
        if self.network.isHost():
            self.updateSync()
            self.syncTimeout = GObject.timeout_add(1000, self.updateSync)
        elif self.network.isPeer():
            self.sendTempoQuery()
            self.syncTimeout = GObject.timeout_add(1000, self.updateSync)

        self.activity.connect("shared", self.shared)

        if self.activity.shared_activity:  # PEER
            self.activity.shared_activity.connect("buddy-joined",
                                                   self.buddy_joined)
            self.activity.shared_activity.connect("buddy-left",
                                                   self.buddy_left)
            self.activity.connect("joined", self.joined)
            self.network.setMode(Net.MD_WAIT)

        #-- Final Set Up --------------------------------------
        self.setVolume(self.volume)
        self.setTempo(self.tempo)
        #self.activity.toolbar_box.set_current_toolbar(1)  # JamToolbar
        self.setDesktop(0, True)
Пример #28
0
    def __init__(self, activity):
        Gtk.HBox.__init__(self)

        self.instrumentPanel = None
        self.activity = activity

        self.instrumentDB = InstrumentDB.getRef()
        self.firstTime = False
        self.playing = False
        self.csnd = new_csound_client()
        self.timeout_ms = 50
        self.instVolume = 50
        self.drumVolume = 0.5
        self.instrument = 'sarangi'
        self.regularity = 0.75
        self.beat = 4
        self.reverb = 0.1
        self.tempo = Config.PLAYER_TEMPO
        self.beatDuration = 60.0/self.tempo
        self.ticksPerSecond = Config.TICKS_PER_BEAT*self.tempo/60.0
        self.rythmInstrument = 'drum1kit'
        self.csnd.load_drumkit(self.rythmInstrument)
        self.muteInst = False
        self.drumFillin = Fillin( self.beat, self.tempo, self.rythmInstrument, self.reverb, self.drumVolume )
        self.sequencer= MiniSequencer(self.recordStateButton, self.recordOverSensitivity)
        self.loop = Loop(self.beat, sqrt( self.instVolume*0.01 ))
        self.csnd.setTempo(self.tempo)
        self.noteList = []
        time.sleep(0.001) # why?
        self.trackpad = Trackpad( self )
        for i in range(21):
            self.csnd.setTrackVolume( 100, i )

        for i in  range(10):
            r = str(i+1)
            self.csnd.load_instrument('guidice' + r)

        self.volume = 100
        self.csnd.setMasterVolume(self.volume)
        self.sequencer.beat = self.beat
        self.loop.beat = self.beat

        self.leftBox = Gtk.VBox()
        self.rightBox = Gtk.VBox()
        # TODO: right is at left, and left is at right?
        self.pack_start(self.rightBox, False, False, 0)
        self.pack_start(self.leftBox, False, False, 0)

        self.enableKeyboard()
        self.setInstrument(self.instrument)

        self.connect('key-press-event', self.onKeyPress)
        self.connect('key-release-event', self.onKeyRelease)

        self.drawGeneration()
        self.show_all()
        if 'a good idea' == True:
            self.playStartupSound()

        self.beatPickup = True
        #self.regenerate()

        self.heartbeatStart = time.time()
        self.syncQueryStart = {}
        self.syncTimeout = None

        self.network = Net.Network()
        self.network.addWatcher( self.networkStatusWatcher )
        self.network.connectMessage( Net.HT_SYNC_REPLY, self.processHT_SYNC_REPLY )
        self.network.connectMessage( Net.HT_TEMPO_UPDATE, self.processHT_TEMPO_UPDATE )
        self.network.connectMessage( Net.PR_SYNC_QUERY, self.processPR_SYNC_QUERY )
        self.network.connectMessage( Net.PR_TEMPO_QUERY, self.processPR_TEMPO_QUERY )
        self.network.connectMessage( Net.PR_REQUEST_TEMPO_CHANGE, self.processPR_REQUEST_TEMPO_CHANGE )

        # data packing classes
        self.packer = xdrlib.Packer()
        self.unpacker = xdrlib.Unpacker("")

        #-- handle forced networking ---------------------------------------
        if self.network.isHost():
            self.updateSync()
            self.syncTimeout = GObject.timeout_add( 1000, self.updateSync )
        elif self.network.isPeer():
            self.sendTempoQuery()
            self.syncTimeout = GObject.timeout_add( 1000, self.updateSync )
        #-------------------------------------------------------------------

        # Toolbar
        if Config.HAVE_TOOLBOX:
            from sugar3.graphics.toolbarbox import ToolbarButton

            # no sharing
            # self.max_participants = 1

            self._playToolbar = playToolbar(self)
            ## Uncomment to show play and record tabs ##
            '''
            play_toolbar_button = ToolbarButton(label=_('Play'),
                                                page=self._playToolbar,
                                                # Fixme: need an icon
                                                icon_name='activity-start')
            self._playToolbar.show()
            play_toolbar_button.show()
            self.activity.toolbox.toolbar.insert(play_toolbar_button, -1)

            self._recordToolbar = recordToolbar(self)
            record_toolbar_button = ToolbarButton(label=_('Record'),
                                                page=self._recordToolbar,
                                                # Fixme: need an icon
                                                icon_name='media-record')
            self._recordToolbar.show()
            record_toolbar_button.show()
            self.activity.toolbox.toolbar.insert(record_toolbar_button, -1)
            '''
        else:
            self._playToolbar = playToolbar(self)

        ## set to 1 to show play and record tabs ##
        if 0:
            self._recordToolbar = recordToolbar(self)
            self.activity.toolbox.add_toolbar(_('Play'), self._playToolbar)
            self.activity.toolbox.add_toolbar(_('Record'), self._recordToolbar)
            self.activity.toolbox.set_current_toolbar(1)
            self._playToolbar.show()
            self._recordToolbar.show()

        if not Config.HAVE_TOOLBOX:
            self.activity.connect( "shared", self.shared )

        if os.path.isfile("FORCE_SHARE"):    # HOST
            #print "::::: Sharing as TTDBG%f :::::" % r
            #self.activity.set_title(_("TTDBG%f" % r))
            print "::::: Sharing as TamTam :::::"
            self.activity.set_title(_("TamTam"))
            self.activity.share()
        elif self.activity.shared_activity: # PEER
            self.activity.shared_activity.connect( "buddy-joined", self.buddy_joined )
            self.activity.shared_activity.connect( "buddy-left", self.buddy_left )
            self.activity.connect( "joined", self.joined )
            self.network.setMode( Net.MD_WAIT )
Пример #29
0
 def __init__(self, noteDB = None, jam = None ):
     self.noteDB = noteDB
     self.jam = jam
     self.csnd = new_csound_client()
     self.pid = {}   #stream_pid : local_pid
     self.instrumentDB = InstrumentDB.getRef()
    def __init__(self, activity):
        gtk.EventBox.__init__(self)

        self.instrumentPanel = None
        self.activity = activity

        #self.set_border_width(Config.MAIN_WINDOW_PADDING)
        #self.set_border_width(0)

        self.instrumentDB = InstrumentDB.getRef()
        self.firstTime = False
        self.playing = False
        self.csnd = new_csound_client()
        self.timeout_ms = 50
        self.instVolume = 50
        self.drumVolume = 0.5
        self.instrument = 'sarangi'
        self.regularity = 0.75
        self.beat = 4
        self.reverb = 0.1
        self.tempo = Config.PLAYER_TEMPO
        self.beatDuration = 60.0 / self.tempo
        self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0
        self.rythmInstrument = 'drum1kit'
        self.csnd.load_drumkit(self.rythmInstrument)
        self.muteInst = False
        self.drumFillin = Fillin(self.beat, self.tempo, self.rythmInstrument,
                                 self.reverb, self.drumVolume)
        self.sequencer = MiniSequencer(self.recordStateButton,
                                       self.recordOverSensitivity)
        self.loop = Loop(self.beat, sqrt(self.instVolume * 0.01))
        self.csnd.setTempo(self.tempo)
        self.noteList = []
        time.sleep(0.001)  # why?
        self.trackpad = Trackpad(self)
        for i in range(21):
            self.csnd.setTrackVolume(100, i)

        for i in range(10):
            r = str(i + 1)
            self.csnd.load_instrument('guidice' + r)

        self.volume = 100
        self.csnd.setMasterVolume(self.volume)
        self.sequencer.beat = self.beat
        self.loop.beat = self.beat
        self.tooltips = gtk.Tooltips()

        self.mainWindowBox = gtk.HBox()
        self.leftBox = gtk.VBox()
        self.rightBox = gtk.VBox()
        self.mainWindowBox.pack_start(self.rightBox, False, True)
        self.mainWindowBox.pack_start(self.leftBox, True, True)
        self.add(self.mainWindowBox)

        self.enableKeyboard()
        self.setInstrument(self.instrument)

        self.connect('key-press-event', self.onKeyPress)
        self.connect('key-release-event', self.onKeyRelease)

        self.drawGeneration()
        self.show_all()
        if 'a good idea' == True:
            self.playStartupSound()

        self.beatPickup = True
        #self.regenerate()

        self.heartbeatStart = time.time()
        self.syncQueryStart = {}
        self.syncTimeout = None

        self.network = Net.Network()
        self.network.addWatcher(self.networkStatusWatcher)
        self.network.connectMessage(Net.HT_SYNC_REPLY,
                                    self.processHT_SYNC_REPLY)
        self.network.connectMessage(Net.HT_TEMPO_UPDATE,
                                    self.processHT_TEMPO_UPDATE)
        self.network.connectMessage(Net.PR_SYNC_QUERY,
                                    self.processPR_SYNC_QUERY)
        self.network.connectMessage(Net.PR_TEMPO_QUERY,
                                    self.processPR_TEMPO_QUERY)
        self.network.connectMessage(Net.PR_REQUEST_TEMPO_CHANGE,
                                    self.processPR_REQUEST_TEMPO_CHANGE)

        # data packing classes
        self.packer = xdrlib.Packer()
        self.unpacker = xdrlib.Unpacker("")

        #-- handle forced networking ---------------------------------------
        if self.network.isHost():
            self.updateSync()
            self.syncTimeout = gobject.timeout_add(1000, self.updateSync)
        elif self.network.isPeer():
            self.sendTempoQuery()
            self.syncTimeout = gobject.timeout_add(1000, self.updateSync)
        #-------------------------------------------------------------------

        # Toolbar
        if Config.HAVE_TOOLBOX:
            from sugar.graphics.toolbarbox import ToolbarButton

            # no sharing
            # self.max_participants = 1

            self._playToolbar = playToolbar(self)
            ## Uncomment to show play and record tabs ##
            '''
            play_toolbar_button = ToolbarButton(label=_('Play'),
                                                page=self._playToolbar,
                                                # Fixme: need an icon
                                                icon_name='activity-start')
            self._playToolbar.show()
            play_toolbar_button.show()
            self.activity.toolbox.toolbar.insert(play_toolbar_button, -1)

            self._recordToolbar = recordToolbar(self)
            record_toolbar_button = ToolbarButton(label=_('Record'),
                                                page=self._recordToolbar,
                                                # Fixme: need an icon
                                                icon_name='media-record')
            self._recordToolbar.show()
            record_toolbar_button.show()
            self.activity.toolbox.toolbar.insert(record_toolbar_button, -1)
            '''
        else:
            self._playToolbar = playToolbar(self)

        ## set to 1 to show play and record tabs ##
        if 0:
            self._recordToolbar = recordToolbar(self)
            self.activity.toolbox.add_toolbar(_('Play'), self._playToolbar)
            self.activity.toolbox.add_toolbar(_('Record'), self._recordToolbar)
            self.activity.toolbox.set_current_toolbar(1)
            self._playToolbar.show()
            self._recordToolbar.show()

        if not Config.HAVE_TOOLBOX:
            self.activity.connect("shared", self.shared)

        if os.path.isfile("FORCE_SHARE"):  # HOST
            r = random.random()
            #print "::::: Sharing as TTDBG%f :::::" % r
            #self.activity.set_title(_("TTDBG%f" % r))
            print "::::: Sharing as TamTam :::::"
            self.activity.set_title(_("TamTam"))
            self.activity.share()
        elif self.activity._shared_activity:  # PEER
            self.activity._shared_activity.connect("buddy-joined",
                                                   self.buddy_joined)
            self.activity._shared_activity.connect("buddy-left",
                                                   self.buddy_left)
            self.activity.connect("joined", self.joined)
            self.network.setMode(Net.MD_WAIT)
Пример #31
0
 def __init__(self, file):
     self.file = file
     self.instrumentDB = InstrumentDB.getRef()
Пример #32
0
    def drumRythmSequence(self, instrumentName, nbeats, density, regularity):
        instrumentDB = InstrumentDB.getRef()
        rythmSequence = []
        binSelection = []
        downBeats = []
        upBeats = []
        beats = []
        countDown = 0
        onsetTime = None

        if instrumentDB.instNamed[
                instrumentName].instrumentRegister == Config.PUNCH:
            registerDensity = 0.5
            downBeatRecurence = 4
            downBeats = [
                x for x in GenerationConstants.DRUM_PUNCH_ACCENTS[nbeats]
            ]
            for downBeat in downBeats:
                upBeats.append(downBeat + Config.TICKS_PER_BEAT / 2)

        if instrumentDB.instNamed[
                instrumentName].instrumentRegister == Config.LOW:
            registerDensity = 1
            downBeatRecurence = 4
            downBeats = [
                x for x in GenerationConstants.DRUM_LOW_ACCENTS[nbeats]
            ]
            for downBeat in downBeats:
                upBeats.append(downBeat + Config.TICKS_PER_BEAT / 2)

        if instrumentDB.instNamed[
                instrumentName].instrumentRegister == Config.MID:
            registerDensity = .75
            downBeatRecurence = 1
            downBeats = [
                x for x in GenerationConstants.DRUM_MID_ACCENTS[nbeats]
            ]
            for downBeat in downBeats:
                upBeats.append(downBeat + Config.TICKS_PER_BEAT / 4)

        if instrumentDB.instNamed[
                instrumentName].instrumentRegister == Config.HIGH:
            registerDensity = 1.5
            downBeatRecurence = 1
            downBeats = [
                x for x in GenerationConstants.DRUM_HIGH_ACCENTS[nbeats]
            ]
            for downBeat in downBeats:
                upBeats.append(downBeat + Config.TICKS_PER_BEAT / 4)

        realDensity = density * registerDensity
        if realDensity > 1.:
            realDensity = 1.

        list = range(int(realDensity * len(downBeats)))
        for i in list:
            if random.random() < (regularity * downBeatRecurence
                                  ) and binSelection.count(1) < len(downBeats):
                binSelection.append(1)
            else:
                if binSelection.count(0) < len(downBeats):
                    binSelection.append(0)
                else:
                    binSelection.append(1)

        countDown = binSelection.count(1)

        length = len(downBeats) - 1
        for i in range(countDown):
            ran1 = random.randint(0, length)
            ran2 = random.randint(0, length)
            randMin = min(ran1, ran2)
            onsetTime = downBeats.pop(randMin)
            rythmSequence.append(onsetTime)
            length -= 1

        length = len(upBeats) - 1
        for i in range(len(binSelection) - countDown):
            ran1 = random.randint(0, length)
            ran2 = random.randint(0, length)
            randMin = min(ran1, ran2)
            onsetTime = upBeats.pop(randMin)
            rythmSequence.append(onsetTime)
            length -= 1

        rythmSequence.sort()
        return rythmSequence
Пример #33
0
    def __init__(self, handle):
        """Set up the HelloWorld activity."""
        activity.Activity.__init__(self, handle)

        # we do not have collaboration features
        # make the share option insensitive
        self.max_participants = 1

        # toolbar with the new toolbar redesign
        toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)

        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        keybord_labels = RadioToolButton()
        keybord_labels.props.icon_name = 'q_key'
        keybord_labels.props.group = keybord_labels
        keybord_labels.connect('clicked', self.set_keyboard_labels_cb)
        toolbar_box.toolbar.insert(keybord_labels, -1)

        notes_labels = RadioToolButton()
        notes_labels.props.icon_name = 'do_key'
        notes_labels.props.group = keybord_labels
        notes_labels.connect('clicked', self.set_notes_labels_cb)
        toolbar_box.toolbar.insert(notes_labels, -1)

        german_labels = RadioToolButton()
        german_labels.props.icon_name = 'c_key'
        german_labels.props.group = keybord_labels
        german_labels.connect('clicked', self.set_german_labels_cb)
        toolbar_box.toolbar.insert(german_labels, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        self.keyboard_letters = ['ZSXDCVGBHNJM', 'Q2W3ER5T6Y7U', 'I']

        notes = ['DO', 'DO#', 'RE', 'RE#', 'MI', 'FA', 'FA#', 'SOL',
                 'SOL#', 'LA', 'LA#', 'SI']
        self.notes_labels = [notes, notes, ['DO']]

        german_notes = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G',
                        'G#', 'A', 'A#', 'B']

        self.german_labels = [german_notes, german_notes, ['C']]

        self.piano = PianoKeyboard(octaves=2, add_c=True,
                                   labels=self.keyboard_letters)

        # init csound
        self.instrumentDB = InstrumentDB.getRef()
        self.firstTime = False
        self.playing = False
        self.csnd = new_csound_client()
        self.timeout_ms = 50
        self.instVolume = 50
        self.drumVolume = 0.5
        self.instrument = 'piano'
        self.regularity = 0.75
        self.beat = 4
        self.reverb = 0.1
        self.tempo = Config.PLAYER_TEMPO
        self.beatDuration = 60.0 / self.tempo
        self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0
        #self.rythmInstrument = 'drum1kit'
        #self.csnd.load_drumkit(self.rythmInstrument)
        self.sequencer = MiniSequencer(self.recordStateButton,
                                       self.recordOverSensitivity)
        self.loop = Loop(self.beat, math.sqrt(self.instVolume * 0.01))

        self.muteInst = False
        self.csnd.setTempo(self.tempo)
        self.noteList = []
        time.sleep(0.001)  # why?
        for i in range(21):
            self.csnd.setTrackVolume(100, i)

        for i in range(10):
            r = str(i + 1)
            self.csnd.load_instrument('guidice' + r)

        self.volume = 100
        self.csnd.setMasterVolume(self.volume)

        self.enableKeyboard()
        self.setInstrument(self.instrument)

        self.connect('key-press-event', self.onKeyPress)
        self.connect('key-release-event', self.onKeyRelease)
        # finish csount init

        self.piano.connect('key_pressed', self.__key_pressed_cb)
        self.piano.connect('key_released', self.__key_released_cb)
        vbox = Gtk.VBox()
        vbox.set_homogeneous(False)
        self.load_instruments()
        vbox.pack_end(self.piano, True, True, 0)
        self.scrolled = Gtk.ScrolledWindow()
        vbox.pack_start(self.scrolled, False, False, 0)
        self.scrolled.add(self.instruments_iconview)
        vbox.show_all()
        self.set_canvas(vbox)
        piano_height = Gdk.Screen.width() / 2
        self.scrolled.set_size_request(
            -1, Gdk.Screen.height() - piano_height - style.GRID_CELL_SIZE)
        self.connect('size-allocate', self.__allocate_cb)
Пример #34
0
def generator(instrument, nbeats, density, regularity, reverbSend):

    instrumentDB = InstrumentDB.getRef()
    makeRythm = GenRythm()

    noteDuration = GenerationConstants.DOUBLE_TICK_DUR / 2
    trackId = 5
    pan = 0.5
    attack = 0.005
    decay = 0.095
    filterType = 0
    filterCutoff = 1000
    tied = False
    mode = 'mini'

    def makePitchSequence(length, drumPitch):
        pitchSequence = []
        append = pitchSequence.append
        list = range(length)
        max = len(drumPitch) - 1
        for i in list:
            append(drumPitch[random.randint(0, max)])
        return pitchSequence

    def makeGainSequence(onsetList):
        gainSequence = []
        append = gainSequence.append
        for onset in onsetList:
            if onset == 0:
                gain = random.uniform(
                    GenerationConstants.GAIN_MID_MAX_BOUNDARY,
                    GenerationConstants.GAIN_MAX_BOUNDARY)
            elif (onset % Config.TICKS_PER_BEAT) == 0:
                gain = random.uniform(
                    GenerationConstants.GAIN_MID_MIN_BOUNDARY,
                    GenerationConstants.GAIN_MID_MAX_BOUNDARY)
            else:
                gain = random.uniform(
                    GenerationConstants.GAIN_MIN_BOUNDARY,
                    GenerationConstants.GAIN_MID_MIN_BOUNDARY)
            append(gain)
        return gainSequence

    def pageGenerate(regularity, drumPitch):
        barLength = Config.TICKS_PER_BEAT * nbeats

        #print 'pageGenerate drumPitch[0] ', drumPitch[0]
        currentInstrument = instrumentDB.instNamed[instrument].kit[
            drumPitch[0]]  #.name

        rythmSequence = makeRythm.drumRythmSequence(currentInstrument, nbeats,
                                                    density, regularity)
        pitchSequence = makePitchSequence(len(rythmSequence), drumPitch)
        gainSequence = makeGainSequence(rythmSequence)

        trackNotes = []
        list = range(len(rythmSequence))
        for i in list:
            trackNotes.append(
                CSoundNote(rythmSequence[i], pitchSequence[i], gainSequence[i],
                           pan, noteDuration, trackId,
                           instrumentDB.instNamed[instrument].instrumentId,
                           attack, decay, reverbSend, filterType, filterCutoff,
                           tied, mode))
        return trackNotes

##################################################################################
#  begin generate()

    if regularity > 0.75:
        streamOfPitch = GenerationConstants.DRUM_COMPLEXITY1
    elif regularity > 0.5:
        streamOfPitch = GenerationConstants.DRUM_COMPLEXITY2
    elif regularity > 0.25:
        streamOfPitch = GenerationConstants.DRUM_COMPLEXITY3
    else:
        streamOfPitch = GenerationConstants.DRUM_COMPLEXITY4

    trackNotes = []
    for drumPitch in streamOfPitch:
        trackNotes.append(pageGenerate(regularity, drumPitch))
    return trackNotes
Пример #35
0
 def __init__(self):
     self.instrumentDB = InstrumentDB.getRef()
Пример #36
0
    def drumRythmSequence(self, instrumentName, nbeats, density, regularity ):
        instrumentDB = InstrumentDB.getRef()
        rythmSequence = []
        binSelection = []
        downBeats = []
        upBeats = []
        beats = []
        countDown = 0
        onsetTime = None

        if instrumentDB.instNamed[instrumentName].instrumentRegister == Config.PUNCH:
            registerDensity = 0.5
            downBeatRecurence = 4
            downBeats = [x for x in GenerationConstants.DRUM_PUNCH_ACCENTS[ nbeats ]]
            for downBeat in downBeats:
                upBeats.append( downBeat + Config.TICKS_PER_BEAT / 2 )

        if instrumentDB.instNamed[instrumentName].instrumentRegister == Config.LOW:
            registerDensity =1
            downBeatRecurence = 4
            downBeats = [x for x in GenerationConstants.DRUM_LOW_ACCENTS[ nbeats ]]
            for downBeat in downBeats:
                upBeats.append( downBeat + Config.TICKS_PER_BEAT / 2 )

        if instrumentDB.instNamed[instrumentName].instrumentRegister == Config.MID:
            registerDensity = .75
            downBeatRecurence = 1
            downBeats = [x for x in GenerationConstants.DRUM_MID_ACCENTS[ nbeats ]]
            for downBeat in downBeats:
                upBeats.append( downBeat + Config.TICKS_PER_BEAT / 4 )

        if instrumentDB.instNamed[instrumentName].instrumentRegister == Config.HIGH:
            registerDensity = 1.5
            downBeatRecurence = 1
            downBeats = [x for x in GenerationConstants.DRUM_HIGH_ACCENTS[ nbeats ]]
            for downBeat in downBeats:
                upBeats.append( downBeat + Config.TICKS_PER_BEAT / 4 )

        realDensity = density * registerDensity
        if realDensity > 1.:
            realDensity = 1.

        list = range( int( realDensity  * len( downBeats ) ) )
        for i in list:
            if random.random() < ( regularity * downBeatRecurence ) and binSelection.count( 1 ) < len( downBeats ):
                binSelection.append( 1 )
            else:
                if binSelection.count( 0 ) < len( downBeats ):
                    binSelection.append( 0 )
                else:
                    binSelection.append( 1 )

        countDown = binSelection.count( 1 )

        length = len(downBeats) - 1
        for i in range( countDown ):
            ran1 = random.randint(0, length)
            ran2 = random.randint(0, length)
            randMin = min(ran1, ran2)
            onsetTime = downBeats.pop(randMin)
            rythmSequence.append( onsetTime )
            length -= 1

        length = len(upBeats) - 1
        for i in range( len( binSelection ) - countDown ):
            ran1 = random.randint(0, length)
            ran2 = random.randint(0, length)
            randMin = min(ran1, ran2)
            onsetTime = upBeats.pop(randMin)
            rythmSequence.append( onsetTime )
            length -= 1

        rythmSequence.sort()
        return rythmSequence
Пример #37
0
    def __init__(self, handle):
        """Set up the HelloWorld activity."""
        activity.Activity.__init__(self, handle)

        # we do not have collaboration features
        # make the share option insensitive
        self.max_participants = 1

        # toolbar with the new toolbar redesign
        toolbar_box = ToolbarBox()

        activity_button = ActivityToolbarButton(self)
        toolbar_box.toolbar.insert(activity_button, 0)

        toolbar_box.toolbar.insert(Gtk.SeparatorToolItem(), -1)

        keybord_labels = RadioToolButton()
        keybord_labels.props.icon_name = 'q_key'
        keybord_labels.props.group = keybord_labels
        keybord_labels.connect('clicked', self.set_keyboard_labels_cb)
        toolbar_box.toolbar.insert(keybord_labels, -1)

        notes_labels = RadioToolButton()
        notes_labels.props.icon_name = 'do_key'
        notes_labels.props.group = keybord_labels
        notes_labels.connect('clicked', self.set_notes_labels_cb)
        toolbar_box.toolbar.insert(notes_labels, -1)

        ti_notes_labels = RadioToolButton()
        ti_notes_labels.props.icon_name = 'ti_key'
        ti_notes_labels.props.group = keybord_labels
        ti_notes_labels.connect('clicked', self.set_ti_notes_labels_cb)
        toolbar_box.toolbar.insert(ti_notes_labels, -1)

        german_labels = RadioToolButton()
        german_labels.props.icon_name = 'c_key'
        german_labels.props.group = keybord_labels
        german_labels.connect('clicked', self.set_german_labels_cb)
        toolbar_box.toolbar.insert(german_labels, -1)

        no_labels = RadioToolButton()
        no_labels.props.icon_name = 'edit-clear'
        no_labels.props.group = keybord_labels
        no_labels.connect('clicked', self.set_keyboard_no_labels_cb)
        toolbar_box.toolbar.insert(no_labels, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = False
        separator.set_expand(True)
        toolbar_box.toolbar.insert(separator, -1)

        stop_button = StopButton(self)
        toolbar_box.toolbar.insert(stop_button, -1)
        stop_button.show()

        self.set_toolbar_box(toolbar_box)
        toolbar_box.show_all()

        self.keyboard_letters = ['ZSXDCVGBHNJM', 'Q2W3ER5T6Y7U', 'I']

        notes = [
            'DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA',
            ['FA#', 'SOLb'], 'SOL', ['SOL#', 'LAb'], 'LA', ['LA#', 'SIb'], 'SI'
        ]
        self.notes_labels = [notes, notes, ['DO']]

        # some countries use TI instead of SI
        ti_notes = [
            'DO', ['DO#', 'REb'], 'RE', ['RE#', 'MIb'], 'MI', 'FA',
            ['FA#', 'SOLb'], 'SOL', ['SOL#', 'LAb'], 'LA', ['LA#', 'TIb'], 'TI'
        ]
        self.ti_notes_labels = [ti_notes, ti_notes, ['DO']]

        german_notes = [
            'C', ['C#', 'Db'], 'D', ['D#', 'Eb'], 'E', 'F', ['F#', 'Gb'], 'G',
            ['G#', 'Ab'], 'A', ['A#', 'Bb'], 'B'
        ]

        self.german_labels = [german_notes, german_notes, ['C']]

        self.piano = PianoKeyboard(octaves=2,
                                   add_c=True,
                                   labels=self.keyboard_letters)

        # init csound
        self.instrumentDB = InstrumentDB.getRef()
        self.firstTime = False
        self.playing = False
        self.csnd = new_csound_client()
        self.timeout_ms = 50
        self.instVolume = 50
        self.drumVolume = 0.5
        self.instrument = 'piano'
        self.regularity = 0.75
        self.beat = 4
        self.reverb = 0.1
        self.tempo = Config.PLAYER_TEMPO
        self.beatDuration = 60.0 / self.tempo
        self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0
        #self.rythmInstrument = 'drum1kit'
        #self.csnd.load_drumkit(self.rythmInstrument)
        self.sequencer = MiniSequencer(self.recordStateButton,
                                       self.recordOverSensitivity)
        self.loop = Loop(self.beat, math.sqrt(self.instVolume * 0.01))

        self.muteInst = False
        self.csnd.setTempo(self.tempo)
        self.noteList = []
        time.sleep(0.001)  # why?
        for i in range(21):
            self.csnd.setTrackVolume(100, i)

        for i in range(10):
            r = str(i + 1)
            self.csnd.load_instrument('guidice' + r)

        self.volume = 100
        self.csnd.setMasterVolume(self.volume)

        self.enableKeyboard()
        self.setInstrument(self.instrument)

        self.connect('key-press-event', self.onKeyPress)
        self.connect('key-release-event', self.onKeyRelease)
        # finish csount init

        self.piano.connect('key_pressed', self.__key_pressed_cb)
        self.piano.connect('key_released', self.__key_released_cb)
        vbox = Gtk.VBox()
        vbox.set_homogeneous(False)
        self.load_instruments()
        vbox.pack_end(self.piano, True, True, 0)
        self.scrolled = Gtk.ScrolledWindow()
        vbox.pack_start(self.scrolled, False, False, 0)
        self.scrolled.add(self.instruments_iconview)
        vbox.show_all()
        self.set_canvas(vbox)
        piano_height = Gdk.Screen.width() / 2
        self.scrolled.set_size_request(
            -1,
            Gdk.Screen.height() - piano_height - style.GRID_CELL_SIZE)
        self.connect('size-allocate', self.__allocate_cb)
Пример #38
0
    def __init__(self, activity):

        Gtk.EventBox.__init__(self)

        self.instrumentPanel = None
        self.activity = activity

        self.instrumentDB = InstrumentDB.getRef()
        self.firstTime = False
        self.playing = False
        self.csnd = new_csound_client()
        self.timeout_ms = 50
        self.instVolume = 50
        self.drumVolume = 0.5
        self.instrument = 'sarangi'
        self.regularity = 0.75
        self.beat = 4
        self.reverb = 0.1
        self.tempo = Config.PLAYER_TEMPO
        self.beatDuration = 60.0 / self.tempo
        self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0
        self.rythmInstrument = 'drum1kit'
        self.csnd.load_drumkit(self.rythmInstrument)
        self.muteInst = False
        
        self.drumFillin = Fillin(
            self.beat, self.tempo,
            self.rythmInstrument,
            self.reverb, self.drumVolume)

        self.sequencer = MiniSequencer(
            self.recordStateButton,
            self.recordOverSensitivity)
            
        self.loop = Loop(self.beat, sqrt(
            self.instVolume * 0.01))
        self.csnd.setTempo(self.tempo)
        self.noteList = []
        time.sleep(0.001) # why?
        
        for i in range(21):
            self.csnd.setTrackVolume(100, i)

        for i in  range(10):
            r = str(i + 1)
            self.csnd.load_instrument('guidice' + r)

        self.volume = 100
        self.csnd.setMasterVolume(self.volume)
        self.sequencer.beat = self.beat
        self.loop.beat = self.beat

        # Descripcion: Contenedor Principal
        self.mainWindowBox = Gtk.HBox()
        
        self.leftBox = Gtk.VBox()
        self.rightBox = Gtk.VBox()
        
        # Descripcion: Esto está alrevés, self.rightBox está a la izquierda.
        self.mainWindowBox.pack_start(self.rightBox, False, False, 0)
        
        # Descripcion: Esto está alrevés, self.leftBox está a la derecha.
        self.mainWindowBox.pack_start(self.leftBox, True, True, 0)
        
        self.add(self.mainWindowBox)

        self.enableKeyboard()
        self.setInstrument(self.instrument)

        self.connect('key-press-event', self.onKeyPress)
        self.connect('key-release-event', self.onKeyRelease)

        self.drawGeneration()
        self.show_all()
        
        if 'a good idea' == True:
            self.playStartupSound()

        self.beatPickup = True

        self.heartbeatStart = time.time()
        self.syncQueryStart = {}
        self.syncTimeout = None

        self.network = Net.Network()
        self.network.addWatcher(
            self.networkStatusWatcher)
        
        self.network.connectMessage(
            Net.HT_SYNC_REPLY,
            self.processHT_SYNC_REPLY)
            
        self.network.connectMessage(
            Net.HT_TEMPO_UPDATE,
            self.processHT_TEMPO_UPDATE)
            
        self.network.connectMessage(
            Net.PR_SYNC_QUERY,
            self.processPR_SYNC_QUERY)
            
        self.network.connectMessage(
            Net.PR_TEMPO_QUERY,
            self.processPR_TEMPO_QUERY)
            
        self.network.connectMessage(
            Net.PR_REQUEST_TEMPO_CHANGE,
            self.processPR_REQUEST_TEMPO_CHANGE)

        # data packing classes
        self.packer = xdrlib.Packer()
        self.unpacker = xdrlib.Unpacker("")

        #-- handle forced networking ---------------------------------------
        if self.network.isHost():
            self.updateSync()
            self.syncTimeout = GObject.timeout_add(
                1000, self.updateSync)
            
        elif self.network.isPeer():
            self.sendTempoQuery()
            self.syncTimeout = GObject.timeout_add(
                1000, self.updateSync)
        
        #if not Config.HAVE_TOOLBOX:
        #    self.activity.connect("shared", self.shared)

        if os.path.isfile("FORCE_SHARE"):    # HOST
            r = random.random()
            #print "::::: Sharing as TTDBG%f :::::" % r
            #self.activity.set_title(_("TTDBG%f" % r))
            print "::::: Sharing as TamTam :::::"
            self.activity.set_title(_("TamTam"))
            self.activity.share()
            
        elif self.activity.shared_activity: # PEER
            self.activity.shared_activity.connect(
                "buddy-joined", self.buddy_joined)
                
            self.activity.shared_activity.connect(
                "buddy-left", self.buddy_left)
                
            self.activity.connect("joined", self.joined)
            self.network.setMode(Net.MD_WAIT)
import random

import common.Util.InstrumentDB as InstrumentDB
import common.Config as Config
from common.Util.CSoundNote import CSoundNote
from common.Generation.GenerationConstants import GenerationConstants
from GenRythm import GenRythm

instrumentDB = InstrumentDB.getRef()

def generator( instrument, nbeats, density, regularity, reverbSend ):

    makeRythm = GenRythm()

    noteDuration = GenerationConstants.DOUBLE_TICK_DUR / 2
    trackId = 0
    pan = 0.5
    attack = 0.005
    decay = 0.095
    filterType = 0
    filterCutoff = 1000
    tied = False
    mode = 'mini'

    def makePitchSequence(length, drumPitch):
        pitchSequence = []
        append = pitchSequence.append
        list = range(length)
        max = len(drumPitch) - 1
        for i in list:
            append(drumPitch[ random.randint( 0, max ) ] )
Пример #40
0
 def __init__(self, noteDB=None, jam=None):
     self.noteDB = noteDB
     self.jam = jam
     self.csnd = new_csound_client()
     self.pid = {}  #stream_pid : local_pid
     self.instrumentDB = InstrumentDB.getRef()
Пример #41
0
    def __init__(self, activity):
        GObject.GObject.__init__(self)

        self.activity = activity

        self.instrumentDB = InstrumentDB.getRef()
        self.noteDB = NoteDB.NoteDB()

        #-- initial settings ----------------------------------
        self.tempo = Config.PLAYER_TEMPO
        self.beatDuration = 60.0 / self.tempo
        self.ticksPerSecond = Config.TICKS_PER_BEAT * self.tempo / 60.0
        self.volume = 0.5

        self.csnd = new_csound_client()
        for i in range(0, 9):
            self.csnd.setTrackVolume(100, i)
        # csnd expects a range 0-100 for now
        self.csnd.setMasterVolume(self.volume * 100)
        self.csnd.setTempo(self.tempo)

        self.muted = False

        #-- Drawing -------------------------------------------
        def darken(hex):
            hexToDec = {
                "0": 0,
                "1": 1,
                "2": 2,
                "3": 3,
                "4": 4,
                "5": 5,
                "6": 6,
                "7": 7,
                "8": 8,
                "9": 9,
                "A": 10,
                "B": 11,
                "C": 12,
                "D": 13,
                "E": 14,
                "F": 15,
                "a": 10,
                "b": 11,
                "c": 12,
                "d": 13,
                "e": 14,
                "f": 15
            }
            r = int(0.7 * (16 * hexToDec[hex[1]] + hexToDec[hex[2]]))
            g = int(0.7 * (16 * hexToDec[hex[3]] + hexToDec[hex[4]]))
            b = int(0.7 * (16 * hexToDec[hex[5]] + hexToDec[hex[6]]))
            return r * 256, g * 256, b * 256

        def lighten(hex):
            hexToDec = {
                "0": 0,
                "1": 1,
                "2": 2,
                "3": 3,
                "4": 4,
                "5": 5,
                "6": 6,
                "7": 7,
                "8": 8,
                "9": 9,
                "A": 10,
                "B": 11,
                "C": 12,
                "D": 13,
                "E": 14,
                "F": 15,
                "a": 10,
                "b": 11,
                "c": 12,
                "d": 13,
                "e": 14,
                "f": 15
            }
            r = 255 - int(0.7 * (255 -
                                 (16 * hexToDec[hex[1]] + hexToDec[hex[2]])))
            g = 255 - int(0.7 * (255 -
                                 (16 * hexToDec[hex[3]] + hexToDec[hex[4]])))
            b = 255 - int(0.7 * (255 -
                                 (16 * hexToDec[hex[5]] + hexToDec[hex[6]])))
            return r * 256, g * 256, b * 256

        xoColor = profile.get_color()
        if not xoColor:
            xoColorKey = ("#8D8D8D,#FFDDEA")
            xoColor = XoColor(xoColorKey)

        # colors in Config and in XoColor are strings,
        # the colors in style are style.Color, transform all to Gdk.Color
        self.colors = {"bg": CairoUtil.get_gdk_color(Config.PANEL_BCK_COLOR),
               "black": style.COLOR_BLACK.get_gdk_color(),
               #"Picker_Bg": colormap.alloc_color("#404040"),
               #"Picker_Bg_Inactive": colormap.alloc_color("#808080"),
               "Picker_Bg": style.COLOR_TOOLBAR_GREY.get_gdk_color(),
               "Picker_Bg_Inactive": style.COLOR_BUTTON_GREY.get_gdk_color(),
               "Picker_Fg": style.COLOR_WHITE.get_gdk_color(),
               "Border_Active": \
                        CairoUtil.get_gdk_color(xoColor.get_stroke_color()),
               "Border_Inactive": CairoUtil.get_gdk_color("#8D8D8D"),
               "Border_Highlight": CairoUtil.get_gdk_color("#FFFFFF"),
               "Bg_Active": CairoUtil.get_gdk_color(xoColor.get_fill_color()),
               "Bg_Inactive": CairoUtil.get_gdk_color("#DBDBDB"),
               "Preview_Note_Fill": CairoUtil.get_gdk_color(Config.BG_COLOR),
               "Preview_Note_Border": CairoUtil.get_gdk_color(Config.FG_COLOR),
               "Preview_Note_Selected": style.COLOR_WHITE.get_gdk_color(),
                # TODO: lighten here can be removed, check if is used in other
                # places
               "Note_Fill_Active": Gdk.Color(*lighten("#590000")),
               # base "Border_Active"
               "Note_Fill_Inactive": Gdk.Color(*lighten("#8D8D8D")),
               # base "Border_Inactive"
               "Beat_Line": CairoUtil.get_gdk_color("#959595")}
        self.colors["Note_Border_Active"] = self.colors["Border_Active"]
        self.colors["Note_Border_Inactive"] = self.colors["Border_Inactive"]

        self.sampleNoteHeight = 7

        self.sampleBg = cairo.ImageSurface.create_from_png(
            imagefile('sampleBG.png'))
        self.loopPitchOffset = 4
        self.loopTickOffset = 13
        self.pitchPerPixel = float(Config.NUMBER_OF_POSSIBLE_PITCHES - 1) / \
            (Block.Loop.HEIGHT - 2 * self.loopPitchOffset - \
                 self.sampleNoteHeight)
        self.pixelsPerPitch = float(Block.Loop.HEIGHT - \
            2 * self.loopPitchOffset - self.sampleNoteHeight) / \
            (Config.MAXIMUM_PITCH - Config.MINIMUM_PITCH)
        self.pixelsPerTick = Block.Loop.BEAT / float(Config.TICKS_PER_BEAT)
        self.ticksPerPixel = 1.0 / self.pixelsPerTick

        #-- Instruments ---------------------------------------
        self.instrumentImage = {}
        self.instrumentImageActive = {}
        for inst in self.instrumentDB.getSet("All"):
            if not inst.kitStage:
                self.prepareInstrumentImage(inst.instrumentId, inst.img)
            self.csnd.load_instrument(inst.name)

        #-- Loop Images ---------------------------------------
        self.loopImage = {}  # get filled in through updateLoopImage
        self.loopImageActive = {}

        #-- Key Images ----------------------------------------
        self.keyImage = {}
        self.keyImageActive = {}
        # use hardware key codes to work on any keyboard layout (hopefully)
        self.valid_shortcuts = {
            18: "9",
            19: "0",
            20: "-",
            21: "=",
            32: "O",
            33: "P",
            34: "[",
            35: "]",
            47: ";",
            48: "'",
            51: "\\",
            60: ".",
            61: "/",
            None: " "
        }
        for key in self.valid_shortcuts.keys():
            self.prepareKeyImage(key)

        #-- Toolbars ------------------------------------------

        self.jamToolbar = JamToolbar(self)
        jam_toolbar_button = ToolbarButton(label=_('Jam'),
                                           page=self.jamToolbar,
                                           icon_name='voltemp')
        self.jamToolbar.show()
        jam_toolbar_button.show()
        self.activity.toolbar_box.toolbar.insert(jam_toolbar_button, -1)

        self.beatToolbar = BeatToolbar(self)
        beat_toolbar_button = ToolbarButton(label=_('Beat'),
                                            page=self.beatToolbar,
                                            icon_name='heart')
        self.beatToolbar.show()
        beat_toolbar_button.show()
        self.activity.toolbar_box.toolbar.insert(beat_toolbar_button, -1)

        self.desktopToolbar = DesktopToolbar(self)
        desktop_toolbar_button = ToolbarButton(label=_('Desktop'),
                                               page=self.desktopToolbar,
                                               icon_name='jam-presets-list')
        self.desktopToolbar.show()
        desktop_toolbar_button.show()
        self.activity.toolbar_box.toolbar.insert(desktop_toolbar_button, -1)

        if Config.FEATURES_MIC or Config.FEATURES_NEWSOUNDS:
            self.recordToolbar = RecordToolbar(self)
            record_toolbar_button = ToolbarButton(label=_('Record'),
                                                  page=self.recordToolbar,
                                                  icon_name='microphone')
            self.recordToolbar.show()
            record_toolbar_button.show()
            self.activity.toolbar_box.toolbar.insert(record_toolbar_button, -1)

        separator = Gtk.SeparatorToolItem()
        separator.props.draw = True
        separator.set_expand(False)
        self.activity.toolbar_box.toolbar.insert(separator, -1)
        separator.show()

        common_playback_buttons(self.activity.toolbar_box.toolbar, self)

        #-- GUI -----------------------------------------------
        if True:  # GUI
            self.modify_bg(Gtk.StateType.NORMAL, self.colors["bg"])

            self.GUI = {}
            self.GUI["mainVBox"] = Gtk.VBox()
            self.add(self.GUI["mainVBox"])

            #-- Desktop -------------------------------------------
            self.desktop = self.GUI["desktop"] = Desktop(self)
            self.GUI["mainVBox"].pack_start(self.GUI["desktop"], True, True, 0)

            #-- Bank ----------------------------------------------
            separator = Gtk.Label(label=" ")
            separator.set_size_request(-1, style.TOOLBOX_SEPARATOR_HEIGHT)
            self.GUI["mainVBox"].pack_start(separator, False, True, 0)
            self.GUI["notebook"] = Gtk.Notebook()
            self.GUI["notebook"].set_scrollable(True)
            self.GUI["notebook"].modify_bg(Gtk.StateType.NORMAL,
                                           self.colors["Picker_Bg"])
            self.GUI["notebook"].modify_bg(Gtk.StateType.ACTIVE,
                                           self.colors["Picker_Bg_Inactive"])
            # TODO gtk3 no available anymore?
            #self.GUI["notebook"].props.tab_vborder = style.TOOLBOX_TAB_VBORDER
            #self.GUI["notebook"].props.tab_hborder = style.TOOLBOX_TAB_HBORDER
            self.GUI["notebook"].set_size_request(-1, scale(160))
            self.GUI["notebook"].connect("switch-page", self.setPicker)
            self.GUI["mainVBox"].pack_start(self.GUI["notebook"], False, False,
                                            0)
            self.pickers = {}
            self.pickerScroll = {}
            for type in [Picker.Instrument, Picker.Drum, Picker.Loop]:
                self.pickers[type] = type(self)

            def prepareLabel(name):
                label = Gtk.Label(label=Tooltips.categories.get(name) or name)
                label.set_alignment(0.0, 0.5)
                label.modify_fg(Gtk.StateType.NORMAL, self.colors["Picker_Fg"])
                label.modify_fg(Gtk.StateType.ACTIVE, self.colors["Picker_Fg"])
                return label

            self.GUI["notebook"].append_page(self.pickers[Picker.Drum],
                                             prepareLabel(_("Drum Kits")))
            self.GUI["notebook"].append_page(self.pickers[Picker.Loop],
                                             prepareLabel(_("Loops")))

            sets = self.instrumentDB.getLabels()[:]
            sets.sort()
            for set in sets:
                page = Gtk.HBox()
                page.set = set
                self.GUI["notebook"].append_page(page, prepareLabel(set))

            self.show_all()

            self.GUI["notebook"].set_current_page(0)

        #-- Keyboard ------------------------------------------
        self.key_dict = {}
        self.nextTrack = 2
        self.keyboardListener = None
        self.recordingNote = None

        self.keyMap = {}

        # default instrument
        self._updateInstrument(
            self.instrumentDB.instNamed["kalimba"].instrumentId, 0.5)
        self.instrumentStack = []

        # metronome
        page = NoteDB.Page(1, local=False)
        self.metronomePage = self.noteDB.addPage(-1, page)
        self.metronome = False

        #-- Drums ---------------------------------------------
        self.drumLoopId = None
        # use dummy values for now
        self.drumFillin = Fillin(
            2, 100, self.instrumentDB.instNamed["drum1kit"].instrumentId, 0, 1)

        #-- Desktops ------------------------------------------
        self.curDesktop = None
        # copy preset desktops
        path = Config.FILES_DIR + "/Desktops/"
        filelist = os.listdir(path)
        for file in filelist:
            shutil.copyfile(path + file, Config.TMP_DIR + '/' + file)

        #-- Network -------------------------------------------
        self.network = Net.Network()
        self.network.addWatcher(self.networkStatusWatcher)
        self.network.connectMessage(Net.HT_SYNC_REPLY,
                                    self.processHT_SYNC_REPLY)
        self.network.connectMessage(Net.HT_TEMPO_UPDATE,
                                    self.processHT_TEMPO_UPDATE)
        self.network.connectMessage(Net.PR_SYNC_QUERY,
                                    self.processPR_SYNC_QUERY)
        self.network.connectMessage(Net.PR_TEMPO_QUERY,
                                    self.processPR_TEMPO_QUERY)
        self.network.connectMessage(Net.PR_REQUEST_TEMPO_CHANGE,
                                    self.processPR_REQUEST_TEMPO_CHANGE)

        # sync
        self.syncQueryStart = {}
        self.syncTimeout = None
        self.heartbeatLoop = self.csnd.loopCreate()
        self.syncBeats = 4
        self.syncTicks = self.syncBeats * Config.TICKS_PER_BEAT
        self.offsetTicks = 0  # offset from the true heartbeat
        self.csnd.loopSetNumTicks(self.syncTicks * HEARTBEAT_BUFFER,
                                  self.heartbeatLoop)
        self.heartbeatStart = time.time()
        self.csnd.loopStart(self.heartbeatLoop)
        self.curBeat = 0
        self.beatWheelTimeout = GObject.timeout_add(100, self.updateBeatWheel)

        # data packing classes
        self.packer = xdrlib.Packer()
        self.unpacker = xdrlib.Unpacker("")

        # handle forced networking
        if self.network.isHost():
            self.updateSync()
            self.syncTimeout = GObject.timeout_add(1000, self.updateSync)
        elif self.network.isPeer():
            self.sendTempoQuery()
            self.syncTimeout = GObject.timeout_add(1000, self.updateSync)

        self.activity.connect("shared", self.shared)

        if self.activity.shared_activity:  # PEER
            self.activity.shared_activity.connect("buddy-joined",
                                                  self.buddy_joined)
            self.activity.shared_activity.connect("buddy-left",
                                                  self.buddy_left)
            self.activity.connect("joined", self.joined)
            self.network.setMode(Net.MD_WAIT)

        #-- Final Set Up --------------------------------------
        self.setVolume(self.volume)
        self.setTempo(self.tempo)
        #self.activity.toolbar_box.set_current_toolbar(1)  # JamToolbar
        self.setDesktop(0, True)
Пример #42
0
 def __init__(self):
     self.instrumentDB = InstrumentDB.getRef()