Exemple #1
0
 def _setup_background(self):
     self._background = BackgroundComponent(name='Background')
     self._background.layer = Layer(
         priority=3,
         dials=self._dial_matrix,
         dial_buttons=self._dial_button_matrix.submatrix[:, :])
     self._background.set_enabled(True)
 def _create_background(self):
     self._background = BackgroundComponent(
         name=u'Background',
         is_enabled=False,
         add_nop_listeners=True,
         layer=Layer(clear_button=u'clear_button',
                     duplicate_button=u'duplicate_button',
                     quantize_button=u'quantize_button',
                     scene_launch_buttons=u'scene_launch_buttons',
                     priority=-1) +
         Layer(
             duplicate_button_with_shift=u'duplicate_button_with_shift',
             track_select_buttons_with_shift=
             u'track_select_buttons_with_shift',
             up_button_with_shift=u'up_button_with_shift',
             down_button_with_shift=u'down_button_with_shift',
             left_button_with_shift=u'left_button_with_shift',
             right_button_with_shift=u'right_button_with_shift',
             double_button=u'duplicate_button_with_shift',
             clear_button_with_shift=u'clear_button_with_shift',
             volume_button_with_shift=u'volume_button_with_shift',
             pan_button_with_shift=u'pan_button_with_shift',
             sends_button_with_shift=u'sends_button_with_shift',
             device_button_with_shift=u'device_button_with_shift',
             stop_clip_button_with_shift=u'stop_clip_button_with_shift',
             fixed_length_button_with_shift=u'fixed_length_button_with_shift'
         ))
     self._background.set_enabled(True)
Exemple #3
0
 def _create_background(self):
     self._background = BackgroundComponent(
         name=b'Background',
         is_enabled=False,
         add_nop_listeners=True,
         layer=Layer(**{name: name
                        for name in BANK_BUTTON_NAMES}))
     self._background.set_enabled(True)
Exemple #4
0
 def _create_background(self):
     self._background = BackgroundComponent(
         name=u'Background',
         is_enabled=False,
         add_nop_listeners=True,
         layer=Layer(set_loop_button=u'set_loop_button',
                     nudge_button=u'nudge_button',
                     bank_button=u'bank_button'))
     self._background.set_enabled(True)
Exemple #5
0
 def _create_background(self):
     self._background = BackgroundComponent(
         name='Background',
         is_enabled=False,
         add_nop_listeners=True,
         layer=Layer(
             select_button_7_with_shift='select_buttons_with_shift_raw[3]',
             select_button_4_with_shift='select_buttons_with_shift_raw[4]',
             select_button_5_with_shift='select_buttons_with_shift_raw[5]',
             select_button_6_with_shift='select_buttons_with_shift_raw[6]'))
     self._background.set_enabled(True)
Exemple #6
0
 def _setup_background(self):
     self._background = BackgroundComponent(name='Background')
     self._background.layer = Layer(
         priority=3,
         matrix=self._matrix.submatrix[:, :],
         faders=self._fader_matrix.submatrix[:, :],
         left_knobs=self._knob_left_matrix.submatrix[:, :],
         right_knobs=self._knob_right_matrix.submatrix[:, :],
         dials=self._dial_matrix,
         dial_buttons=self._dial_button_matrix.submatrix[:, :],
         keys=self._key_matrix.submatrix[:, :])
     self._background.set_enabled(True)
Exemple #7
0
 def _setup_background(self):
     self._background = BackgroundComponent(name='Background')
     self._background.layer = Layer(
         priority=0,
         fader_matrix=self._fader_matrix,
         top_buttons=self._top_buttons,
         bottom_buttons=self._bottom_buttons,
         dial_matrix=self._dial_matrix,
         side_dial_matrix=self._side_dial_matrix,
         encoder_button_matrix=self._encoder_button_matrix,
         grid_matrix=self._grid_matrix)
     self._background.set_enabled(True)
Exemple #8
0
 def _setup_background(self):
     self._background = BackgroundComponent(name='Background')
     self._background.layer = Layer(
         priority=3,
         matrix=self._matrix.submatrix[:, :],
         livid_button=self._livid,
         shift_l_button=self._shift_l,
         shift_r_button=self._shift_r,
         crossfader=self._crossfader,
         dial_matrix=self._dial_matrix.submatrix[:, :],
         menu_matrix=self._menu_matrix.submatrix[:, :],
         fader_matrix=self._fader_matrix.submatrix[:, :],
         button_matrix=self._button_matrix.submatrix[:, :])
     self._background.set_enabled(False)
 def _create_track_assign_button_modes(self):
     self._background = BackgroundComponent(name='Background')
     self._modes = ModesComponent(name='Track_Assign_Button_Modes', is_enabled=False)
     self._modes.add_mode('mute', [
      ExtendComboElementMode(combo_pairs=zip(self._elements.mute_buttons_raw, self._elements.track_assign_buttons_raw)),
      AddLayerMode(self._mixer, Layer(mute_color_controls='track_assign_color_controls'))])
     self._modes.add_mode('solo', [
      ExtendComboElementMode(combo_pairs=zip(self._elements.solo_buttons_raw, self._elements.track_assign_buttons_raw)),
      AddLayerMode(self._mixer, Layer(solo_color_controls='track_assign_color_controls'))])
     self._modes.add_mode('rec_arm', [
      ExtendComboElementMode(combo_pairs=zip(self._elements.arm_buttons_raw, self._elements.track_assign_buttons_raw)),
      AddLayerMode(self._mixer, Layer(arm_color_controls='track_assign_color_controls'))])
     self._modes.add_mode('clip_stop', [
      ExtendComboElementMode(combo_pairs=zip(self._elements.clip_stop_buttons_raw, self._elements.track_assign_buttons_raw)),
      AddLayerMode(self._session, Layer(stop_clip_color_controls='track_assign_color_controls'))])
     self._modes.add_mode('shift', [
      AddLayerMode(self._transport, Layer(metronome_color_control='track_assign_color_controls_raw[4]', clip_trigger_quantization_color_controls='physical_track_color_controls')),
      AddLayerMode(self._clip_actions, Layer(quantize_color_control='track_assign_color_controls_raw[0]')),
      LayerMode(self._background, Layer(button1='track_assign_color_controls_raw[1]', button2='track_assign_color_controls_raw[2]', button3='track_assign_color_controls_raw[3]', button5='track_assign_color_controls_raw[5]', button6='track_assign_color_controls_raw[6]', button7='track_assign_color_controls_raw[7]'))], behaviour=MomentaryBehaviour())
     self._modes.add_mode('assign_a', [
      AddLayerMode(self._mixer, Layer(assign_a_buttons='track_assign_buttons', assign_a_color_controls='track_assign_color_controls'))], behaviour=MomentaryBehaviour())
     self._modes.add_mode('assign_b', [
      AddLayerMode(self._mixer, Layer(assign_b_buttons='track_assign_buttons', assign_b_color_controls='track_assign_color_controls'))], behaviour=MomentaryBehaviour())
     self._modes.layer = Layer(mute_button='mute_button', solo_button='solo_button', rec_arm_button='rec_arm_button', clip_stop_button='clip_stop_button', shift_button='shift_button', assign_a_button='assign_a_button', assign_b_button='assign_b_button')
     self._modes.selected_mode = 'clip_stop'
Exemple #10
0
 def _create_clip_launch_background(self):
     self._clip_launch_background = BackgroundComponent(
         name=b'Background',
         is_enabled=False,
         add_nop_listeners=True,
         layer=Layer(clip_launch_button=self._clip_launch_button,
                     track_stop_button=self._track_stop_button,
                     priority=-1))
 def _create_background(self):
     self._background = BackgroundComponent(
         name='Background',
         is_enabled=False,
         add_nop_listeners=True,
         layer=Layer(
             secondary_up_button='secondary_up_button',
             secondary_down_button='secondary_down_button',
             device_select_button='device_select_button',
             unused_matrix=(
                 self._elements.device_select_matrix.submatrix[:, 1:]),
             pot_parameter_name_displays='pot_parameter_name_displays',
             pot_parameter_value_displays='pot_parameter_value_displays',
             fader_parameter_name_displays='fader_parameter_name_displays',
             fader_parameter_value_displays='fader_parameter_value_displays'
         ))
     self._background.set_enabled(True)
 def _init_background(self):
     self._background = BackgroundComponent(is_root=True)
     self._background.layer = self._create_background_layer()
     self._matrix_background = BackgroundComponent()
     self._matrix_background.set_enabled(False)
     self._matrix_background.layer = Layer(matrix='matrix')
     self._mod_background = ModifierBackgroundComponent(is_root=True)
     self._mod_background.layer = Layer(shift_button='shift_button', select_button='select_button', delete_button='delete_button', duplicate_button='duplicate_button', quantize_button='quantize_button')
	def _setup_background(self):
		self._background = BackgroundComponent(name = 'Background')
		self._background.layer = Layer(priority = 0, fader_matrix = self._fader_matrix, 
													top_buttons = self._top_buttons,
													bottom_buttons = self._bottom_buttons,
													dial_matrix = self._dial_matrix,
													side_dial_matrix = self._side_dial_matrix,
													encoder_button_matrix = self._encoder_button_matrix,
													grid_matrix = self._grid_matrix)
		self._background.set_enabled(True)
	def _setup_background(self):
		self._background = BackgroundComponent(name = 'Background')
		self._background.layer = Layer(priority = 3, matrix = self._matrix.submatrix[:,:],
													livid_button = self._livid,
													shift_l_button = self._shift_l,
													shift_r_button = self._shift_r,
													crossfader = self._crossfader,
													dial_matrix = self._dial_matrix.submatrix[:,:],
													menu_matrix = self._menu_matrix.submatrix[:,:],
													fader_matrix = self._fader_matrix.submatrix[:,:],
													button_matrix = self._button_matrix.submatrix[:,:])
		self._background.set_enabled(False)
Exemple #15
0
 def _create_components(self):
     super(Launchpad_X, self)._create_components()
     self._background = BackgroundComponent(name='Background',
                                            add_nop_listeners=True)
     self._session_layout_mode = partial(
         self._elements.layout_switch.send_value, sysex.SESSION_LAYOUT_BYTE)
     self._create_recording_modes()
     self._create_mixer_modes()
     self._create_session_modes()
     self._create_note_modes()
     self._create_main_modes()
     self._mixer.set_send_controls = nop
     self._Launchpad_X__on_layout_switch_value.subject = self._elements.layout_switch
 def _create_components(self):
     super(Launchkey_Mini_MK3, self)._create_components()
     self.register_slot(self._elements.incontrol_mode_switch, nop, 'value')
     self._background = BackgroundComponent(name='Background',
                                            add_nop_listeners=True)
     self._create_auto_arm()
     self._create_view_control()
     self._create_transport()
     self._create_device()
     self._create_drum_group()
     self._create_pot_modes()
     self._create_stop_solo_mute_modes()
     self._create_pad_modes()
     self._create_recording_modes()
Exemple #17
0
	def _setup_background(self):
		self._background = BackgroundComponent(name = 'Background')
		self._background.layer = Layer(priority = 3, dials = self._dial_matrix, dial_buttons = self._dial_button_matrix.submatrix[:,:])
		self._background.set_enabled(True)
Exemple #18
0
class Twister(LividControlSurface):
	__module__ = __name__
	__doc__ = " Monomodular controller script for Livid CNTRLR "


	_sysex_id = 8
	_model_name = 'Twister'
	_host_name = 'Twister'
	_version_check = 'b996'
	monomodular = None

	device_provider_class = ModDeviceProvider

	def __init__(self, *a, **k):
		super(Twister, self).__init__(*a, **k)
		self._skin = Skin(TwisterColors)
		self._device_selection_follows_track_selection = True
		with self.component_guard():
			self._setup_monobridge()
			self._setup_controls()
			#self._define_sysex()
			self._setup_background()
			self._setup_m4l_interface()
			self._setup_mod()
			self._setup_device_control()
			self._setup_modes()
		self._on_device_changed.subject = self.song
		self._on_selected_track_changed.subject = self.song.view
	

	def _initialize_script(self):
		super(Twister, self)._initialize_script()
		self._connected = True
	

	def _setup_controls(self):
		is_momentary = True
		optimized = True
		resource = PrioritizedResource
		self._encoder = [CodecEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = TWISTER_DIALS[index], name = 'Encoder_' + str(index), num = TWISTER_DIALS[index], script = self, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(16)] 
		self._encoder_button = [TwisterButtonElement(is_momentary = is_momentary, msg_type = MIDI_CC_TYPE, channel = 1, identifier = TWISTER_DIAL_BUTTONS[index], name = 'Encoder_Button_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(16)]	

		self._dial_matrix = ButtonMatrixElement(name = 'Dial_Matrix', rows = [self._encoder[index*4:(index*4)+4] for index in range(4)])
		self._dial_button_matrix = ButtonMatrixElement(name = 'Dial_Button_Matrix', rows = [self._encoder_button[index*4:(index*4)+4] for index in range(4)])
	

	def _setup_background(self):
		self._background = BackgroundComponent(name = 'Background')
		self._background.layer = Layer(priority = 3, dials = self._dial_matrix, dial_buttons = self._dial_button_matrix.submatrix[:,:])
		self._background.set_enabled(True)
	

	def _setup_m4l_interface(self):
		self._m4l_interface = M4LInterfaceComponent(controls=self.controls, component_guard=self.component_guard, priority = 10)
		self._m4l_interface.name = "M4LInterface"
		self.get_control_names = self._m4l_interface.get_control_names
		self.get_control = self._m4l_interface.get_control
		self.grab_control = self._m4l_interface.grab_control
		self.release_control = self._m4l_interface.release_control
	

	def _define_sysex(self):
		pass
	

	def _check_connection(self):
		self._connected = True
		self._initialize_hardware()
		self._initialize_script()
	

	def _setup_mixer_control(self):
		self._mixer_session_ring = SessionRingComponent(num_tracks = 4, num_scenes = 4)
		self._mixer = MonoMixerComponent(name = 'Mixer', tracks_provider = self._mixer_session_ring, track_assigner = simple_track_assigner, invert_mute_feedback = True, auto_name = True, enable_skinning = True)

		self._mixer.layer = Layer(priority = 4, 
											solo_buttons = self._dial_button_matrix.submatrix[:,0],
											stop_clip_buttons = self._dial_button_matrix.submatrix[:,1],
											track_select_buttons = self._dial_button_matrix.submatrix[:,2])
		self._mixer.set_enabled(True)
	

	def _setup_device_control(self):
		self._device = SpecialDeviceComponent(name = 'Device_Component', device_provider = self._device_provider, device_bank_registry = DeviceBankRegistry(), script = self)
		self._device.layer = Layer(priority = 4, parameter_controls = self._dial_matrix.submatrix[:,:],)
		self._device.bank_layer = AddLayerMode(self._device, Layer(priority = 4, 
												bank_prev_button = self._encoder_button[12],
												bank_next_button = self._encoder_button[13]))
		self._device.set_enabled(False)
	

	def _setup_mod(self):
		self.monomodular = get_monomodular(self)
		self.monomodular.name = 'monomodular_switcher'
		self.modhandler = TwisterModHandler(self, device_provider = self._device_provider)
		self.modhandler.name = 'ModHandler' 
		self.modhandler.layer = Layer(priority = 8,
										twister_encoder_button_grid = self._dial_button_matrix.submatrix[:,:],)
										#twister_encoder_grid = self._dial_matrix.submatrix[:,:],)
		self.modhandler.set_enabled(False)
	

	def _setup_modes(self):
		self._modswitcher = ModesComponent(name = 'ModSwitcher')
		self._modswitcher.add_mode('mod', [self.modhandler, self._device])
		self._modswitcher.add_mode('device', [self._device, self._device.bank_layer])
		self._modswitcher.selected_mode = 'device'
		self._modswitcher.set_enabled(True)
	

	def _update_modswitcher(self):
		debug('update modswitcher', self.modhandler.active_mod())
		if self.modhandler.active_mod():
			self._modswitcher.selected_mode = 'mod'
		else:
			self._modswitcher.selected_mode = 'device'
	

	@listens('appointed_device')
	def _on_device_changed(self):
		debug('appointed device changed, script')
		self._update_modswitcher()
	

	@listens('selected_track')
	def _on_selected_track_changed(self):
		debug('_on_selected_track_changed')
		#super(Cntrlr, self)._on_selected_track_changed()
		#self._drum_group_finder.device_parent = self.song.veiw.selected_track
		if not len(self.song.view.selected_track.devices):
			self._update_modswitcher()
	

	def restart_monomodular(self):
		#debug('restart monomodular')
		self.modhandler.disconnect()
		with self.component_guard():
			self._setup_mod()
Exemple #19
0
class Cntrlr(LividControlSurface):
	__module__ = __name__
	__doc__ = " Monomodular controller script for Livid CNTRLR "


	_sysex_id = 8
	_model_name = 'Cntrlr'
	_host_name = 'Cntrlr'
	monomodular = None

	device_provider_class = ModDeviceProvider

	def __init__(self, *a, **k):
		super(Cntrlr, self).__init__(*a, **k)
		self._skin = Skin(CntrlrColors)
		self._device_selection_follows_track_selection = FOLLOW
		with self.component_guard():
			self._setup_controls()
			self._define_sysex()
			self._setup_background()
			#self._setup_autoarm()
			self._setup_viewcontrol()
			self._setup_session_control()
			self._setup_mixer_control()
			self._setup_transport_control()
			#self._setup_device_control()
			#self._setup_device_selector()
			#self._setup_session_recording_component()
			#self._setup_modes()
			self._setup_m4l_interface()
	

	def _initialize_script(self):
		super(Cntrlr, self)._initialize_script()
		self._connected = True
		#self._main_modes.selected_mode = 'MixMode'

		self._session_ring._update_highlight()
		self._session_ring.track_offset = 0
		if liveobj_valid(self.song.visible_tracks[0]):
			self.song.view.selected_track = self.song.visible_tracks[0]
	

	def _setup_controls(self):
		is_momentary = True
		optimized = True
		resource = PrioritizedResource
		self._fader = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_FADERS[index], name = 'Fader_' + str(index), num = index, script = self,  optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(8)]
		self._dial_left = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_KNOBS_LEFT[index], name = 'Dial_Left_' + str(index), num = CNTRLR_KNOBS_LEFT[index], script = self, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)]
		self._dial_right = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_KNOBS_RIGHT[index], name = 'Dial_Right_' + str(index), num = CNTRLR_KNOBS_RIGHT[index], script = self, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)]
		self._encoder = [CodecEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_DIALS[index], name = 'Encoder_' + str(index), num = CNTRLR_DIALS[index], script = self, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)] 
		self._encoder_button = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CNTRLR_DIAL_BUTTONS[index], name = 'Encoder_Button_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)]	
		self._grid = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CNTRLR_GRID[index], name = 'Grid_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(16)]
		self._button = [MonoButtonElement(is_momentary = is_momentary,msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CNTRLR_BUTTONS[index], name = 'Button_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(32)]
		self._knobs = self._dial_left + self._dial_right

		self._fader_matrix = ButtonMatrixElement(name = 'Fader_Matrix', rows = [self._fader])
		self._matrix = ButtonMatrixElement(name = 'Matrix', rows = [self._grid[index*4:(index*4)+4] for index in range(4)])
		self._knob_left_matrix = ButtonMatrixElement(name = 'Knob_Left_Matrix', rows = [self._dial_left[index*4:(index*4)+4] for index in range(3)])
		self._knob_right_matrix = ButtonMatrixElement(name = 'Knob_Right_Matrix', rows = [self._dial_right[index*4:(index*4)+4] for index in range(3)])
		self._dial_matrix = ButtonMatrixElement(name = 'Dial_Matrix', rows = [self._encoder[index*4:(index*4)+4] for index in range(3)])
		self._dial_button_matrix = ButtonMatrixElement(name = 'Dial_Button_Matrix', rows = [self._encoder_button[index*4:(index*4)+4] for index in range(1,3)])
		self._key_matrix = ButtonMatrixElement(name = 'Key_Matrix', rows = [self._button[0:16], self._button[16:32]])
		
		self._translated_controls = self._fader + self._knobs + self._encoder[4:] + self._grid + self._button
	

	def _setup_background(self):
		self._background = BackgroundComponent(name = 'Background')
		self._background.layer = Layer(priority = 3, matrix = self._matrix.submatrix[:,:], faders = self._fader_matrix.submatrix[:,:], left_knobs = self._knob_left_matrix.submatrix[:,:], right_knobs = self._knob_right_matrix.submatrix[:,:], dials = self._dial_matrix, dial_buttons = self._dial_button_matrix.submatrix[:,:], keys = self._key_matrix.submatrix[:,:])
		self._background.set_enabled(True)
	

	def _define_sysex(self):
		#self.encoder_navigation_on = SendLividSysexMode(livid_settings = self._livid_settings, call = 'set_encoder_encosion_mode', message = [13, 0, 0, 0]) 
		pass
	

	def _setup_transport_control(self):
		self._transport = CntrlrTransportComponent(name = 'Transport') 
		self._transport._play_toggle.view_transform = lambda value: 'Transport.PlayOn' if value else 'Transport.PlayOff'
		self._transport._record_toggle.view_transform = lambda value: 'Transport.RecordOn' if value else 'Transport.RecordOff'
		self._transport._nudge_up_toggle.view_transform = lambda value: 'Transport.NudgeOn' if value else 'Transport.NudgeOff'
		self._transport._nudge_down_toggle.view_transform = lambda value: 'Transport.NudgeOn' if value else 'Transport.NudgeOff'
		self._transport._loop_toggle.view_transform = lambda value: 'Transport.LoopOn' if value else 'Transport.LoopOff'
		self._transport.layer = Layer(priority = 4,
									play_button = self._button[28],
									stop_button = self._button[29],
									record_button = self._button[30],
									tap_tempo_button = self._button[31],
									nudge_up_button = self._button[3],
									nudge_down_button = self._button[19],
									loop_button = self._button[23])
		self._transport.set_enabled(True)
	

	def _setup_autoarm(self):
		self._auto_arm = CntrlrAutoArmComponent(name='Auto_Arm')
		#self._auto_arm._update_notification = lambda a: None
		self._auto_arm.can_auto_arm_track = self._can_auto_arm_track
	

	def _setup_session_recording_component(self):
		self._clip_creator = ClipCreator()
		self._clip_creator.name = 'ClipCreator'
		self._recorder = FixedLengthSessionRecordingComponent(clip_creator = self._clip_creator, view_controller = ViewControlComponent(), name = 'SessionRecorder') # is_enabled = False)
		self._recorder.main_layer = AddLayerMode(self._recorder, Layer(priority = 4, record_button = self._button[29]))
		#self._recorder.shift_layer = AddLayerMode(self._recorder, Layer(priority = 4, automation_button = self._button[29]))
		self._recorder.set_enabled(False)
	

	def _setup_session_control(self):
		self._session_ring = SessionRingComponent(num_tracks = 4, num_scenes = 4)
		self._session_ring.set_enabled(True)

		self._session_navigation = SessionNavigationComponent(name = 'SessionNavigation', session_ring = self._session_ring)

		self._session_navigation._vertical_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._vertical_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._horizontal_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._horizontal_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._vertical_paginator.scroll_up_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._vertical_paginator.scroll_up_button.disabled_color = 'Session.PageNavigationButtonOff'
		self._session_navigation._vertical_paginator.scroll_down_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._vertical_paginator.scroll_down_button.disabled_color = 'Session.PageNavigationButtonOff'
		self._session_navigation._horizontal_paginator.scroll_up_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._horizontal_paginator.scroll_up_button.disabled_color = 'Session.PageNavigationButtonOff'
		self._session_navigation._horizontal_paginator.scroll_down_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._horizontal_paginator.scroll_down_button.disabled_color = 'Session.PageNavigationButtonOff'

		self._session_navigation.layer = Layer(priority = 4,
									down_button = self._button[14],
									up_button = self._button[15],
									left_button = self._button[12],
									right_button = self._button[13])
		self._session_navigation.set_enabled(True)

		self._session = SessionComponent(session_ring = self._session_ring, auto_name = True)
		hasattr(self._session, '_enable_skinning') and self._session._enable_skinning()
		self._session.layer = Layer(priority = 4,
									clip_launch_buttons = self._matrix.submatrix[:,:])
		self._session.set_enabled(True)
	

	def _setup_mixer_control(self):
		self._mixer_session_ring = SessionRingComponent(num_tracks = 4, num_scenes = 4)
		self._mixer = MonoMixerComponent(name = 'Mixer', tracks_provider = self._mixer_session_ring, track_assigner = simple_track_assigner, invert_mute_feedback = True, auto_name = True, enable_skinning = True)

		self._mixer.layer = Layer(priority = 4, 
											solo_buttons = self._key_matrix.submatrix[8:11, 0],
											stop_clip_buttons = self._key_matrix.submatrix[:3, 0],
											track_select_buttons = self._key_matrix.submatrix[4:8, 0],)
		for strip in self._mixer._channel_strips:
			strip._on_select_button_double_clicked = self._toggle_view
		self._mixer.set_enabled(True)
	

	def _toggle_view(self, *a):
		debug('toggle_view')
		debug('Clip is visible:', self.application().view.is_view_visible('Detail/Clip'))
		debug('Device is visible:', self.application().view.is_view_visible('Detail/DeviceChain'))
		if self.application().view.is_view_visible('Detail/Clip'):
			self._view_control.show_view('Detail/DeviceChain')
		else:
			self._view_control.show_view('Detail/Clip')

	def _setup_device_control(self):
		self._device_selection_follows_track_selection = FOLLOW
		self._device = DeviceComponent(name = 'Device_Component', device_provider = self._device_provider, device_bank_registry = DeviceBankRegistry())
		self._device.layer = Layer(priority = 4, parameter_controls = self._dial_matrix.submatrix[:, 1:3],)
		#self._device.mod_layer = AddLayerMode(self._device, Layer(priority = 4, parameter_controls = self._dial_matrix.submatrix[:, 1:3],))
		self._device.main_layer = AddLayerMode(self._device, Layer(priority = 4, parameter_controls = self._dial_matrix.submatrix[:, 1:3], 
												on_off_button = self._encoder_button[4],
												bank_prev_button = self._encoder_button[6],
												bank_next_button = self._encoder_button[7],))
												#lock_button = self._encoder_button[5],
		self._device.set_enabled(False)

		self._device_navigator = DeviceNavigator(self._device_provider, self._mixer, self)
		self._device_navigator.name = 'Device_Navigator'
		self._device_navigator.select_dial_layer = AddLayerMode(self._device_navigator, Layer(priority = 6, device_select_dial = self._encoder[0],))
		self._device_navigator.main_layer = AddLayerMode(self._device_navigator, Layer(priority = 4, 
											prev_chain_button = self._encoder_button[8], 
											next_chain_button = self._encoder_button[9], 
											exit_button = self._encoder_button[10], 
											enter_button = self._encoder_button[11],))
		self._device_navigator.set_enabled(False)
	

	def _setup_device_selector(self):
		self._device_selector = DeviceSelectorComponent(self)
		self._device_selector.name = 'Device_Selector'
		#self._device_selector.select_layer = AddLayerMode(self._device_selector, Layer(priority = 6 , matrix = self._matrix.submatrix[:, :]))
		self._device_selector.select_layer = AddLayerMode(self._device_selector, Layer(priority = 6, matrix = ButtonMatrixElement(rows = [self._grid[:4],self._grid[4:8],self._grid[8:12],self._grid[12:14]])))
		self._device_selector.assign_layer = AddLayerMode(self._device_selector, Layer(priority = 7, assign_button = self._grid[14]))
		self._device_selector.set_enabled(False)
	

	def _setup_viewcontrol(self):
		self._view_control = ViewControlComponent(name='View_Control')
		#self._view_control.main_layer = AddLayerMode(self._view_control, Layer(priority = 5, 
		#																		scene_select_dial = self._encoder[2],
		#																		track_select_dial = self._encoder[3],))
		#self._view_control.main_layer = AddLayerMode(self._view_control, Layer(prev_track_button=self._button[24], 
		#											next_track_button= self._button[25], 
		#											next_scene_button=self._button[27], 
		#											prev_scene_button = self._button[26]))
		self._view_control.set_enabled(True)
	

	def _setup_modes(self):

		common = CompoundMode(self._mixer,
									self._session_ring)
		main_buttons=CompoundMode(self._mixer.main_buttons_layer, 
									self._transport,
									self._recorder,
									self._recorder.main_layer, 
									self._device,)
		shifted_main_buttons=CompoundMode(self._mixer.solo_buttons_layer, 
									self._recorder, 
									self._recorder.shift_layer,
									self._session.scene_launch_layer,
									self._device,)
		main_faders=CompoundMode(self._mixer.main_faders_layer, 
									self._mixer.master_fader_layer)
		main_dials=CompoundMode(self._view_control,
									self._view_control.main_layer,
									self._device_navigator,
									self._device_navigator.select_dial_layer,
									self.encoder_navigation_on)
		shifted_dials=CompoundMode(self._session_navigation,
									self._session_navigation.nav_dial_layer,
									self._device_navigator,
									self._device_navigator.select_dial_layer,
									self.encoder_navigation_on)

		self._modalt_mode = ModesComponent(name = 'ModAltMode')
		self._modalt_mode.add_mode('disabled', None)
		self._modalt_mode.add_mode('enabled', [tuple([self._enable_mod_alt, self._disable_mod_alt])], behaviour = CancellableBehaviourWithRelease(), cycle_mode_button_color = 'Mod.AltOn')
		self._modalt_mode.selected_mode = 'disabled'
		self._modalt_mode.set_enabled(False)
		self._modalt_mode.layer = Layer(priority = 4, enabled_button = self._encoder_button[1])

		self._modswitcher = ModesComponent(name = 'ModSwitcher')
		self._modswitcher.add_mode('mod', [self.modhandler, self._modalt_mode, main_faders, self._mixer.main_knobs_layer, self._device, main_dials, DelayMode(self.modhandler.update, delay = .5, parent_task_group = self._task_group)])
		self._modswitcher.add_mode('instrument', [self._instrument.shift_button_layer, main_buttons, main_faders, self._mixer.main_knobs_layer, self._device, self._device.main_layer, self._device_navigator, self._device_navigator.main_layer, self._device_navigator.select_dial_layer]) #self._instrument.shift_button_layer, self._optional_translations])
		self._modswitcher.selected_mode = 'instrument'
		self._modswitcher.set_enabled(False)

		self._instrument._main_modes = ModesComponent(name = 'InstrumentModes')
		self._instrument._main_modes.add_mode('disabled', [main_buttons, 
																					main_dials, 
																					self._device.main_layer, 
																					self._session, 
																					self._session, 
																					self._session.clip_launch_layer])
		self._instrument._main_modes.add_mode('drumpad', [self._instrument._drumpad.sequencer_layer, 
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_split', [self._instrument._drumpad.split_layer,
																					self._instrument._selected_session,
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_sequencer', [self._instrument._drumpad.sequencer_layer, 
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_shifted', [self._instrument._drumpad.sequencer_shift_layer, 
																					self._instrument.drumpad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('drumpad_split_shifted', [self._instrument._drumpad.split_layer, 
																					self._instrument.drumpad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('drumpad_sequencer_shifted', [self._instrument._drumpad.sequencer_shift_layer, 
																					self._instrument.drumpad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad', [self._instrument._keypad.sequencer_layer, 
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_split', [self._instrument._keypad.split_layer,
																					self._instrument._selected_session,
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_sequencer', [self._instrument._keypad.sequencer_layer, 
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_shifted', [self._instrument._keypad.sequencer_shift_layer, 
																					self._instrument.keypad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad_split_shifted', [self._instrument._keypad.split_layer, 
																					self._instrument.keypad_shift_layer,
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad_sequencer_shifted', [self._instrument._keypad.sequencer_shift_layer, 
																					self._instrument.keypad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('drumpad_session', [self._instrument._drumpad.sequencer_session_layer, 
																					main_buttons,
																					self._device.main_layer,
																					self._session,
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_split_session', [self._instrument._drumpad.split_session_layer,
																					self._instrument._selected_session,
																					main_buttons,
																					self._device.main_layer,
																					self._session,
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_sequencer_session', [self._instrument._drumpad.sequencer_session_layer, 
																					main_buttons,
																					self._device.main_layer,
																					self._session,  
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_shifted_session', [self._instrument._drumpad.sequencer_session_shift_layer, 
																					self._instrument.drumpad_shift_layer, 
																					main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		self._instrument._main_modes.add_mode('drumpad_split_shifted_session', [self._instrument._drumpad.split_session_layer,
																					self._instrument.drumpad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		self._instrument._main_modes.add_mode('drumpad_sequencer_shifted_session', [self._instrument._drumpad.sequencer_session_shift_layer, 
																					self._instrument.drumpad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad_session', [self._instrument._keypad.sequencer_session_layer, 
																					main_buttons,
																					self._device.main_layer,
																					self._session, 
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_split_session', [self._instrument._keypad.split_session_layer,
																					self._instrument._selected_session,
																					main_buttons,
																					self._device.main_layer,
																					self._session,
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_sequencer_session', [self._instrument._keypad.sequencer_session_layer, 
																					main_buttons,
																					self._device.main_layer,
																					self._session, 
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_shifted_session', [self._instrument._keypad.sequencer_session_shift_layer, 
																					self._instrument.keypad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad_split_shifted_session', [self._instrument._keypad.split_session_layer, 
																					self._instrument.keypad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad_sequencer_shifted_session', [self._instrument._keypad.sequencer_session_shift_layer,
																					self._instrument.keypad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])

		self._instrument._main_modes.add_mode('audioloop', [self._instrument.audioloop_layer, 
																					main_buttons,
																					self._device.main_layer,
																					main_dials,
																					self._session,
																					DelayMode(self._session.clip_launch_layer, delay = .1)])
		self._instrument._main_modes.add_mode('audioloop_shifted', [self._instrument.audioloop_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		#self._instrument._main_modes.add_mode('audioloop_shifted_session', [self._instrument.audioloop_layer, self._session, shifted_main_buttons, main_dials, shifted_dials])
		self._instrument.register_component(self._instrument._main_modes)
		self._instrument._main_modes.selected_mode = 'disabled'
		self._instrument.set_enabled(True)

		self._main_modes = ModesComponent(name = 'MainModes')
		self._main_modes.add_mode('disabled', [self._background])
		self._main_modes.add_mode('MixMode', [common, 
													self._instrument, 
													self._instrument.shift_button_layer,
													self._mixer,
													main_faders, 
													self._mixer.main_knobs_layer,
													self._device,
													self._device.main_layer,
													self._device_navigator,
													self._device_navigator.main_layer,
													self._device_navigator.select_dial_layer])
		self._main_modes.add_mode('ModSwitcher', [common,
													main_faders, 
													main_dials, 
													self._mixer.main_knobs_layer,
													self._view_control,
													self._view_control.main_layer,
													self._device_navigator,
													self._device_navigator.select_dial_layer, 
													self.encoder_navigation_on, 
													self._modswitcher, 
													DelayMode(self._update_modswitcher, delay = .1)], 
													behaviour = ColoredCancellableBehaviourWithRelease(color = 'ModeButtons.ModSwitcher', off_color = 'ModeButtons.ModSwitcherDisabled'))
		self._main_modes.add_mode('Translations', [common, 
													main_faders, 
													main_dials,
													self._mixer.main_knobs_layer, 
													self._translations, 
													DelayMode(self._translations.selector_layer, delay = .1)], 
													behaviour = DefaultedBehaviour(default_mode = 'MixMode', color = 'ModeButtons.Translations', off_color = 'ModeButtons.TranslationsDisabled'))
		self._main_modes.add_mode('DeviceSelector', [common,
													self._device_selector,
													DelayMode(self._device_selector.select_layer, delay = .1),
													DelayMode(self.modhandler.lock_layer, delay = .1),
													DelayMode(self._device_selector.assign_layer, delay = .5), 
													main_buttons,
													main_dials, 
													main_faders, 
													self._mixer.main_knobs_layer, 
													self._device.main_layer,
													self._device_navigator,
													self._device_navigator.main_layer,
													self._device_navigator.select_dial_layer], 
													behaviour = ColoredCancellableBehaviourWithRelease(color = 'ModeButtons.DeviceSelector', off_color = 'ModeButtons.DeviceSelectorDisabled'))
		self._main_modes.layer = Layer(priority = 4, ModSwitcher_button = self._encoder_button[2], DeviceSelector_button = self._encoder_button[0], Translations_button = self._encoder_button[3]) #, 
		self._main_modes.selected_mode = 'disabled'
		self._main_modes.set_enabled(True)

		self._test.subject = self._instrument._main_modes
	

	def _setup_modes(self):
		pass
	

	def _setup_m4l_interface(self):
		self._m4l_interface = M4LInterfaceComponent(controls=self.controls, component_guard=self.component_guard, priority = 10)
		self._m4l_interface.name = "M4LInterface"
		self.get_control_names = self._m4l_interface.get_control_names
		self.get_control = self._m4l_interface.get_control
		self.grab_control = self._m4l_interface.grab_control
		self.release_control = self._m4l_interface.release_control
	

	def _can_auto_arm_track(self, track):
		routing = track.current_input_routing
		return routing == 'Ext: All Ins' or routing == 'All Ins' or routing.startswith('Cntrlr Input')
	

	def _get_num_tracks(self):
		return self.num_tracks
	



#	a
Exemple #20
0
class ATOM(ControlSurface):
    def __init__(self, *a, **k):
        super(ATOM, self).__init__(*a, **k)
        with self.component_guard():
            with inject(skin=const(skin)).everywhere():
                self._elements = Elements()
        with self.component_guard():
            with inject(element_container=const(self._elements)).everywhere():
                self._create_lighting()
                self._create_transport()
                self._create_record_modes()
                self._create_undo()
                self._create_view_toggle()
                self._create_background()
                self._create_session()
                self._create_mixer()
                self._create_encoder_modes()
                self._create_session_navigation_modes()
                self._create_keyboard()
                self._create_drum_group()
                self._create_note_modes()
                self._create_pad_modes()
                self._create_user_assignments_mode()
                self._target_track = ArmedTargetTrackComponent(
                    name=u'Target_Track')
                self.__on_target_track_changed.subject = self._target_track
        self._drum_group_finder = self.register_disconnectable(
            PercussionInstrumentFinder(
                device_parent=self._target_track.target_track))
        self.__on_drum_group_changed.subject = self._drum_group_finder
        self.__on_drum_group_changed()
        self.__on_main_view_changed.subject = self.application.view

    def disconnect(self):
        self._send_midi(midi.NATIVE_MODE_OFF_MESSAGE)
        super(ATOM, self).disconnect()

    def port_settings_changed(self):
        self._send_midi(midi.NATIVE_MODE_ON_MESSAGE)
        super(ATOM, self).port_settings_changed()

    def _create_lighting(self):
        self._lighting = LightingComponent(name=u'Lighting',
                                           is_enabled=False,
                                           layer=Layer(
                                               shift_button=u'shift_button',
                                               zoom_button=u'zoom_button'))
        self._lighting.set_enabled(True)

    def _create_transport(self):
        self._transport = TransportComponent(
            name=u'Transport',
            is_enabled=False,
            layer=Layer(play_button=u'play_button',
                        loop_button=u'play_button_with_shift',
                        stop_button=u'stop_button',
                        metronome_button=u'click_button'))
        self._transport.set_enabled(True)

    def _create_record_modes(self):
        self._session_record = SessionRecordingComponent(
            name=u'Session_Record',
            is_enabled=False,
            layer=Layer(record_button=u'record_button'))
        self._record_modes = ModesComponent(name=u'Record_Modes')
        self._record_modes.add_mode(u'session', self._session_record)
        self._record_modes.add_mode(
            u'arrange',
            AddLayerMode(self._transport,
                         layer=Layer(record_button=u'record_button')))
        self.__on_main_view_changed()

    def _create_undo(self):
        self._undo = UndoRedoComponent(
            name=u'Undo',
            is_enabled=False,
            layer=Layer(undo_button=u'stop_button_with_shift'))
        self._undo.set_enabled(True)

    def _create_view_toggle(self):
        self._view_toggle = ViewToggleComponent(
            name=u'View_Toggle',
            is_enabled=False,
            layer=Layer(detail_view_toggle_button=u'show_hide_button',
                        main_view_toggle_button=u'preset_button'))
        self._view_toggle.set_enabled(True)

    def _create_background(self):
        self._background = BackgroundComponent(
            name=u'Background',
            is_enabled=False,
            add_nop_listeners=True,
            layer=Layer(set_loop_button=u'set_loop_button',
                        nudge_button=u'nudge_button',
                        bank_button=u'bank_button'))
        self._background.set_enabled(True)

    def _create_session(self):
        self._session_ring = SessionRingComponent(name=u'Session_Ring',
                                                  num_tracks=SESSION_WIDTH,
                                                  num_scenes=SESSION_HEIGHT)
        self._session = SessionComponent(name=u'Session',
                                         session_ring=self._session_ring)
        self._session_navigation = SessionNavigationComponent(
            name=u'Session_Navigation',
            is_enabled=False,
            session_ring=self._session_ring,
            layer=Layer(left_button=u'left_button',
                        right_button=u'right_button'))
        self._session_navigation.set_enabled(True)
        self._session_overview = SessionOverviewComponent(
            name=u'Session_Overview',
            is_enabled=False,
            session_ring=self._session_ring,
            enable_skinning=True,
            layer=Layer(button_matrix=u'pads_with_zoom'))

    def _create_mixer(self):
        self._mixer = MixerComponent(
            name=u'Mixer',
            auto_name=True,
            tracks_provider=self._session_ring,
            track_assigner=SimpleTrackAssigner(),
            invert_mute_feedback=True,
            channel_strip_component_type=ChannelStripComponent)

    def _create_encoder_modes(self):
        self._encoder_modes = ModesComponent(name=u'Encoder_Modes',
                                             enable_skinning=True)
        self._encoder_modes.add_mode(
            u'volume',
            AddLayerMode(self._mixer, Layer(volume_controls=u'encoders')))
        self._encoder_modes.add_mode(
            u'pan', AddLayerMode(self._mixer, Layer(pan_controls=u'encoders')))
        self._encoder_modes.add_mode(
            u'send_a',
            AddLayerMode(self._mixer, Layer(send_a_controls=u'encoders')))
        self._encoder_modes.add_mode(
            u'send_b',
            AddLayerMode(self._mixer, Layer(send_b_controls=u'encoders')))
        self._encoder_modes.selected_mode = u'volume'

    def _create_session_navigation_modes(self):
        self._session_navigation_modes = ModesComponent(
            name=u'Session_Navigation_Modes',
            is_enabled=False,
            layer=Layer(cycle_mode_button=u'bank_button'))
        self._session_navigation_modes.add_mode(
            u'default',
            AddLayerMode(self._session_navigation,
                         layer=Layer(up_button=u'up_button',
                                     down_button=u'down_button')),
            cycle_mode_button_color=u'DefaultButton.Off')
        self._session_navigation_modes.add_mode(
            u'paged',
            AddLayerMode(self._session_navigation,
                         layer=Layer(page_up_button=u'up_button',
                                     page_down_button=u'down_button',
                                     page_left_button=u'left_button',
                                     page_right_button=u'right_button')),
            cycle_mode_button_color=u'DefaultButton.On')
        self._session_navigation_modes.selected_mode = u'default'

    def _create_keyboard(self):
        self._keyboard = KeyboardComponent(
            midi.KEYBOARD_CHANNEL,
            name=u'Keyboard',
            is_enabled=False,
            layer=Layer(matrix=u'pads',
                        scroll_up_button=u'up_button',
                        scroll_down_button=u'down_button'))

    def _create_drum_group(self):
        self._drum_group = DrumGroupComponent(
            name=u'Drum_Group',
            is_enabled=False,
            translation_channel=midi.DRUM_CHANNEL,
            layer=Layer(matrix=u'pads',
                        scroll_page_up_button=u'up_button',
                        scroll_page_down_button=u'down_button'))

    def _create_note_modes(self):
        self._note_modes = ModesComponent(name=u'Note_Modes', is_enabled=False)
        self._note_modes.add_mode(u'keyboard', self._keyboard)
        self._note_modes.add_mode(u'drum', self._drum_group)
        self._note_modes.selected_mode = u'keyboard'

    def _create_pad_modes(self):
        self._pad_modes = ModesComponent(
            name=u'Pad_Modes',
            is_enabled=False,
            layer=Layer(session_button=u'full_level_button',
                        note_button=u'note_repeat_button',
                        channel_button=u'select_button',
                        encoder_modes_button=u'setup_button'))
        self._pad_modes.add_mode(
            u'session',
            (AddLayerMode(self._background,
                          Layer(unused_pads=u'pads_with_shift')),
             AddLayerMode(
                 self._session,
                 Layer(clip_launch_buttons=u'pads',
                       scene_launch_buttons=self._elements.pads_with_shift.
                       submatrix[3:, :])), self._session_overview,
             self._session_navigation_modes))
        self._pad_modes.add_mode(u'note', self._note_modes)
        self._pad_modes.add_mode(
            u'channel',
            (self._elements.pads.reset,
             AddLayerMode(
                 self._mixer,
                 Layer(
                     arm_buttons=self._elements.pads.submatrix[:, :1],
                     solo_buttons=self._elements.pads.submatrix[:, 1:2],
                     track_select_buttons=self._elements.pads.submatrix[:,
                                                                        2:3])),
             AddLayerMode(
                 self._session,
                 Layer(stop_track_clip_buttons=self._elements.pads.
                       submatrix[:, 3:])), self._session_navigation_modes))
        self._pad_modes.add_mode(
            u'encoder_modes',
            (LayerMode(
                self._encoder_modes,
                Layer(volume_button=self._elements.pads_raw[0][0],
                      pan_button=self._elements.pads_raw[0][1],
                      send_a_button=self._elements.pads_raw[0][2],
                      send_b_button=self._elements.pads_raw[0][3])),
             AddLayerMode(
                 self._background,
                 Layer(unused_pads=self._elements.pads.submatrix[:, 1:]))),
            behaviour=MomentaryBehaviour())
        self._pad_modes.selected_mode = u'session'
        self._pad_modes.set_enabled(True)

    def _create_user_assignments_mode(self):
        self._translating_background = TranslatingBackgroundComponent(
            midi.USER_CHANNEL,
            name=u'Translating_Background',
            is_enabled=False,
            add_nop_listeners=True,
            layer=Layer(note_repeat_button=u'note_repeat_button',
                        full_level_button=u'full_level_button',
                        bank_button=u'bank_button',
                        preset_button=u'preset_button',
                        show_hide_button=u'show_hide_button',
                        nudge_button=u'nudge_button',
                        set_loop_button=u'set_loop_button',
                        setup_button=u'setup_button',
                        up_button=u'up_button',
                        down_button=u'down_button',
                        left_button=u'left_button',
                        right_button=u'right_button',
                        select_button=u'select_button',
                        click_button=u'click_button',
                        record_button=u'record_button',
                        play_button=u'play_button',
                        stop_button=u'stop_button',
                        pads=u'pads',
                        encoders=u'encoders'))
        self._top_level_modes = ModesComponent(
            name=u'Top_Level_Modes',
            is_enabled=False,
            support_momentary_mode_cycling=False,
            layer=Layer(cycle_mode_button=u'editor_button'))
        self._top_level_modes.add_mode(
            u'default',
            self.refresh_state,
            cycle_mode_button_color=u'DefaultButton.Off')
        self._top_level_modes.add_mode(
            u'user',
            self._translating_background,
            cycle_mode_button_color=u'DefaultButton.On')
        self._top_level_modes.selected_mode = u'default'
        self._top_level_modes.set_enabled(True)

    @listens(u'is_view_visible', u'Session')
    def __on_main_view_changed(self):
        if self.application.view.is_view_visible(u'Session'):
            self._record_modes.selected_mode = u'session'
        else:
            self._record_modes.selected_mode = u'arrange'

    @listens(u'target_track')
    def __on_target_track_changed(self):
        self._drum_group_finder.device_parent = self._target_track.target_track

    @listens(u'instrument')
    def __on_drum_group_changed(self):
        drum_group = self._drum_group_finder.drum_group
        self._drum_group.set_drum_group_device(drum_group)
        self._note_modes.selected_mode = u'drum' if liveobj_valid(
            drum_group) else u'keyboard'
class OhmModes(LividControlSurface):


	_sysex_id = 2
	_alt_sysex_id = 7
	_model_name = 'Ohm'
	_version_check = 'b996'
	_host_name = 'Ohm'

	def __init__(self, c_instance):
		super(OhmModes, self).__init__(c_instance)
		self._skin = Skin(OhmColors)
		with self.component_guard():
			self._define_sysex()
			self._setup_controls()
			self._setup_background()
			self._setup_m4l_interface()
			self._setup_translations()
			self._setup_session_control()
			self._setup_mixer_control()
			self._setup_device_control()
			self._setup_transport_control()
			self._setup_drumgroup()
			self._setup_keygroup()
			self._setup_bassgroup()
			self._setup_mod()
			self._setup_modswitcher()
			self._setup_modes()
		self._on_device_changed.subject = self._device_provider
	

	def _define_sysex(self):
		#self._send_midi(tuple(switchxfader))
		self._reverse_crossfader = SendLividSysexMode(self._livid_settings, call = 'reverse crossfader', message = [1])
	

	def update_display(self):
		super(OhmModes, self).update_display()
		#self.strobe()
	

	def _initialize_hardware(self):
		super(OhmModes, self)._initialize_hardware()
		#self._reverse_crossfader.enter_mode()
	

	def _initialize_script(self):
		super(OhmModes, self)._initialize_script()
		self._main_modes.selected_mode = 'Mix'
		self._session.update()
		self._mixer.update()
	

	def _setup_controls(self):
		is_momentary = True
		optimized = True
		resource = PrioritizedResource
		self._fader = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = OHM_FADERS[index], name = 'Fader_' + str(index), num = index, script = self, optimized_send_midi = optimized, resource_type = resource) for index in range(8)]
		self._button = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = OHM_BUTTONS[index], name = 'Button_' + str(index), script = self, skin = self._skin, optimized_send_midi = optimized, resource_type = resource) for index in range(8)]
		self._dial = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = OHM_DIALS[index], name = 'Encoder_' + str(index), num = index, script = self, optimized_send_midi = optimized, resource_type = resource) for index in range(16)]
		self._menu = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = OHM_MENU[index], name = 'Menu_' + str(index), script = self, skin = self._skin, optimized_send_midi = optimized, resource_type = resource) for index in range(6)]
		self._crossfader = MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CROSSFADER, name = 'Crossfader', script = self, optimized_send_midi = optimized, resource_type = resource)
		self._livid = MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = LIVID, name = 'Livid_Button', skin = self._skin, script = self, optimized_send_midi = optimized, resource_type = resource)
		self._shift_l = MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = SHIFT_L, name = 'Page_Button_Left', script = self, skin = self._skin, optimized_send_midi = optimized, resource_type = resource)
		self._shift_r = MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = SHIFT_R, name = 'Page_Button_Right', script = self, skin = self._skin, optimized_send_midi = optimized, resource_type = resource)
		self._grid = [[MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = column * 8 + row, name = 'Grid_' + str(column + (row*8)), script = self, skin = self._skin, optimized_send_midi = optimized, resource_type = resource) for column in range(8)] for row in range(8)]
		self._matrix = ButtonMatrixElement(name = 'Matrix', rows = [[self._grid[row][column] for column in range(8)] for row in range(8)])
		self._dial_matrix = ButtonMatrixElement(name = 'DialMatrix', rows = [self._dial[index*4:(index*4)+4] for index in range(4)])
		self._menu_matrix = ButtonMatrixElement(name = 'MenuMatrix', rows = [self._menu])
		self._fader_matrix = ButtonMatrixElement(name = 'FaderMatrix', rows = [self._fader])
		self._button_matrix = ButtonMatrixElement(name = 'ButtonMatrix', rows = [self._button])

		self._parameter_controls = ButtonMatrixElement(rows = [self._dial[:4], self._dial[4:8]])
	

	def _setup_background(self):
		self._background = BackgroundComponent(name = 'Background')
		self._background.layer = Layer(priority = 3, matrix = self._matrix.submatrix[:,:],
													livid_button = self._livid,
													shift_l_button = self._shift_l,
													shift_r_button = self._shift_r,
													crossfader = self._crossfader,
													dial_matrix = self._dial_matrix.submatrix[:,:],
													menu_matrix = self._menu_matrix.submatrix[:,:],
													fader_matrix = self._fader_matrix.submatrix[:,:],
													button_matrix = self._button_matrix.submatrix[:,:])
		self._background.set_enabled(False)
	

	def _setup_m4l_interface(self):
		self._m4l_interface = M4LInterfaceComponent(controls=self.controls, component_guard=self.component_guard)
		self.get_control_names = self._m4l_interface.get_control_names
		self.get_control = self._m4l_interface.get_control
		self.grab_control = self._m4l_interface.grab_control
		self.release_control = self._m4l_interface.release_control
	

	def _setup_translations(self):
		controls = []
		for array in self._grid:
			for button in array:
				controls.append(button)
		if FADER_BANKING:
			controls = controls + self._dial
		if DIAL_BANKING:
			controls = controls + self._dial
		self._translations = TranslationComponent(controls = controls, user_channel_offset = USER_CHANNEL, channel = 8)
		self._translations.layer = Layer(priority = 5, channel_selector_buttons = self._menu_matrix.submatrix[:,:])
		self._translations.set_enabled(False)

		dj_controls = [self._grid[7][index] for index in range(7)]
		self._dj_translation = TranslationComponent(controls = dj_controls, channel = 12)
	

	def _setup_session_control(self):
		self._session_ring = SessionRingComponent(num_tracks = 7, num_scenes = 5)
		self._session_ring.set_enabled(True)

		self._session_navigation = SessionNavigationComponent(session_ring = self._session_ring)
		self._session_navigation.scroll_navigation_layer = AddLayerMode(self._session_navigation, Layer(priority = 5, up_button = self._menu[2], down_button = self._menu[5], left_button = self._menu[3], right_button = self._menu[4]))
		self._session_navigation.page_navigation_layer = AddLayerMode(self._session_navigation, Layer(priority = 5, page_up_button = self._menu[2], page_down_button = self._menu[5], page_left_button = self._menu[3], page_right_button = self._menu[4]))
		self._session_navigation._vertical_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._vertical_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._horizontal_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._horizontal_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._vertical_paginator.scroll_up_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._vertical_paginator.scroll_down_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._horizontal_paginator.scroll_up_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._horizontal_paginator.scroll_down_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation.set_enabled(False)

		self._session = OhmSessionComponent(name = 'Session', session_ring = self._session_ring, auto_name = True)
		hasattr(self._session, '_enable_skinning') and self._session._enable_skinning()
		self._session.set_enabled(False)
		self._session.clip_launch_layer = AddLayerMode(self._session, Layer(priority = 5,  clip_launch_buttons = self._matrix.submatrix[:7,:5]))
		self._session.scene_launch_layer = AddLayerMode(self._session, Layer(priority = 5,  scene_launch_buttons = self._matrix.submatrix[7,:5]))

		self._session_zoom = SessionOverviewComponent(name = 'Session_Overview', session_ring = self._session_ring, enable_skinning = True)
		self._session_zoom.layer = Layer(priority = 5, button_matrix = self._matrix.submatrix[:7,:5])
		self._session_zoom.set_enabled(False)

		self._session_modes = ModesComponent(name = 'Session_Modes')
		self._session_modes.add_mode('disabled', [self._session, 
														self._session.clip_launch_layer, 
														self._session.scene_launch_layer, 
														self._session_navigation, 
														self._session_navigation.scroll_navigation_layer])
		self._session_modes.add_mode('enabled', [self._session, 
														self._session.scene_launch_layer, 
														self._session_zoom, 
														self._session_navigation, 
														self._session_navigation.page_navigation_layer],  
														behaviour = DefaultedBehaviour())
		self._session_modes.layer = Layer(priority = 5, enabled_button = self._grid[7][7])
		self._session_modes.selected_mode = 'disabled'
		self._session_modes.set_enabled(False)
	

	def _setup_mixer_control(self):
		self._mixer = OhmMixerComponent(name = 'Mixer', tracks_provider = self._session_ring, track_assigner = simple_track_assigner, invert_mute_feedback = True, auto_name = True, enable_skinning = True)
		self._mixer.layer = Layer(priority = 5, volume_controls = self._fader_matrix.submatrix[:7, :], prehear_volume_control = self._dial[15], crossfader_control = self._crossfader)
		self._mixer.master_strip().layer = Layer(priority = 5, volume_control = self._fader[7], select_button = self._button[7])
		self._mixer.mix_layer = AddLayerMode(self._mixer, Layer(priority = 5, mute_buttons = self._matrix.submatrix[:7,5], 
													solo_buttons = self._matrix.submatrix[:7,6], 
													arm_buttons = self._matrix.submatrix[:7,7], 
													send_controls = self._dial_matrix.submatrix[:,:2],
													pan_controls = self._dial_matrix.submatrix[:7,2:],
													track_select_buttons = self._button_matrix.submatrix[:7,:],))
		self._mixer.dj_layer = AddLayerMode(self._mixer, Layer(priority = 5, mute_buttons = self._matrix.submatrix[:7,5],
													crossfade_toggles = self._matrix.submatrix[:7,6],
													end_pan_controls = self._dial_matrix.submatrix[:3,3],
													eq_gain_controls = self._dial_matrix.submatrix[:,:3],
													track_select_buttons = self._button_matrix.submatrix[:7,:],))
		self._mixer.instrument_layer = AddLayerMode(self._mixer, Layer(priority = 5, 
													instrument_send_controls = self._dial_matrix.submatrix[:,2:],
													arming_track_select_buttons = self._button_matrix.submatrix[:7,:]))
	

	def _setup_device_control(self):
		self._device = OhmDeviceComponent(script = self, name = 'Device_Component', device_provider = self._device_provider, device_bank_registry = DeviceBankRegistry())
		self._device.layer = Layer(priority = 5, parameter_controls = self._parameter_controls )
		self._device.set_enabled(False)

		self._device_navigator = DeviceNavigator(self._device_provider, self._mixer, self, name = 'Device_Navigator', )
		self._device_navigator.layer = Layer(priority = 5, prev_button = self._menu[3], next_button = self._menu[4])
		self._device_navigator.set_enabled(False)
	

	def _setup_transport_control(self):
		self._transport = OhmTransportComponent()
		self._transport.name = 'Transport'
		self._transport.layer = Layer(priority = 5, play_button = self._menu[0], stop_button = self._menu[1])
		self._transport.set_enabled(False)
	

	def _setup_drumgroup(self):
		self._drumgroup = MonoDrumGroupComponent(translation_channel = PAGE1_DRUM_CHANNEL, set_pad_translations = self.set_pad_translations)
		self._drumgroup._on_selected_track_changed.subject = None
		self._drumgroup.translation_channel = PAGE1_DRUM_CHANNEL
		self._drumgroup.layer = Layer(priority = 6, matrix = self._matrix.submatrix[:4, :4])
		self._drumgroup.set_enabled(False)
	

	def _setup_keygroup(self):
		self._scale_mode = ModesComponent(name = 'ScaleMode')
		for scale in SCALES:
			debug('making scale mode:', scale, str(scale))
			self._scale_mode.add_mode(str(scale), [])
		self._scale_mode.layer = Layer(priority = 5, 
										ionian_button = self._grid[7][0],
										dorian_button = self._grid[7][1],
										phrygian_button = self._grid[7][2],
										lydian_button = self._grid[7][3],
										mixolydian_button = self._grid[7][4],
										aeolian_button = self._grid[7][5],
										locrian_button = self._grid[7][6],
										major_button = self._grid[7][7])
		self._scale_mode.selected_mode = 'ionian'
		self._scale_mode.set_enabled(False)
		self._on_scale_change.subject = self._scale_mode

		self._octave_offset_component = ScrollingChannelizedSettingsComponent(name = 'NoteOffset', parent_task_group = self._task_group, value_dict = range(104), default_value_index = 36, default_channel = 0, bank_increment = 12, bank_on_color = 'MonoInstrument.OffsetOnValue', bank_off_color = 'MonoInstrument.OffsetOffValue')
		self._octave_offset_component.layer = Layer(priority = 5, bank_up_button = self._menu[2], bank_down_button = self._menu[5])
		self._on_octave_change.subject = self._octave_offset_component

		self._keygroup = OhmKeyGroupComponent()
		self._keygroup._on_selected_track_changed.subject = None
		self._keygroup.translation_channel = PAGE1_KEYS_CHANNEL
		self._keygroup.layer = Layer(priority = 6, matrix = self._matrix.submatrix[:, 4:7])
		self._keygroup.set_enabled(False)
	

	def _setup_bassgroup(self):
		self._bassgroup = OhmBassGroupComponent()
		self._bassgroup._on_selected_track_changed.subject = None
		self._bassgroup.translation_channel = PAGE1_BASS_CHANNEL
		self._bassgroup.layer = Layer(priority = 6, matrix = self._matrix.submatrix[4:, :4])
		self._bassgroup.set_enabled(False)
	

	def _setup_mod(self):
		self.monomodular = get_monomodular(self)
		self.monomodular.name = 'monomodular_switcher'
		self.modhandler = OhmModHandler(self)
		self.modhandler.name = 'ModHandler' 
		self.modhandler.layer = Layer(priority = 5, 
									grid = self._matrix.submatrix[:,:],
									nav_up_button = self._menu[2],
									nav_down_button = self._menu[5],
									nav_left_button = self._menu[3],
									nav_right_button =  self._menu[4],
									shift_button = self._menu[1],
									alt_button = self._menu[0],
									parameter_controls = self._dial_matrix)
		self.modhandler.legacy_shift_mode = AddLayerMode(self.modhandler, Layer(priority = 6,
									channel_buttons = self._matrix.submatrix[:, 1],
									nav_matrix = self._matrix.submatrix[4:8, 2:6]))
		self.modhandler.shift_mode = AddLayerMode(self.modhandler, Layer(priority = 6, 
									device_selector_matrix = self._matrix.submatrix[:, 0],
									lock_button = self._livid,
									key_buttons = self._matrix.submatrix[:, 7]))
									
		self.modhandler.set_enabled(False)
		self.modhandler.set_mod_button(self._livid)
	

	def _setup_modswitcher(self):
		self._modswitcher = ModesComponent(name = 'ModSwitcher')
		self._modswitcher.add_mode('mod', [self.modhandler, DelayMode(self.modhandler.update, delay = .5)])
		self._modswitcher.add_mode('translations', [self._translations])
		self._modswitcher.selected_mode = 'translations'
		self._modswitcher.set_enabled(False)
	

	def _setup_modes(self):

		self._main_modes = ModesComponent(name = 'MainModes')
		self._main_modes.add_mode('disabled', [self._background])
		self._main_modes.add_mode('Mix', [self._session_modes, 
											self._mixer,
											self._mixer.mix_layer,
											self._transport])

		self._main_modes.add_mode('DJ', [self._session_modes,
											self._mixer,
											self._mixer.dj_layer,
											self._dj_translation,
											tuple([self._assign_tempo, self._deassign_tempo])],
											behaviour = DefaultedBehaviour(default_mode = 'Mix'))
											#tuple([ lambda:self._set_tempo_buttons([self._grid[7][5], self._grid[7][6]]), self._set_tempo_buttons([])])],

		self._main_modes.add_mode('Instrument', [self._update_keygroup_colors,
											self._bassgroup,
											self._keygroup,
											self._scale_mode,
											self._octave_offset_component,
											self._device,
											self._device_navigator,
											self._mixer,
											self._mixer.instrument_layer,
											self._drumgroup],
											behaviour = DefaultedBehaviour(default_mode = 'Mix'))

		self._main_modes.add_mode('Mod', [self._modswitcher,
											self._device,
											self._mixer,
											self._mixer.instrument_layer], 
											behaviour = DefaultedBehaviour(default_mode = 'Mix'))
		self._main_modes.layer = Layer(priority = 5, Instrument_button = self._shift_l, DJ_button = self._shift_r, Mod_button = self._livid)
		self._main_modes.selected_mode = 'disabled'
		self._main_modes.set_enabled(True)
	

	def disconnect(self):
		super(OhmModes, self).disconnect()
	

	def strobe(self):
		if self._backlight_type != 'static':
			if self._backlight_type is 'pulse':
				self._backlight = int(math.fabs(self._timer * 16 % 64 - 32) + 32)
			if self._backlight_type is 'up':
				self._backlight = int(self._timer * 8 % 64 + 16)
			if self._backlight_type is 'down':
				self._backlight = int(math.fabs(int(self._timer * 8 % 64 - 64)) + 16)
		self._send_midi(tuple([176, 27, int(self._backlight)]))
		if self._ohm_type != 'static':
			if self._ohm_type is 'pulse':
				self._ohm = int(math.fabs(self._timer * 16 % 64 - 32) + 32)
			if self._ohm_type is 'up':
				self._ohm = int(self._timer * 8 % 64 + 16)
			if self._ohm_type is 'down':
				self._ohm = int(math.fabs(int(self._timer * 8 % 64 - 64)) + 16)
		self._send_midi(tuple([176, 63, int(self._ohm)]))
		self._send_midi(tuple([176, 31, int(self._ohm)]))
	

	def handle_sysex(self, midi_bytes):
		debug('sysex: ', str(midi_bytes))
		if len(midi_bytes) > 14:
			if midi_bytes[:6] == tuple([240, 0, 1, 97, 12, 64]):
				self._register_pad_pressed(midi_bytes[6:14])
			elif midi_bytes[:6] == tuple([240, 0, 1, 97, 17, 64]):
				self._register_pad_pressed(midi_bytes[6:14])
			elif midi_bytes[3:11] == tuple([6, 2, 0, 1, 97, 1, 0]  + [self._sysex_id]) or midi_bytes[3:11] == tuple([6, 2, 0, 1, 97, 1, 0]  + [self._alt_sysex_id]):
				if not self._connected:
					#self._connection_routine.kill()
					self._connected = True
					self._livid_settings.set_model(midi_bytes[11])
					self._initialize_hardware()
					self.schedule_message(1, self._initialize_script)
	

	@listens('device')
	def _on_device_changed(self):  
		self.schedule_message(1, self._update_modswitcher)
		#debug('base on_device_changed')
		self._update_modswitcher()
	

	def _on_selected_track_changed(self):
		super(OhmModes, self)._on_selected_track_changed()
		if not len(self.song.view.selected_track.devices):
			self._update_modswitcher()
	

	def _update_modswitcher(self):
		debug('update modswitcher, mod is:', self.modhandler.active_mod())
		if self.modhandler.active_mod():
			self._modswitcher.selected_mode = 'mod'
		else:
			self._modswitcher.selected_mode = 'translations'
	

	@listens('selected_mode')
	def _on_scale_change(self, mode):
		debug('new scale is:', mode, self._scale_mode.selected_mode)
		self._keygroup.scale = SCALES.index(self._scale_mode.selected_mode)
	

	@listens('value')
	def _on_octave_change(self, value):
		self._keygroup.offset = value
	

	#stupid hack....4 hours wasted on two buttons is too long, so we're doing this instead
	def _update_keygroup_colors(self):
		self._grid[5][7].send_value(2, force = True)
		self._grid[6][7].send_value(2, force = True)
	

	#everything below needs to be consolidated into transport component
	def _assign_tempo(self):
		self._grid[5][7].send_value(4, True)
		self._grid[6][7].send_value(4, True)
		self._tempo_up_value.subject = self._grid[5][7]
		self._tempo_down_value.subject = self._grid[6][7]
	

	def _deassign_tempo(self):
		self._tempo_up_value.subject and self._tempo_up_value.subject.turn_off()
		self._tempo_down_value.subject and self._tempo_down_value.subject.turn_off()
		self._tempo_up_value.subject = None
		self._tempo_down_value.subject = None
	

	@listens('value')
	def _tempo_up_value(self, value):
		if value:
			self.song.tempo = round(min(self.song.tempo + 1, 999))
	

	@listens('value')
	def _tempo_down_value(self, value):
		if value:
			self.song.tempo = round(max(self.song.tempo - 1, 20))
class DS1(LividControlSurface):


	_sysex_id = 16
	_model_name = 'DS1'


	def __init__(self, c_instance):
		super(DS1, self).__init__(c_instance)
		self._skin = Skin(DS1Colors)
		with self.component_guard():
			self._define_sysex()
			self._setup_controls()
			self._setup_background()
			self._setup_m4l_interface()
			self._setup_session_control()
			self._setup_mixer_control()
			self._setup_transport_control()
			self._setup_device_control()
			self._setup_session_recording_component()
			self._setup_main_modes()
	

	def _initialize_script(self):
		super(DS1, self)._initialize_script()
		self._main_modes.set_enabled(True)
		self._main_modes.selected_mode = 'Main'
	

	def _initialize_hardware(self):
		super(DS1, self)._initialize_hardware()
		self.local_control_off.enter_mode()
		self.encoder_absolute_mode.enter_mode()
		self.encoder_speed_sysex.enter_mode()
	


	def _define_sysex(self):
		self.encoder_speed_sysex = SendLividSysexMode(livid_settings = self._livid_settings, call = 'set_encoder_mapping', message = ENCODER_SPEED)
		self.encoder_absolute_mode = SendLividSysexMode(livid_settings = self._livid_settings, call = 'set_encoder_encosion_mode', message = [2])
		self.local_control_off = SendLividSysexMode(livid_settings = self._livid_settings, call = 'set_local_control', message = [0])

	

	def _setup_controls(self):
		is_momentary = True
		optimized = True
		resource = PrioritizedResource
		self._fader = [MonoEncoderElement(mapping_feedback_delay = -1, msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = DS1_FADERS[index], name = 'Fader_' + str(index), num = index, script = self, optimized_send_midi = optimized, resource_type = resource) for index in range(8)]
		self._dial = [[MonoEncoderElement(mapping_feedback_delay = -1, msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = DS1_DIALS[x][y], name = 'Dial_' + str(x) + '_' + str(y), num = x + (y*5), script = self, optimized_send_midi = optimized, resource_type = resource) for x in range(8)] for y in range(5)]
		self._side_dial = [MonoEncoderElement(mapping_feedback_delay = -1, msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = DS1_SIDE_DIALS[x], name = 'Side_Dial_' + str(x), num = x, script = self, optimized_send_midi = optimized, resource_type = resource) for x in range(4)]
		self._encoder = [MonoEncoderElement(mapping_feedback_delay = -1, msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = DS1_ENCODERS[x], name = 'Encoder_' + str(x), num = x, script = self, optimized_send_midi = optimized, resource_type = resource) for x in range(4)]
		self._encoder_button = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = DS1_ENCODER_BUTTONS[index], name = 'EncoderButton_' + str(index), script = self, skin = self._skin, optimized_send_midi = optimized, resource_type = resource) for index in range(4)]
		self._master_fader = MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = DS1_MASTER, name = 'MasterFader', num = 0, script = self, optimized_send_midi = optimized, resource_type = resource)
		self._button = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = DS1_BUTTONS[index], name = 'Button_' + str(index), script = self, skin = self._skin, optimized_send_midi = optimized, resource_type = resource) for index in range(16)]
		self._grid = [[MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = DS1_GRID[x][y], name = 'Button_' + str(x) + '_' + str(y), script = self, skin = self._skin, optimized_send_midi = optimized, resource_type = resource) for x in range(3)] for y in range(3)]
		self._dummy = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = 120+x, name = 'Dummy_Dial_' + str(x), num = x, script = self, optimized_send_midi = optimized, resource_type = resource) for x in range(5)]

		self._fader_matrix = ButtonMatrixElement(name = 'FaderMatrix', rows = [self._fader])
		self._top_buttons = ButtonMatrixElement(name = 'TopButtonMatrix', rows = [self._button[:8]])
		self._bottom_buttons = ButtonMatrixElement(name = 'BottomButtonMatrix', rows = [self._button[8:]])
		self._dial_matrix = ButtonMatrixElement(name = 'DialMatrix', rows = self._dial)
		self._side_dial_matrix = ButtonMatrixElement(name = 'SideDialMatrix', rows = [self._side_dial])
		self._encoder_matrix = ButtonMatrixElement(name = 'EncoderMatrix', rows = [self._encoder])
		self._encoder_button_matrix = ButtonMatrixElement(name = 'EncoderButtonMatrix', rows = [self._encoder_button])
		self._grid_matrix = ButtonMatrixElement(name = 'GridMatrix', rows = self._grid)
		self._selected_parameter_controls = ButtonMatrixElement(name = 'SelectedParameterControls', rows = [self._dummy + self._encoder[:1] + self._encoder[2:]])
	

	def _setup_background(self):
		self._background = BackgroundComponent(name = 'Background')
		self._background.layer = Layer(priority = 0, fader_matrix = self._fader_matrix, 
													top_buttons = self._top_buttons,
													bottom_buttons = self._bottom_buttons,
													dial_matrix = self._dial_matrix,
													side_dial_matrix = self._side_dial_matrix,
													encoder_button_matrix = self._encoder_button_matrix,
													grid_matrix = self._grid_matrix)
		self._background.set_enabled(True)
	

	def _setup_autoarm(self):
		self._auto_arm = AutoArmComponent(name='Auto_Arm')
		self._auto_arm.can_auto_arm_track = self._can_auto_arm_track
	

	def _tracks_to_use(self):
		return self.song.visible_tracks + self.song.return_tracks
	

	def _setup_session_control(self):
		self._session_ring = SessionRingComponent(num_tracks = 8, num_scenes = 1, tracks_to_use = self._tracks_to_use)
		self._session_ring.set_enabled(True)

		self._session_navigation = DS1SessionNavigationComponent(name = 'SessionNavigation', session_ring = self._session_ring)
		self._session_navigation._vertical_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._vertical_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._horizontal_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._horizontal_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
		self._session_navigation.layer = Layer(priority = 4, track_select_dial = ComboElement(control = self._encoder[1], modifier = [self._encoder_button[1]] ), up_button = self._grid[0][1], down_button = self._grid[0][2])
		self._session_navigation.set_enabled(False)
		
		self._session = DS1SessionComponent(session_ring = self._session_ring, auto_name = True)
		hasattr(self._session, '_enable_skinning') and self._session._enable_skinning()
		self._session.layer = Layer(priority = 4, scene_launch_buttons = self._grid_matrix.submatrix[1:2, 1:2])
		self._session.clips_layer = AddLayerMode(self._session, Layer(priority = 4, clip_launch_buttons = self._top_buttons, stop_track_clip_buttons = self._bottom_buttons))
		self._session.set_enabled(False)
	

	def _setup_mixer_control(self):

		self._mixer = MonoMixerComponent(name = 'Mixer', num_returns = 2, tracks_provider = self._session_ring, track_assigner = simple_track_assigner, invert_mute_feedback = True, auto_name = True, enable_skinning = True)
		self._mixer.master_strip().set_volume_control(self._master_fader)
		self._mixer.set_prehear_volume_control(self._side_dial[3])
		self._mixer.layer = Layer(volume_controls = self._fader_matrix, track_select_dial = self._encoder[1])
		self._strip = [self._mixer.channel_strip(index) for index in range(8)]
		for index in range(8):
			self._strip[index].layer = Layer(priority = 4, parameter_controls = self._dial_matrix.submatrix[index:index+1, :])
		self._mixer.selected_strip().layer = Layer(priority = 4, parameter_controls = self._selected_parameter_controls)
		self._mixer.master_strip().layer = Layer(priority = 4, parameter_controls = self._side_dial_matrix.submatrix[:3, :])
		self._mixer.main_layer = AddLayerMode(self._mixer, Layer(priority = 4, solo_buttons = self._bottom_buttons, mute_buttons = self._top_buttons))
		self._mixer.select_layer = AddLayerMode(self._mixer, Layer(priority = 4, arm_buttons = self._bottom_buttons, track_select_buttons = self._top_buttons))
		self.song.view.selected_track = self._mixer.channel_strip(0)._track 
		self._mixer.set_enabled(False)
	

	def _setup_transport_control(self):
		self._transport = DS1TransportComponent()
		self._transport.name = 'Transport'
		self._transport._record_toggle.view_transform = lambda value: 'Transport.RecordOn' if value else 'Transport.RecordOff'
		self._transport.layer = Layer(priority = 4, stop_button = self._grid[1][0], play_button = self._grid[0][0], record_button = self._grid[2][0])
		self._transport.set_enabled(True)
	

	def _setup_device_control(self):
		self._device = DeviceComponent(name = 'Device_Component', device_provider = self._device_provider, device_bank_registry = DeviceBankRegistry())

		self._device_navigator = DeviceNavigator(self._device_provider, self._mixer, self)
		self._device_navigator.name = 'Device_Navigator'
	

	def _setup_session_recording_component(self):
		self._clip_creator = ClipCreator()
		self._clip_creator.name = 'ClipCreator'
		self._recorder = SessionRecordingComponent(ViewControlComponent())
		self._recorder.set_enabled(True)
		self._recorder.layer = Layer(priority = 4, automation_button = self._grid[1][2], record_button  = self._grid[2][1],)
	

	def _setup_m4l_interface(self):
		self._m4l_interface = M4LInterfaceComponent(controls=self.controls, component_guard=self.component_guard, priority = 10)
		self._m4l_interface.name = "M4LInterface"
		self.get_control_names = self._m4l_interface.get_control_names
		self.get_control = self._m4l_interface.get_control
		self.grab_control = self._m4l_interface.grab_control
		self.release_control = self._m4l_interface.release_control
	

	def _setup_translations(self):
		controls = []
		for control in self.controls:
			controls.append(control)
		self._translations = TranslationComponent(controls, 10)
		self._translations.name = 'TranslationComponent'
		self._translations.set_enabled(False)
	

	def _setup_main_modes(self):
		self._main_modes = ModesComponent(name = 'MainModes')
		self._main_modes.add_mode('Main', [self._mixer, self._mixer.main_layer, self._session, self._session_navigation], cycle_mode_button_color = 'ModeButtons.Main')
		self._main_modes.add_mode('Select', [self._mixer, self._mixer.select_layer, self._session, self._session_navigation], cycle_mode_button_color = 'ModeButtons.Select')
		self._main_modes.add_mode('Clips', [self._mixer, self._session, self._session.clips_layer, self._session_navigation], cycle_mode_button_color = 'ModeButtons.Clips')
		self._main_modes.layer = Layer(priority = 4, cycle_mode_button = self._grid[2][2])
		self._main_modes.selected_mode = 'Main'
		self._main_modes.set_enabled(False)
	

	def _can_auto_arm_track(self, track):
		routing = track.current_input_routing
		return routing == 'Ext: All Ins' or routing == 'All Ins' or routing.startswith('DS1 Input')
		#self._main_modes.selected_mode in ['Sends', 'Device'] and
	

#	a
Exemple #23
0
class Cntrlr(LividControlSurface):
	__module__ = __name__
	__doc__ = " Monomodular controller script for Livid CNTRLR "


	_sysex_id = 8
	_model_name = 'Cntrlr'
	_host_name = 'Cntrlr'
	monomodular = None

	device_provider_class = ModDeviceProvider

	def __init__(self, *a, **k):
		super(Cntrlr, self).__init__(*a, **k)
		self._skin = Skin(CntrlrColors)
		self._device_selection_follows_track_selection = FOLLOW
		with self.component_guard():
			self._setup_controls()
			self._define_sysex()
			self._setup_background()
			#self._setup_autoarm()
			self._setup_viewcontrol()
			self._setup_session_control()
			self._setup_mixer_control()
			self._setup_transport_control()
			#self._setup_device_control()
			#self._setup_device_selector()
			#self._setup_session_recording_component()
			#self._setup_modes()
			self._setup_m4l_interface()
	

	def _initialize_script(self):
		super(Cntrlr, self)._initialize_script()
		self._connected = True
		#self._main_modes.selected_mode = 'MixMode'

		self._session_ring._update_highlight()
		self._session_ring.track_offset = 0
		if liveobj_valid(self.song.visible_tracks[0]):
			self.song.view.selected_track = self.song.visible_tracks[0]
	

	def _setup_controls(self):
		is_momentary = True
		optimized = True
		resource = PrioritizedResource
		self._fader = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_FADERS[index], name = 'Fader_' + str(index), num = index, script = self,  optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(8)]
		self._dial_left = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_KNOBS_LEFT[index], name = 'Dial_Left_' + str(index), num = CNTRLR_KNOBS_LEFT[index], script = self, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)]
		self._dial_right = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_KNOBS_RIGHT[index], name = 'Dial_Right_' + str(index), num = CNTRLR_KNOBS_RIGHT[index], script = self, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)]
		self._encoder = [CodecEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_DIALS[index], name = 'Encoder_' + str(index), num = CNTRLR_DIALS[index], script = self, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)] 
		self._encoder_button = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CNTRLR_DIAL_BUTTONS[index], name = 'Encoder_Button_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)]	
		self._grid = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CNTRLR_GRID[index], name = 'Grid_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(16)]
		self._button = [MonoButtonElement(is_momentary = is_momentary,msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CNTRLR_BUTTONS[index], name = 'Button_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(32)]
		self._knobs = self._dial_left + self._dial_right

		self._fader_matrix = ButtonMatrixElement(name = 'Fader_Matrix', rows = [self._fader])
		self._matrix = ButtonMatrixElement(name = 'Matrix', rows = [self._grid[index*4:(index*4)+4] for index in range(4)])
		self._knob_left_matrix = ButtonMatrixElement(name = 'Knob_Left_Matrix', rows = [self._dial_left[index*4:(index*4)+4] for index in range(3)])
		self._knob_right_matrix = ButtonMatrixElement(name = 'Knob_Right_Matrix', rows = [self._dial_right[index*4:(index*4)+4] for index in range(3)])
		self._dial_matrix = ButtonMatrixElement(name = 'Dial_Matrix', rows = [self._encoder[index*4:(index*4)+4] for index in range(3)])
		self._dial_button_matrix = ButtonMatrixElement(name = 'Dial_Button_Matrix', rows = [self._encoder_button[index*4:(index*4)+4] for index in range(1,3)])
		self._key_matrix = ButtonMatrixElement(name = 'Key_Matrix', rows = [self._button[0:16], self._button[16:32]])
		
		self._translated_controls = self._fader + self._knobs + self._encoder[4:] + self._grid + self._button
	

	def _setup_background(self):
		self._background = BackgroundComponent(name = 'Background')
		self._background.layer = Layer(priority = 3, matrix = self._matrix.submatrix[:,:], faders = self._fader_matrix.submatrix[:,:], left_knobs = self._knob_left_matrix.submatrix[:,:], right_knobs = self._knob_right_matrix.submatrix[:,:], dials = self._dial_matrix, dial_buttons = self._dial_button_matrix.submatrix[:,:], keys = self._key_matrix.submatrix[:,:])
		self._background.set_enabled(True)
	

	def _define_sysex(self):
		#self.encoder_navigation_on = SendLividSysexMode(livid_settings = self._livid_settings, call = 'set_encoder_encosion_mode', message = [13, 0, 0, 0]) 
		pass
	

	def _setup_transport_control(self):
		self._transport = CntrlrTransportComponent(name = 'Transport') 
		self._transport._play_toggle.view_transform = lambda value: 'Transport.PlayOn' if value else 'Transport.PlayOff'
		self._transport._record_toggle.view_transform = lambda value: 'Transport.RecordOn' if value else 'Transport.RecordOff'
		self._transport._nudge_up_toggle.view_transform = lambda value: 'Transport.NudgeOn' if value else 'Transport.NudgeOff'
		self._transport._nudge_down_toggle.view_transform = lambda value: 'Transport.NudgeOn' if value else 'Transport.NudgeOff'
		self._transport._loop_toggle.view_transform = lambda value: 'Transport.LoopOn' if value else 'Transport.LoopOff'
		self._transport.layer = Layer(priority = 4,
									play_button = self._button[28],
									stop_button = self._button[29],
									record_button = self._button[30],
									tap_tempo_button = self._button[31],
									nudge_up_button = self._button[3],
									nudge_down_button = self._button[19],
									loop_button = self._button[23])
		self._transport.set_enabled(True)
	

	def _setup_autoarm(self):
		self._auto_arm = CntrlrAutoArmComponent(name='Auto_Arm')
		#self._auto_arm._update_notification = lambda a: None
		self._auto_arm.can_auto_arm_track = self._can_auto_arm_track
	

	def _setup_session_recording_component(self):
		self._clip_creator = ClipCreator()
		self._clip_creator.name = 'ClipCreator'
		self._recorder = FixedLengthSessionRecordingComponent(clip_creator = self._clip_creator, view_controller = ViewControlComponent(), name = 'SessionRecorder') # is_enabled = False)
		self._recorder.main_layer = AddLayerMode(self._recorder, Layer(priority = 4, record_button = self._button[29]))
		#self._recorder.shift_layer = AddLayerMode(self._recorder, Layer(priority = 4, automation_button = self._button[29]))
		self._recorder.set_enabled(False)
	

	def _setup_session_control(self):
		self._session_ring = SessionRingComponent(num_tracks = 4, num_scenes = 4)
		self._session_ring.set_enabled(True)

		self._session_navigation = SessionNavigationComponent(name = 'SessionNavigation', session_ring = self._session_ring)

		self._session_navigation._vertical_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._vertical_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._horizontal_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._horizontal_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._vertical_paginator.scroll_up_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._vertical_paginator.scroll_up_button.disabled_color = 'Session.PageNavigationButtonOff'
		self._session_navigation._vertical_paginator.scroll_down_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._vertical_paginator.scroll_down_button.disabled_color = 'Session.PageNavigationButtonOff'
		self._session_navigation._horizontal_paginator.scroll_up_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._horizontal_paginator.scroll_up_button.disabled_color = 'Session.PageNavigationButtonOff'
		self._session_navigation._horizontal_paginator.scroll_down_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._horizontal_paginator.scroll_down_button.disabled_color = 'Session.PageNavigationButtonOff'

		self._session_navigation.layer = Layer(priority = 4,
									down_button = self._button[14],
									up_button = self._button[15],
									left_button = self._button[12],
									right_button = self._button[13])
		self._session_navigation.set_enabled(True)

		self._session = SessionComponent(session_ring = self._session_ring, auto_name = True)
		hasattr(self._session, '_enable_skinning') and self._session._enable_skinning()
		self._session.layer = Layer(priority = 4,
									clip_launch_buttons = self._matrix.submatrix[:,:])
		self._session.set_enabled(True)
	

	def _setup_mixer_control(self):
		self._mixer_session_ring = SessionRingComponent(num_tracks = 4, num_scenes = 4)
		self._mixer = MonoMixerComponent(name = 'Mixer', tracks_provider = self._mixer_session_ring, track_assigner = simple_track_assigner, invert_mute_feedback = True, auto_name = True, enable_skinning = True)

		self._mixer.layer = Layer(priority = 4, 
											solo_buttons = self._key_matrix.submatrix[8:11, 0],
											stop_clip_buttons = self._key_matrix.submatrix[:3, 0],
											track_select_buttons = self._key_matrix.submatrix[4:8, 0],)
		for strip in self._mixer._channel_strips:
			strip._on_select_button_double_clicked = self._toggle_view
		self._mixer.set_enabled(True)
	

	def _toggle_view(self, *a):
		debug('toggle_view')
		debug('Clip is visible:', self.application.view.is_view_visible('Detail/Clip'))
		debug('Device is visible:', self.application.view.is_view_visible('Detail/DeviceChain'))
		if self.application.view.is_view_visible('Detail/Clip'):
			self._view_control.show_view('Detail/DeviceChain')
		else:
			self._view_control.show_view('Detail/Clip')

	def _setup_device_control(self):
		self._device_selection_follows_track_selection = FOLLOW
		self._device = DeviceComponent(name = 'Device_Component', device_provider = self._device_provider, device_bank_registry = DeviceBankRegistry())
		self._device.layer = Layer(priority = 4, parameter_controls = self._dial_matrix.submatrix[:, 1:3],)
		#self._device.mod_layer = AddLayerMode(self._device, Layer(priority = 4, parameter_controls = self._dial_matrix.submatrix[:, 1:3],))
		self._device.main_layer = AddLayerMode(self._device, Layer(priority = 4, parameter_controls = self._dial_matrix.submatrix[:, 1:3], 
												on_off_button = self._encoder_button[4],
												bank_prev_button = self._encoder_button[6],
												bank_next_button = self._encoder_button[7],))
												#lock_button = self._encoder_button[5],
		self._device.set_enabled(False)

		self._device_navigator = DeviceNavigator(self._device_provider, self._mixer, self)
		self._device_navigator.name = 'Device_Navigator'
		self._device_navigator.select_dial_layer = AddLayerMode(self._device_navigator, Layer(priority = 6, device_select_dial = self._encoder[0],))
		self._device_navigator.main_layer = AddLayerMode(self._device_navigator, Layer(priority = 4, 
											prev_chain_button = self._encoder_button[8], 
											next_chain_button = self._encoder_button[9], 
											exit_button = self._encoder_button[10], 
											enter_button = self._encoder_button[11],))
		self._device_navigator.set_enabled(False)
	

	def _setup_device_selector(self):
		self._device_selector = DeviceSelectorComponent(self)
		self._device_selector.name = 'Device_Selector'
		#self._device_selector.select_layer = AddLayerMode(self._device_selector, Layer(priority = 6 , matrix = self._matrix.submatrix[:, :]))
		self._device_selector.select_layer = AddLayerMode(self._device_selector, Layer(priority = 6, matrix = ButtonMatrixElement(rows = [self._grid[:4],self._grid[4:8],self._grid[8:12],self._grid[12:14]])))
		self._device_selector.assign_layer = AddLayerMode(self._device_selector, Layer(priority = 7, assign_button = self._grid[14]))
		self._device_selector.set_enabled(False)
	

	def _setup_viewcontrol(self):
		self._view_control = ViewControlComponent(name='View_Control')
		#self._view_control.main_layer = AddLayerMode(self._view_control, Layer(priority = 5, 
		#																		scene_select_dial = self._encoder[2],
		#																		track_select_dial = self._encoder[3],))
		#self._view_control.main_layer = AddLayerMode(self._view_control, Layer(prev_track_button=self._button[24], 
		#											next_track_button= self._button[25], 
		#											next_scene_button=self._button[27], 
		#											prev_scene_button = self._button[26]))
		self._view_control.set_enabled(True)
	

	def _setup_modes(self):

		common = CompoundMode(self._mixer,
									self._session_ring)
		main_buttons=CompoundMode(self._mixer.main_buttons_layer, 
									self._transport,
									self._recorder,
									self._recorder.main_layer, 
									self._device,)
		shifted_main_buttons=CompoundMode(self._mixer.solo_buttons_layer, 
									self._recorder, 
									self._recorder.shift_layer,
									self._session.scene_launch_layer,
									self._device,)
		main_faders=CompoundMode(self._mixer.main_faders_layer, 
									self._mixer.master_fader_layer)
		main_dials=CompoundMode(self._view_control,
									self._view_control.main_layer,
									self._device_navigator,
									self._device_navigator.select_dial_layer,
									self.encoder_navigation_on)
		shifted_dials=CompoundMode(self._session_navigation,
									self._session_navigation.nav_dial_layer,
									self._device_navigator,
									self._device_navigator.select_dial_layer,
									self.encoder_navigation_on)

		self._modalt_mode = ModesComponent(name = 'ModAltMode')
		self._modalt_mode.add_mode('disabled', None)
		self._modalt_mode.add_mode('enabled', [tuple([self._enable_mod_alt, self._disable_mod_alt])], behaviour = CancellableBehaviourWithRelease(), cycle_mode_button_color = 'Mod.AltOn')
		self._modalt_mode.selected_mode = 'disabled'
		self._modalt_mode.set_enabled(False)
		self._modalt_mode.layer = Layer(priority = 4, enabled_button = self._encoder_button[1])

		self._modswitcher = ModesComponent(name = 'ModSwitcher')
		self._modswitcher.add_mode('mod', [self.modhandler, self._modalt_mode, main_faders, self._mixer.main_knobs_layer, self._device, main_dials, DelayMode(self.modhandler.update, delay = .5, parent_task_group = self._task_group)])
		self._modswitcher.add_mode('instrument', [self._instrument.shift_button_layer, main_buttons, main_faders, self._mixer.main_knobs_layer, self._device, self._device.main_layer, self._device_navigator, self._device_navigator.main_layer, self._device_navigator.select_dial_layer]) #self._instrument.shift_button_layer, self._optional_translations])
		self._modswitcher.selected_mode = 'instrument'
		self._modswitcher.set_enabled(False)

		self._instrument._main_modes = ModesComponent(name = 'InstrumentModes')
		self._instrument._main_modes.add_mode('disabled', [main_buttons, 
																					main_dials, 
																					self._device.main_layer, 
																					self._session, 
																					self._session, 
																					self._session.clip_launch_layer])
		self._instrument._main_modes.add_mode('drumpad', [self._instrument._drumpad.sequencer_layer, 
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_split', [self._instrument._drumpad.split_layer,
																					self._instrument._selected_session,
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_sequencer', [self._instrument._drumpad.sequencer_layer, 
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_shifted', [self._instrument._drumpad.sequencer_shift_layer, 
																					self._instrument.drumpad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('drumpad_split_shifted', [self._instrument._drumpad.split_layer, 
																					self._instrument.drumpad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('drumpad_sequencer_shifted', [self._instrument._drumpad.sequencer_shift_layer, 
																					self._instrument.drumpad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad', [self._instrument._keypad.sequencer_layer, 
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_split', [self._instrument._keypad.split_layer,
																					self._instrument._selected_session,
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_sequencer', [self._instrument._keypad.sequencer_layer, 
																					main_buttons,
																					self._device.main_layer,
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_shifted', [self._instrument._keypad.sequencer_shift_layer, 
																					self._instrument.keypad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad_split_shifted', [self._instrument._keypad.split_layer, 
																					self._instrument.keypad_shift_layer,
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad_sequencer_shifted', [self._instrument._keypad.sequencer_shift_layer, 
																					self._instrument.keypad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					shifted_dials])
		self._instrument._main_modes.add_mode('drumpad_session', [self._instrument._drumpad.sequencer_session_layer, 
																					main_buttons,
																					self._device.main_layer,
																					self._session,
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_split_session', [self._instrument._drumpad.split_session_layer,
																					self._instrument._selected_session,
																					main_buttons,
																					self._device.main_layer,
																					self._session,
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_sequencer_session', [self._instrument._drumpad.sequencer_session_layer, 
																					main_buttons,
																					self._device.main_layer,
																					self._session,  
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('drumpad_shifted_session', [self._instrument._drumpad.sequencer_session_shift_layer, 
																					self._instrument.drumpad_shift_layer, 
																					main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		self._instrument._main_modes.add_mode('drumpad_split_shifted_session', [self._instrument._drumpad.split_session_layer,
																					self._instrument.drumpad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		self._instrument._main_modes.add_mode('drumpad_sequencer_shifted_session', [self._instrument._drumpad.sequencer_session_shift_layer, 
																					self._instrument.drumpad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad_session', [self._instrument._keypad.sequencer_session_layer, 
																					main_buttons,
																					self._device.main_layer,
																					self._session, 
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_split_session', [self._instrument._keypad.split_session_layer,
																					self._instrument._selected_session,
																					main_buttons,
																					self._device.main_layer,
																					self._session,
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_sequencer_session', [self._instrument._keypad.sequencer_session_layer, 
																					main_buttons,
																					self._device.main_layer,
																					self._session, 
																					DelayMode(self._session.clip_launch_layer, delay = .1), 
																					main_dials])
		self._instrument._main_modes.add_mode('keypad_shifted_session', [self._instrument._keypad.sequencer_session_shift_layer, 
																					self._instrument.keypad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad_split_shifted_session', [self._instrument._keypad.split_session_layer, 
																					self._instrument.keypad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		self._instrument._main_modes.add_mode('keypad_sequencer_shifted_session', [self._instrument._keypad.sequencer_session_shift_layer,
																					self._instrument.keypad_shift_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])

		self._instrument._main_modes.add_mode('audioloop', [self._instrument.audioloop_layer, 
																					main_buttons,
																					self._device.main_layer,
																					main_dials,
																					self._session,
																					DelayMode(self._session.clip_launch_layer, delay = .1)])
		self._instrument._main_modes.add_mode('audioloop_shifted', [self._instrument.audioloop_layer, 
																					shifted_main_buttons,
																					self._device.main_layer,
																					self._session_zoom, 
																					shifted_dials])
		#self._instrument._main_modes.add_mode('audioloop_shifted_session', [self._instrument.audioloop_layer, self._session, shifted_main_buttons, main_dials, shifted_dials])
		self._instrument.register_component(self._instrument._main_modes)
		self._instrument._main_modes.selected_mode = 'disabled'
		self._instrument.set_enabled(True)

		self._main_modes = ModesComponent(name = 'MainModes')
		self._main_modes.add_mode('disabled', [self._background])
		self._main_modes.add_mode('MixMode', [common, 
													self._instrument, 
													self._instrument.shift_button_layer,
													self._mixer,
													main_faders, 
													self._mixer.main_knobs_layer,
													self._device,
													self._device.main_layer,
													self._device_navigator,
													self._device_navigator.main_layer,
													self._device_navigator.select_dial_layer])
		self._main_modes.add_mode('ModSwitcher', [common,
													main_faders, 
													main_dials, 
													self._mixer.main_knobs_layer,
													self._view_control,
													self._view_control.main_layer,
													self._device_navigator,
													self._device_navigator.select_dial_layer, 
													self.encoder_navigation_on, 
													self._modswitcher, 
													DelayMode(self._update_modswitcher, delay = .1)], 
													behaviour = ColoredCancellableBehaviourWithRelease(color = 'ModeButtons.ModSwitcher', off_color = 'ModeButtons.ModSwitcherDisabled'))
		self._main_modes.add_mode('Translations', [common, 
													main_faders, 
													main_dials,
													self._mixer.main_knobs_layer, 
													self._translations, 
													DelayMode(self._translations.selector_layer, delay = .1)], 
													behaviour = DefaultedBehaviour(default_mode = 'MixMode', color = 'ModeButtons.Translations', off_color = 'ModeButtons.TranslationsDisabled'))
		self._main_modes.add_mode('DeviceSelector', [common,
													self._device_selector,
													DelayMode(self._device_selector.select_layer, delay = .1),
													DelayMode(self.modhandler.lock_layer, delay = .1),
													DelayMode(self._device_selector.assign_layer, delay = .5), 
													main_buttons,
													main_dials, 
													main_faders, 
													self._mixer.main_knobs_layer, 
													self._device.main_layer,
													self._device_navigator,
													self._device_navigator.main_layer,
													self._device_navigator.select_dial_layer], 
													behaviour = ColoredCancellableBehaviourWithRelease(color = 'ModeButtons.DeviceSelector', off_color = 'ModeButtons.DeviceSelectorDisabled'))
		self._main_modes.layer = Layer(priority = 4, ModSwitcher_button = self._encoder_button[2], DeviceSelector_button = self._encoder_button[0], Translations_button = self._encoder_button[3]) #, 
		self._main_modes.selected_mode = 'disabled'
		self._main_modes.set_enabled(True)

		self._test.subject = self._instrument._main_modes
	

	def _setup_modes(self):
		pass
	

	def _setup_m4l_interface(self):
		self._m4l_interface = M4LInterfaceComponent(controls=self.controls, component_guard=self.component_guard, priority = 10)
		self._m4l_interface.name = "M4LInterface"
		self.get_control_names = self._m4l_interface.get_control_names
		self.get_control = self._m4l_interface.get_control
		self.grab_control = self._m4l_interface.grab_control
		self.release_control = self._m4l_interface.release_control
	

	def _can_auto_arm_track(self, track):
		routing = track.current_input_routing
		return routing == 'Ext: All Ins' or routing == 'All Ins' or routing.startswith('Cntrlr Input')
	

	def _get_num_tracks(self):
		return self.num_tracks
	



#	a
	def _setup_background(self):
		self._background = BackgroundComponent()
		self._background.layer = Layer(priority = 3, matrix = self._button_matrix, encoders = self._encoder_matrix, livid = self._livid, buttons = self._code_buttons, keys = self._code_keys)
		self._background.set_enabled(False)
class Codec(LividControlSurface):


	_sysex_id = 4
	_model_name = 'Code'
	_host_name = 'Codec'
	_version_check = 'b996'
	monomodular = None

	def __init__(self, c_instance, *a, **k):
		self.log_message = logger.warning
		super(Codec, self).__init__(c_instance, *a, **k)
		self._locked = False
		self._shift_button = None
		self._device_selection_follows_track_selection=FOLLOW
		self._leds_last = 0
		self._shift_latching = LatchingShiftedBehaviour if SHIFT_LATCHING else ShiftedBehaviour
		self._skin = Skin(CodecColors)
		with self.component_guard():
			self._define_sysex()
			self._setup_controls()
			self._setup_background()
			self._setup_mixer_controls()
			self._setup_device_navigator()
			self._setup_device_controls()
			self._setup_special_device_control() 
			self._setup_device_chooser()
			self._setup_device_selector()
			self._setup_send_reset()
			self._setup_default_buttons()
			self._setup_shift_modes()
			self._setup_mod()
			self._setup_modswitcher()
			self._setup_modes() 
			self._setup_m4l_interface()
		self._background.set_enabled(True)
	

	def _initialize_hardware(self):
		super(Codec, self)._initialize_hardware()
	

	def _initialize_script(self):
		super(Codec, self)._initialize_script()
		self._on_device_changed.subject = self._device_provider
		self._main_modes.set_enabled(True)
		self._main_modes.selected_mode = 'mix'
	

	def _define_sysex(self):
		self.fast_encoder_sysex = SendLividSysexMode(livid_settings = self._livid_settings, call = 'set_encoder_speed', message = FAST_ENCODER_MSG)
		self.normal_encoder_sysex = SendLividSysexMode(livid_settings = self._livid_settings, call = 'set_encoder_speed', message = NORMAL_ENCODER_MSG)
		self.slow_encoder_sysex = SendLividSysexMode(livid_settings = self._livid_settings, call = 'set_encoder_speed', message = SLOW_ENCODER_MSG)
	

	def _setup_controls(self):
		is_momentary = True
		optimized = False
		resource = PrioritizedResource
		self._livid = DoublePressElement(MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = LIVID, name = 'Livid_Button', script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge))
		self._dial = [[CodecEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CODE_DIALS[row][column], name = 'Dial_' + str(column) + '_' +	str(row), num = (column + (row*8)), script = self, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge)	for row in range(4)] for column in range(8)]
		self._button = [[MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CODE_BUTTONS[row][column], name = 'Button_' + str(column) + '_' + str(row), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for row in range(4)] for column in range(8)]
		self._column_button = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CODE_COLUMN_BUTTONS[index], name = 'Column_Button_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(8)]		
		self._row_button = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CODE_ROW_BUTTONS[index], name = 'Row_Button_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(4)]	
		self._code_keys = ButtonMatrixElement(name = 'Code_Keys', rows = [self._column_button])
		self._code_buttons = ButtonMatrixElement(name = 'Code_Buttons', rows = [self._row_button])
		self._encoder_matrix = ButtonMatrixElement(name = 'Encoder_Matrix', rows = [[self._dial[column][row] for column in range(8)] for row in range(4)])
		self._button_matrix = ButtonMatrixElement(name = 'Button_Matrix', rows = [[self._button[column][row] for column in range(8)] for row in range(4)])
	

	def _setup_background(self):
		self._background = BackgroundComponent()
		self._background.layer = Layer(priority = 3, matrix = self._button_matrix, encoders = self._encoder_matrix, livid = self._livid, buttons = self._code_buttons, keys = self._code_keys)
		self._background.set_enabled(False)
	

	def _setup_transport_control(self):
		self._transport = TransportComponent() 
		self._transport.name = 'Transport'
		self._transport.set_enabled(False)
	

	def _setup_mixer_controls(self):
		self._session_ring = SessionRingComponent(name = 'Session_Ring', num_tracks = 8, num_scenes = 0)
		self._session_navigation = SessionNavigationComponent(name = 'Session_Navigation', session_ring = self._session_ring)
		self._session_navigation.layer = Layer(priority = 4, left_button = self._button[6][0], right_button = self._button[7][0])
		self._session_navigation.set_enabled(False)
		#self._session = SessionComponent(name = 'Session', session_ring = self._session_ring)
		self._mixer = CodecMixerComponent(num_returns = 4, name = 'Mixer', tracks_provider = self._session_ring, invert_mute_feedback = True, auto_name = True)
		self._mixer._mix_layer = AddLayerMode(self._mixer, Layer(priority = 4, volume_controls = self._encoder_matrix.submatrix[:8,3],
									pan_controls = self._encoder_matrix.submatrix[:8,2],
									send_controls = self._encoder_matrix.submatrix[:8, :2],
									))
		self._mixer._solo_mute_layer = AddLayerMode(self._mixer, Layer(priority = 4, solo_buttons = self._button_matrix.submatrix[:8,2],
									mute_buttons = self._button_matrix.submatrix[:8,3],
									))
		self._mixer._select_layer = AddLayerMode(self._mixer, Layer(priority = 4, track_select_buttons = self._code_keys))
		self._mixer._sends_layer = AddLayerMode(self._mixer, Layer(priority = 4, send_controls = self._encoder_matrix.submatrix[:, :]))
		self._mixer.set_enabled(False)
	

	def _setup_device_navigator(self):
		self._device_navigator = DeviceNavigator(self._device_provider, self._mixer, self)
		self._device_navigator._dev1_layer = AddLayerMode(self._device_navigator, Layer(priority = 4, prev_button = self._button[4][0], next_button = self._button[5][0], prev_chain_button = self._button[6][0], next_chain_button = self._button[7][0]))
		self._device_navigator._dev2_layer = AddLayerMode(self._device_navigator, Layer(priority = 4, prev_button = self._button[4][1], next_button = self._button[5][1], prev_chain_button = self._button[6][1], next_chain_button = self._button[7][1]))
		self._device_navigator._dev3_layer = AddLayerMode(self._device_navigator, Layer(priority = 4, prev_button = self._button[4][2], next_button = self._button[5][2], prev_chain_button = self._button[6][2], next_chain_button = self._button[7][2]))
		self._device_navigator._dev4_layer = AddLayerMode(self._device_navigator, Layer(priority = 4, prev_button = self._button[4][3], next_button = self._button[5][3], prev_chain_button = self._button[6][3], next_chain_button = self._button[7][3]))
		self._device_navigator.set_enabled(False)
	

	def _setup_device_controls(self):
		self._device = [None for index in range(4)]
		for index in range(4):
			self._device[index] = CodecDeviceComponent(self, index+1, device_bank_registry = DeviceBankRegistry())
			self._device[index].name = 'CodecDevice_Component_' + str(index+1)
			self._device[index].layer = Layer(priority = 4, parameter_controls = self._encoder_matrix.submatrix[:, index],
												on_off_button = self._button[1][index],
												bank_prev_button = self._button[2][index],
												bank_next_button = self._button[3][index],
												)
			self._device[index]._nav_layer = AddLayerMode(self._device[index], Layer(priority = 4, nav_prev_button = self._button[6][index],
																					nav_next_button = self._button[7][index],))
			self._device[index].set_enabled(False)
	

	def _setup_special_device_control(self):
		self._special_device = SpecialCodecDeviceComponent(self, device_bank_registry = DeviceBankRegistry(), device_provider = self._device_provider)
		self._special_device.name = 'SpecialCodecDeviceComponent'
		self._is_active_device = True
		self._special_device.layer = Layer(priority = 4, parameter_controls = self._encoder_matrix.submatrix[:,:],
											on_off_button = self._button[1][0],
											bank_prev_button = self._button[4][0],
											bank_next_button = self._button[5][0],
											)
		self._special_device.set_enabled(False)
	

	def _setup_device_chooser(self):
		self._selected_device = self._device[0]
		self._last_selected_device = self._device[0]

		self._selected_device_modes = ModesComponent()
		self._selected_device_modes.add_mode('disabled', [None])
		self._selected_device_modes.add_mode('device_0', [self._device_navigator._dev1_layer], behaviour = DefaultedBehaviour())
		self._selected_device_modes.add_mode('device_1', [self._device_navigator._dev2_layer], behaviour = DefaultedBehaviour())
		self._selected_device_modes.add_mode('device_2', [self._device_navigator._dev3_layer], behaviour = DefaultedBehaviour())
		self._selected_device_modes.add_mode('device_3', [self._device_navigator._dev4_layer], behaviour = DefaultedBehaviour())
		self._selected_device_modes.layer = Layer(priority = 4, device_0_button = self._button[0][0], device_1_button = self._button[0][1], device_2_button = self._button[0][2], device_3_button = self._button[0][3])
		self._selected_device_modes.selected_mode = 'device_0'
		self._selected_device_modes.set_enabled(False)
		self._on_device_selector_mode_changed.subject = self._selected_device_modes
	

	def _setup_device_selector(self):
		self._device_selector = DeviceSelectorComponent(self)
		self._device_selector.name = 'Device_Selector'
		self._device_selector.layer = Layer(priority = 4, matrix = self._code_keys)
		self._device_selector.set_enabled(False)
	

	def _setup_send_reset(self):
		self._send_reset = CodecResetSendsComponent(self)
		self._send_reset.set_enabled(False)
		#self._send_reset.set_buttons(self._button)
	

	def _setup_default_buttons(self):
		self._value_default = ParameterDefaultComponent(script = self, dials = self._dial)
		self._value_default.layer = Layer(priority = 3, matrix = self._button_matrix)
		self._value_default.set_enabled(False)
	

	def _setup_shift_modes(self):
		self._main_shift_modes = ModesComponent(name = 'MainShiftModes')
		self._main_shift_modes.add_mode('disabled', [self.normal_encoder_sysex], cycle_mode_button_color = 'DefaultButton.Off')
		self._main_shift_modes.add_mode('enabled', [self.slow_encoder_sysex], cycle_mode_button_color = 'DefaultButton.On')  #, self._value_default
		self._main_shift_modes.layer = Layer(priority = 4, cycle_mode_button = self._livid)
		self._main_shift_modes.set_enabled(False)
		self._main_shift_modes.selected_mode = 'disabled'

		self._mod_shift_modes = ModesComponent(name = 'ModShiftModes')
		self._mod_shift_modes.layer = Layer(priority = 4, cycle_mode_button = self._livid)
		self._mod_shift_modes.set_enabled(False)
	

	def _setup_mod(self):
		self.monomodular = get_monomodular(self)
		self.monomodular.name = 'monomodular_switcher'
		self.modhandler = CodecModHandler(script = self, device_provider = self._device_provider)
		self.modhandler.name = 'ModHandler'
		self.modhandler.layer = Layer(priority = 4, code_grid = self._button_matrix.submatrix[:,:], code_encoder_grid = self._encoder_matrix.submatrix[:,:])
		self.modhandler.set_enabled(False)
		self.modhandler.code_buttons_layer = AddLayerMode(self.modhandler, Layer(priority = 5, code_buttons = self._code_buttons))
		self.modhandler.keys_layer = AddLayerMode(self.modhandler, Layer(priority = 5, key_buttons = self._code_keys))
		self.modhandler.code_keys_layer = AddLayerMode(self.modhandler, Layer(priority = 5, code_keys = self._code_buttons))
		self.modhandler.alt_layer = AddLayerMode(self.modhandler, Layer(priority = 4, lock_button = self._livid))
	

	def _setup_modswitcher(self):
		self._modswitcher = ModesComponent(name = 'ModSwitcher')
		self._modswitcher.add_mode('mod', [self.modhandler, self._mod_shift_modes])
		self._modswitcher.add_mode('special_device', [self._special_device, self._mixer, self._mixer._select_layer, self._main_shift_modes])
		self._modswitcher.selected_mode = 'special_device'
		self._modswitcher.set_enabled(False)

		self._mod_shift_modes.add_mode('disabled', [self.modhandler.keys_layer], cycle_mode_button_color = 'Mod.ShiftOff')
		self._mod_shift_modes.add_mode('enabled', [self.modhandler.code_keys_layer, self.modhandler.code_buttons_layer, tuple([self._send_mod_shift, self._release_mod_shift])], cycle_mode_button_color = 'Mod.ShiftOn')
		self._mod_shift_modes.selected_mode = 'disabled'
	

	def _setup_modes(self):
		self._main_modes = ModesComponent(name = 'MainModes')
		self._main_modes.add_mode('disabled', [])
		self._main_modes.add_mode('mix_shifted', [self._mixer, self._mixer._mix_layer, self._mixer._solo_mute_layer, self._device_selector, self._background], groups = ['shifted'], behaviour = self._shift_latching(color = 'Mode.Main'))
		self._main_modes.add_mode('mix', [self._mixer, self._mixer._mix_layer, self._mixer._select_layer, self._mixer._solo_mute_layer, self._session_navigation, self._background, self._main_shift_modes], behaviour = self._shift_latching(color = 'Mode.Main'))
		self._main_modes.add_mode('sends_shifted', [self._mixer, self._mixer._sends_layer, self._mixer._select_layer, self._device_selector, self._background], groups = ['shifted'], behaviour = self._shift_latching(color = 'Mode.Main'))
		self._main_modes.add_mode('sends', [self._mixer, self._mixer._sends_layer, self._mixer._select_layer, self._background, self._main_shift_modes], behaviour = self._shift_latching(color = 'Mode.Main'))
		self._main_modes.add_mode('device_shifted', [self._selected_device_modes, self._device_selector, self._device[0], self._device[1], self._device[2], self._device[3], self._device_selector, self._background], groups = ['shifted'], behaviour = self._shift_latching(color = 'Mode.Main'))
		self._main_modes.add_mode('device', [self._mixer, self._mixer._select_layer, self._selected_device_modes, self._device[0], self._device[1], self._device[2], self._device[3], self._background, self._mixer._select_layer, self._main_shift_modes], behaviour = self._shift_latching(color = 'Mode.Main'))
		self._main_modes.add_mode('special_device_shifted', [self._modswitcher, self._device_selector, self._background], groups = ['shifted'], behaviour = self._shift_latching(color = 'Mode.Main'))
		self._main_modes.add_mode('special_device', [self._modswitcher, self._background], behaviour = self._shift_latching(color = 'Mode.Main'))
		#self._main_modes.add_mode('select', [self.normal_encoder_sysex], behaviour = DelayedExcludingMomentaryBehaviour(excluded_groups = ['shifted']))
		self._main_modes.layer = Layer(priority = 4,
										mix_button = self._row_button[0],
										sends_button = self._row_button[1],
										device_button = self._row_button[2],
										special_device_button = self._row_button[3],
										)
		self._main_modes.selected_mode = 'disabled'
		self._main_modes.set_enabled(False)
	

	def _setup_m4l_interface(self):
		self._m4l_interface = M4LInterfaceComponent(controls=self.controls, component_guard=self.component_guard)
		self.get_control_names = self._m4l_interface.get_control_names
		self.get_control = self._m4l_interface.get_control
		self.grab_control = self._m4l_interface.grab_control
		self.release_control = self._m4l_interface.release_control
	

	@listens('selected_mode')
	def _on_device_selector_mode_changed(self, mode):
		if mode == 'disabled':
			for device in self._device:
				device.set_dynamic_device_provider(None)
		elif mode in DEVICE_COMPONENTS:
			active_device = self._device[DEVICE_COMPONENTS.index(self._selected_device_modes.selected_mode)]
			for device in self._device:
				if device is active_device:
					device.set_dynamic_device_provider(self._device_provider)
				else:
					device.set_dynamic_device_provider(None)
			if active_device.find_track(active_device._get_device()) == self.song.view.selected_track:
				active_device.display_device()
	

	@listens('device')
	def _on_device_changed(self):
		self._on_device_name_changed.subject = self._device_provider.device
		self.schedule_message(1, self._update_modswitcher)
	

	@listens('name')
	def _on_device_name_changed(self):
		for device in self._device:
			device.scan_all()
	

	def _on_selected_track_changed(self):
		super(Codec, self)._on_selected_track_changed()
		#self.schedule_message(1, self._update_modswitcher)
		if not len(self.song.view.selected_track.devices):
			self._update_modswitcher()
	

	def _update_modswitcher(self):
		debug('update modswitcher', self.modhandler.active_mod())
		if self.modhandler.active_mod():
			self._modswitcher.selected_mode = 'mod'
		else:
			self._modswitcher.selected_mode = 'special_device'
	

	"""general functionality"""
	def disconnect(self):
		self.log_message('<<<<<<<<<<<<<<<<<<<<<<<<< Codec log closed >>>>>>>>>>>>>>>>>>>>>>>>>')
		super(Codec, self).disconnect()
	

	def update_display(self):
		super(Codec, self).update_display()
		self.modhandler.send_ring_leds()
	

	def restart_monomodular(self):
		#self.log_message('restart monomodular')
		self.modhandler.disconnect()
		with self.component_guard():
			self._setup_mod()
	

	def _send_mod_shift(self):
		self.modhandler._shift_value(1)
	

	def _release_mod_shift(self):
		self.modhandler._shift_value(0)
class Launchpad_Pro_MK3(InstrumentControlMixin, NovationBase):
    model_family_code = ids.LP_PRO_MK3_FAMILY_CODE
    element_class = Elements
    session_class = SessionComponent
    mixer_class = MixerComponent
    channel_strip_class = ChannelStripComponent
    skin = skin
    suppress_layout_switch = False
    track_recording_class = FixedLengthTrackRecordingComponent

    def __init__(self, *a, **k):
        self._layout_to_restore = None
        self._can_restore_layout = False
        self._last_layout_bytes = ids.SESSION_LAYOUT_BYTES
        super(Launchpad_Pro_MK3, self).__init__(*a, **k)

    def disconnect(self):
        super(Launchpad_Pro_MK3, self).disconnect()
        self._auto_arm.set_enabled(False)
        self._elements.scale_feedback_switch.send_value(Rgb.GREEN.midi_value)

    def on_identified(self, midi_bytes):
        self._elements.firmware_mode_switch.send_value(sysex.DAW_MODE_BYTE)
        self._elements.layout_switch.send_value(self._last_layout_bytes)
        self._target_track_changed()
        self._drum_group_changed()
        self.set_feedback_channels(
            [DRUM_FEEDBACK_CHANNEL, SCALE_FEEDBACK_CHANNEL])
        self._setup_faders()
        super(Launchpad_Pro_MK3, self).on_identified(midi_bytes)

    def port_settings_changed(self):
        self._auto_arm.set_enabled(False)
        super(Launchpad_Pro_MK3, self).port_settings_changed()

    def _setup_faders(self):
        for i, fader_mode in enumerate(FADER_MODES):
            orientation, polarity = (
                sysex.FADER_HORIZONTAL_ORIENTATION,
                sysex.FADER_BIPOLAR) if fader_mode == u'pan' else (
                    sysex.FADER_VERTICAL_ORIENTATION, sysex.FADER_UNIPOLAR)
            self._elements.fader_setup_element.send_value(
                i, orientation, polarity)

    def _create_components(self):
        self._fixed_length_setting = FixedLengthSetting()
        self._fixed_length_recording = FixedLengthRecording(
            self.song, self._fixed_length_setting)
        with inject(fixed_length_recording=const(
                self._fixed_length_recording)).everywhere():
            super(Launchpad_Pro_MK3, self)._create_components()
            self._create_recording_modes()
        self._create_session_overview()
        self._create_auto_arm()
        self._create_background()
        self._create_device_navigation()
        self._create_device_parameters()
        self._create_print_to_clip()
        self._create_undo_redo()
        self._create_transport()
        self._create_clip_actions()
        self._create_quantization()
        self._create_fixed_length()
        self._create_drum_group()
        self._create_scale_pad_translator()
        self._create_mixer_modes()
        self._create_session_modes()
        self._create_note_modes()
        self._create_main_modes()
        self.__on_layout_switch_value.subject = self._elements.layout_switch

    def _create_session_overview(self):
        self._session_overview = SessionOverviewComponent(
            name=u'Session_Overview',
            is_enabled=False,
            session_ring=self._session_ring,
            enable_skinning=True,
            layer=Layer(button_matrix=u'clip_launch_matrix'))

    def _create_auto_arm(self):
        self._auto_arm = AutoArmComponent(name=u'Auto_Arm', is_enabled=False)

    def _create_background(self):
        self._background = BackgroundComponent(
            name=u'Background',
            is_enabled=False,
            add_nop_listeners=True,
            layer=Layer(clear_button=u'clear_button',
                        duplicate_button=u'duplicate_button',
                        quantize_button=u'quantize_button',
                        scene_launch_buttons=u'scene_launch_buttons',
                        priority=-1) +
            Layer(
                duplicate_button_with_shift=u'duplicate_button_with_shift',
                track_select_buttons_with_shift=
                u'track_select_buttons_with_shift',
                up_button_with_shift=u'up_button_with_shift',
                down_button_with_shift=u'down_button_with_shift',
                left_button_with_shift=u'left_button_with_shift',
                right_button_with_shift=u'right_button_with_shift',
                double_button=u'duplicate_button_with_shift',
                clear_button_with_shift=u'clear_button_with_shift',
                volume_button_with_shift=u'volume_button_with_shift',
                pan_button_with_shift=u'pan_button_with_shift',
                sends_button_with_shift=u'sends_button_with_shift',
                device_button_with_shift=u'device_button_with_shift',
                stop_clip_button_with_shift=u'stop_clip_button_with_shift',
                fixed_length_button_with_shift=u'fixed_length_button_with_shift'
            ))
        self._background.set_enabled(True)

    def _create_print_to_clip(self):
        self._print_to_clip = PrintToClipComponent(
            name=u'Print_To_Clip',
            is_enabled=False,
            layer=Layer(
                print_to_clip_control=u'print_to_clip_element',
                print_to_clip_enabler=u'print_to_clip_enabler_element'))
        self._print_to_clip.set_enabled(True)

    def _create_undo_redo(self):
        self._undo_redo = UndoRedoComponent(
            name=u'Undo_Redo',
            is_enabled=False,
            layer=Layer(undo_button=u'record_arm_button_with_shift',
                        redo_button=u'mute_button_with_shift'))
        self._undo_redo.undo_button.color = u'Action.Undo'
        self._undo_redo.undo_button.pressed_color = u'Action.UndoPressed'
        self._undo_redo.redo_button.color = u'Action.Redo'
        self._undo_redo.redo_button.pressed_color = u'Action.RedoPressed'
        self._undo_redo.set_enabled(True)

    def _create_transport(self):
        self._transport = TransportComponent(
            name=u'Transport',
            is_enabled=False,
            layer=Layer(play_button=u'play_button',
                        continue_playing_button=u'play_button_with_shift',
                        metronome_button=u'solo_button_with_shift',
                        capture_midi_button=u'record_button_with_shift',
                        tap_tempo_button=u'sends_button_with_shift'))
        self._transport.tap_tempo_button.color = u'Transport.TapTempo'
        self._transport.set_enabled(True)

    def _create_clip_actions(self):
        self._clip_actions = ClipActionsComponent(
            name=u'Clip_Actions',
            is_enabled=False,
            layer=Layer(duplicate_button=u'duplicate_button',
                        quantize_button=u'quantize_button',
                        double_loop_button=u'duplicate_button_with_shift'))

    def _create_quantization(self):
        self._quantization = QuantizationComponent(
            name=u'Quantization',
            is_enabled=False,
            layer=Layer(
                quantization_toggle_button=u'quantize_button_with_shift'))
        self._quantization.set_enabled(True)
        ClipActionsComponent.quantization_component = self._quantization
        ClipSlotComponent.quantization_component = self._quantization

    def _create_fixed_length(self):
        self._fixed_length = FixedLengthComponent(
            fixed_length_setting=self._fixed_length_setting,
            name=u'Fixed_Length',
            is_enabled=False,
            layer=Layer(fixed_length_button=u'fixed_length_button'))
        self._fixed_length.settings_component.layer = Layer(
            length_option_buttons=u'track_select_buttons')
        self._fixed_length.set_enabled(True)

    def _create_drum_group(self):
        self._drum_group = DrumGroupComponent(
            self._clip_actions,
            name=u'Drum_Group',
            is_enabled=False,
            translation_channel=DRUM_FEEDBACK_CHANNEL,
            layer=Layer(matrix=u'drum_pads'))
        self._drum_group.set_enabled(True)

    def _create_device_parameters(self):
        self._device_parameters = SimpleDeviceParameterComponent(
            name=u'Device_Parameters',
            is_enabled=False,
            device_bank_registry=self._device_bank_registry,
            layer=Layer(
                parameter_controls=u'device_button_faders',
                static_color_controls=u'device_button_fader_color_elements',
                stop_fader_control=u'stop_fader_element'),
            static_color_value=Rgb.DARK_BLUE.midi_value)
        self._device_parameters.set_enabled(True)

    def _create_device_navigation(self):
        self._device_navigation = SimpleDeviceNavigationComponent(
            name=u'Device_Navigation')

    def _create_scale_pad_translator(self):
        self._scale_pad_translator = ConfigurablePlayableComponent(
            SCALE_FEEDBACK_CHANNEL,
            name=u'Scale_Pads',
            is_enabled=False,
            layer=Layer(matrix=u'scale_pads'))
        self._scale_pad_translator.set_enabled(True)

    def _create_mixer_modes(self):
        self._mixer_modes = ModesComponent(
            name=u'Mixer_Modes',
            is_enabled=False,
            enable_skinning=True,
            layer=Layer(arm_button=u'record_arm_button',
                        mute_button=u'mute_button',
                        solo_button=u'solo_button',
                        volume_button=u'volume_button',
                        pan_button=u'pan_button',
                        sends_button=u'sends_button',
                        device_button=u'device_button',
                        stop_button=u'stop_clip_button'))
        self._mixer.layer = Layer(volume_controls=u'volume_button_faders',
                                  pan_controls=u'pan_button_faders',
                                  send_controls=u'sends_button_faders')
        reselect_track_select_mode = partial(setattr, self._mixer_modes,
                                             u'selected_mode', u'track_select')

        def restore_main_layout():
            if self._can_restore_layout and self._layout_to_restore:
                self._elements.layout_switch.send_value(
                    self._layout_to_restore)

        def add_track_select_button_mode(name,
                                         control=None,
                                         component=self._mixer):
            control_key = control if control else u'{}_buttons'.format(name)
            control_dict = {control_key: u'track_select_buttons'}
            self._mixer_modes.add_mode(
                name, (AddLayerMode(component, Layer(**control_dict)),
                       DelayMode(restore_main_layout, delay=0.1)),
                behaviour=ReenterBehaviour(
                    on_reenter=reselect_track_select_mode))

        add_track_select_button_mode(u'track_select')
        add_track_select_button_mode(u'arm')
        add_track_select_button_mode(u'mute')
        add_track_select_button_mode(u'solo')
        add_track_select_button_mode(u'stop',
                                     control=u'stop_track_clip_buttons',
                                     component=self._session)

        def switch_to_fader_layout(bank):
            fader_layout_bytes = (ids.FADER_LAYOUT_BYTE, bank, 0)
            self._elements.layout_switch.send_value(fader_layout_bytes)

        def add_fader_mode(name, bank, add_layer_mode, static_color=None):
            self._mixer_modes.add_mode(
                name,
                (add_layer_mode,
                 AddLayerMode(
                     self._mixer,
                     Layer(track_select_buttons=u'track_select_buttons')),
                 partial(self._mixer._update_send_control_colors),
                 partial(self._mixer.set_static_color_value,
                         static_color), partial(switch_to_fader_layout, bank)),
                behaviour=ReenterBehaviour(
                    on_reenter=reselect_track_select_mode))

        add_fader_mode(
            u'volume',
            0,
            AddLayerMode(
                self._mixer,
                Layer(
                    static_color_controls=u'volume_button_fader_color_elements'
                )),
            static_color=Rgb.GREEN.midi_value)
        add_fader_mode(
            u'pan', 1,
            AddLayerMode(
                self._mixer,
                Layer(
                    track_color_controls=u'pan_button_fader_color_elements')))
        add_fader_mode(
            u'sends', 2,
            AddLayerMode(
                self._mixer,
                Layer(send_select_buttons=u'scene_launch_buttons',
                      return_track_color_controls=
                      u'sends_button_fader_color_elements',
                      stop_fader_control=u'stop_fader_element')))
        add_fader_mode(
            u'device', 3,
            (AddLayerMode(
                self._background,
                Layer(up_button=u'up_button', down_button=u'down_button')),
             AddLayerMode(
                 self._device_navigation,
                 Layer(prev_button=u'left_button',
                       next_button=u'right_button')),
             AddLayerMode(self._device_parameters,
                          Layer(bank_select_buttons=u'scene_launch_buttons'))))
        self._mixer_modes.selected_mode = u'track_select'
        self._mixer_modes.set_enabled(True)

    def _create_session_modes(self):
        self._session_modes = ModesComponent(
            name=u'Session_Modes',
            is_enabled=False,
            layer=Layer(overview_button=u'session_mode_button'))
        self._session_modes.add_mode(
            u'launch',
            AddLayerMode(
                self._session,
                Layer(managed_select_button=u'shift_button',
                      managed_delete_button=u'clear_button',
                      managed_duplicate_button=u'duplicate_button',
                      managed_quantize_button=u'quantize_button',
                      managed_double_button=u'duplicate_button_with_shift',
                      scene_launch_buttons=u'scene_launch_buttons')))
        self._session_modes.add_mode(
            u'overview', (self._session_overview,
                          AddLayerMode(
                              self._session_navigation,
                              Layer(page_up_button=u'up_button',
                                    page_down_button=u'down_button',
                                    page_left_button=u'left_button',
                                    page_right_button=u'right_button'))),
            behaviour=MomentaryBehaviour())
        self._session_modes.selected_mode = u'launch'

    def _create_note_modes(self):
        self._note_modes = ModesComponent(name=u'Note_Modes', is_enabled=False)
        self._note_modes.add_mode(
            u'scale',
            AddLayerMode(self._clip_actions,
                         Layer(delete_button=u'clear_button')))
        self._note_modes.add_mode(
            u'drum',
            AddLayerMode(
                self._drum_group,
                Layer(scroll_up_button=u'left_button',
                      scroll_down_button=u'right_button',
                      scroll_page_up_button=u'up_button',
                      scroll_page_down_button=u'down_button',
                      delete_button=u'clear_button')))

    def _create_main_modes(self):
        self._main_modes = ModesComponent(name=u'Main_Modes', is_enabled=False)
        suppressed_arrow_button_mode = (AddLayerMode(
            self._background,
            Layer(left_button=u'left_button',
                  right_button=u'right_button',
                  up_button=u'up_button',
                  down_button=u'down_button')), )
        self._main_modes.add_mode(u'none', suppressed_arrow_button_mode)
        self._main_modes.add_mode(u'fader', None)
        self._main_modes.add_mode(u'session', self._session_modes)
        self._main_modes.add_mode(u'note',
                                  (self._note_modes, self._clip_actions))
        self._main_modes.add_mode(u'chord', suppressed_arrow_button_mode)
        self._main_modes.selected_mode = u'session'
        self._main_modes.set_enabled(True)
        self.__on_main_mode_changed.subject = self._main_modes

    @listens(u'selected_mode')
    def __on_main_mode_changed(self, mode):
        if mode == u'session':
            self._session_modes.selected_mode = u'launch'
        self._recording_modes.selected_mode = u'session' if mode == u'session' else u'track'
        self._update_controlled_track()
        self._auto_arm.set_enabled(self._is_instrument_mode())

    @listens(u'value')
    def __on_layout_switch_value(self, value):
        self._can_restore_layout = value[0] in LIVE_LAYOUT_BYTES
        if not self._can_restore_layout:
            return
        if value[0] == ids.FADER_LAYOUT_BYTE:
            self._main_modes.selected_mode = u'fader'
        else:
            self._layout_to_restore = value
            if self._mixer_modes.selected_mode in FADER_MODES:
                self._mixer_modes.selected_mode = u'track_select'
            if value in LAYOUT_BYTES_TO_MODE_NAMES_MAP:
                self._main_modes.selected_mode = LAYOUT_BYTES_TO_MODE_NAMES_MAP[
                    value]
            else:
                self._main_modes.selected_mode = u'none'
        self._last_layout_bytes = value

    def _drum_group_changed(self):
        drum_group = self._drum_group_finder.drum_group
        drum_group_valid = liveobj_valid(drum_group)
        self._drum_group.set_drum_group_device(drum_group)
        self._elements.layout_switch.send_value(
            ids.DRUM_LAYOUT_BYTES if drum_group_valid else ids.
            SCALE_LAYOUT_BYTES)
        self._note_modes.selected_mode = u'drum' if drum_group_valid else u'scale'

    def _is_instrument_mode(self):
        return self._main_modes.selected_mode in NOTE_MODE_NAMES

    def _feedback_velocity_changed(self, feedback_velocity):
        self._elements.scale_feedback_switch.send_value(feedback_velocity)
Exemple #27
0
class Launchkey_MK3(InstrumentControlMixin, NovationBase):
    element_class = Elements
    session_height = SESSION_HEIGHT
    mixer_class = MixerComponent
    channel_strip_class = ChannelStripComponent
    skin = skin
    suppress_layout_switch = False

    def __init__(self, *a, **k):
        self._is_small_model = False
        self._last_pad_layout_byte = midi.PAD_SESSION_LAYOUT
        self._last_pot_layout_byte = None
        self._last_fader_layout_byte = midi.VOLUME_LAYOUT
        super(Launchkey_MK3, self).__init__(*a, **k)

    def disconnect(self):
        self._elements.pad_layout_switch.send_value(midi.PAD_DRUM_LAYOUT)
        self._auto_arm.set_enabled(False)
        super(Launchkey_MK3, self).disconnect()

    def on_identified(self, midi_bytes):
        if self._last_pot_layout_byte is None:
            self._last_pot_layout_byte = midi.VOLUME_LAYOUT if self._is_small_model else midi.PAN_LAYOUT
            self._pot_modes.selected_mode = u'volume' if self._is_small_model else u'pan'
        self._elements.incontrol_mode_switch.send_value(midi.INCONTROL_ONLINE_VALUE)
        self._elements.pad_layout_switch.send_value(self._last_pad_layout_byte)
        self._elements.pot_layout_switch.send_value(self._last_pot_layout_byte)
        if not self._is_small_model:
            self._elements.fader_layout_switch.send_value(self._last_fader_layout_byte)
        self._target_track_changed()
        self._drum_group_changed()
        self._auto_arm.set_enabled(True)
        self.set_feedback_channels([DRUM_FEEDBACK_CHANNEL])
        super(Launchkey_MK3, self).on_identified(midi_bytes)

    def port_settings_changed(self):
        self._auto_arm.set_enabled(False)
        super(Launchkey_MK3, self).port_settings_changed()

    def _create_components(self):
        super(Launchkey_MK3, self)._create_components()
        self.register_slot(self._elements.incontrol_mode_switch, nop, u'value')
        self._create_auto_arm()
        self._create_background()
        self._create_notification()
        self._create_view_control()
        self._create_transport()
        self._create_recording_modes()
        self._create_undo()
        self._create_quantization()
        self._create_device()
        self._create_drum_group()
        self._pot_modes = self._create_pot_or_fader_modes(u'pot')
        self._create_stop_solo_mute_modes()
        self._create_pad_modes()
        if not self._is_small_model:
            self._fader_modes = self._create_pot_or_fader_modes(u'fader')
            self._setup_master_fader()
            self._create_fader_button_modes()

    def _setup_master_fader(self):
        strip = self._mixer.master_strip()
        strip.set_volume_control(self._elements.master_fader)
        strip.volume_display.set_control_element(self._elements.master_fader_parameter_value_display)
        self._elements.master_fader_parameter_name_display.display_message(u'Master Volume')

    def _create_session_navigation_layer(self):
        return Layer(up_button=u'up_button', down_button=u'down_button')

    def _create_session_layer(self):
        return super(Launchkey_MK3, self)._create_session_layer() + Layer(scene_launch_buttons=u'scene_launch_buttons')

    def _create_auto_arm(self):
        self._auto_arm = AutoArmComponent(name=u'Auto_Arm', is_enabled=False)

    def _create_background(self):
        self._background = BackgroundComponent(name=u'Background', is_enabled=False, add_nop_listeners=True, layer=Layer(secondary_up_button=u'secondary_up_button', secondary_down_button=u'secondary_down_button', device_select_button=u'device_select_button', unused_matrix=self._elements.device_select_matrix.submatrix[:, 1:], pot_parameter_name_displays=u'pot_parameter_name_displays', pot_parameter_value_displays=u'pot_parameter_value_displays', fader_parameter_name_displays=u'fader_parameter_name_displays', fader_parameter_value_displays=u'fader_parameter_value_displays'))
        self._background.set_enabled(True)

    def _create_notification(self):
        self._notification_component = NotificationComponent(name=u'Notifications', is_enabled=False, layer=Layer(display_lines=u'notification_display'))
        self._notification_component.set_enabled(True)

    def _create_view_control(self):
        self._view_control = NotifyingViewControlComponent(name=u'Track_Scroller', is_enabled=False, track_provider=self._session_ring, layer=Layer(prev_track_button=u'left_button', next_track_button=u'right_button'))
        self._view_control.set_enabled(True)
        self._session_ring_selection_linking = self.register_disconnectable(SessionRingSelectionLinking(session_ring=self._session_ring, selection_changed_notifier=self._view_control))

    def _create_transport(self):
        self._transport = TransportComponent(name=u'Transport', is_enabled=False, layer=Layer(play_button=u'play_button', alt_stop_button=u'stop_button', loop_button=u'loop_button', metronome_button=u'click_button', capture_midi_button=u'capture_midi_button'))
        self._transport.set_enabled(True)

    def _create_undo(self):
        self._undo = UndoRedoComponent(name=u'Undo', is_enabled=False, layer=Layer(undo_button=u'undo_button'))
        self._undo.set_enabled(True)

    def _create_quantization(self):
        self._quantization = QuantizationComponent(name=u'Quantization')
        self._clip_actions = ClipActionsComponent(name=u'Clip_Actions', is_enabled=False, layer=Layer(quantize_button=u'quantize_button'))
        self._clip_actions.set_enabled(True)
        ClipActionsComponent.quantization_component = self._quantization

    def _create_device(self):
        self._device = DeviceComponent(name=u'Device', is_enabled=False, show_notification=self._notification_component.show_notification, device_bank_registry=self._device_bank_registry, toggle_lock=self.toggle_lock, use_parameter_banks=True, layer=Layer(device_lock_button=u'device_lock_button'))
        self._device.set_enabled(True)

    def _create_drum_group(self):
        self._drum_group = DrumGroupComponent(name=u'Drum_Group', is_enabled=False, translation_channel=DRUM_FEEDBACK_CHANNEL, layer=Layer(matrix=u'drum_pads', scroll_page_up_button=u'up_button', scroll_page_down_button=u'down_button'))

    def _create_pot_or_fader_modes(self, modes_type_name):
        modes = ModesComponent(name=u'{}_Modes'.format(modes_type_name.title()), is_enabled=False, layer=Layer(mode_selection_control=u'{}_layout_switch'.format(modes_type_name)))
        elements_name = u'{}s'.format(modes_type_name)
        name_displays_element_name = u'{}_parameter_name_displays'.format(modes_type_name)
        value_displays_element_name = u'{}_parameter_value_displays'.format(modes_type_name)

        def add_pot_or_fader_mixer_mode(parameter_name):
            modes.add_mode(parameter_name, (partial(getattr(self._mixer, u'set_{}_parameter_name'.format(modes_type_name)), parameter_name.replace(u'_', u' ').title()), AddLayerMode(self._mixer, Layer(**{u'{}_controls'.format(parameter_name): elements_name,
              u'{}_parameter_name_displays'.format(modes_type_name): name_displays_element_name,
              u'{}_displays'.format(parameter_name): value_displays_element_name}))))

        modes.add_mode(u'dummy', None)
        add_pot_or_fader_mixer_mode(u'volume')
        modes.add_mode(u'device', AddLayerMode(self._device, Layer(parameter_controls=elements_name, parameter_name_displays=name_displays_element_name, parameter_value_displays=value_displays_element_name)))
        if modes_type_name == u'pot':
            add_pot_or_fader_mixer_mode(u'pan')
        else:
            modes.add_mode(u'pan', None)
        add_pot_or_fader_mixer_mode(u'send_a')
        add_pot_or_fader_mixer_mode(u'send_b')
        for i in range(4):
            modes.add_mode(u'custom{}'.format(i), None)

        modes.selected_mode = u'pan' if modes_type_name == u'pot' else u'volume'
        modes.set_enabled(True)
        self.register_slot(modes, getattr(self, u'_on_{}_mode_byte_changed'.format(modes_type_name)), u'mode_byte')
        return modes

    def _create_fader_button_modes(self):
        self._fader_button_modes = ModesComponent(name=u'Fader_Modes', is_enabled=False, support_momentary_mode_cycling=False, layer=Layer(cycle_mode_button=u'fader_button_modes_button'))
        self._fader_button_modes.add_mode(u'arm', AddLayerMode(self._mixer, Layer(arm_buttons=u'fader_buttons')), cycle_mode_button_color=u'DefaultButton.Off')
        self._fader_button_modes.add_mode(u'track_select', AddLayerMode(self._mixer, Layer(track_select_buttons=u'fader_buttons')), cycle_mode_button_color=u'DefaultButton.On')
        self._fader_button_modes.selected_mode = u'arm'
        self._fader_button_modes.set_enabled(True)

    def _create_stop_solo_mute_modes(self):
        self._stop_solo_mute_modes = ModesComponent(name=u'Stop_Solo_Mute_Modes', is_enabled=False, support_momentary_mode_cycling=False)
        lower_matrix_row = self._elements.clip_launch_matrix.submatrix[:, 1:]
        self._stop_solo_mute_modes.add_mode(u'launch', None, cycle_mode_button_color=u'Mode.Launch.On')
        self._stop_solo_mute_modes.add_mode(u'stop', AddLayerMode(self._session, Layer(stop_track_clip_buttons=lower_matrix_row)), cycle_mode_button_color=u'Session.StopClip')
        self._stop_solo_mute_modes.add_mode(u'solo', AddLayerMode(self._mixer, Layer(solo_buttons=lower_matrix_row)), cycle_mode_button_color=u'Mixer.SoloOn')
        self._stop_solo_mute_modes.add_mode(u'mute', AddLayerMode(self._mixer, Layer(mute_buttons=lower_matrix_row)), cycle_mode_button_color=u'Mixer.MuteOff')
        self._stop_solo_mute_modes.selected_mode = u'launch'
        self._stop_solo_mute_modes.set_enabled(True)
        self.__on_stop_solo_mute_mode_changed.subject = self._stop_solo_mute_modes

    def _create_pad_modes(self):
        self._pad_modes = ModesComponent(name=u'Pad_Modes', is_enabled=False, layer=Layer(mode_selection_control=u'pad_layout_switch'))
        suppress_scene_launch_buttons = AddLayerMode(self._background, layer=Layer(scene_launch_buttons=u'scene_launch_buttons'))
        suppress_all_buttons_around_pads = AddLayerMode(self._background, layer=Layer(scene_launch_buttons=u'scene_launch_buttons', up_button=u'up_button', down_button=u'down_button'))
        self._pad_modes.add_mode(u'dummy', suppress_all_buttons_around_pads)
        self._pad_modes.add_mode(u'drum', (suppress_scene_launch_buttons, self._drum_group))
        self._pad_modes.add_mode(u'session', LayerMode(self._stop_solo_mute_modes, layer=Layer(cycle_mode_button=self._elements.scene_launch_buttons_raw[1])))
        for i in range(6):
            self._pad_modes.add_mode(u'custom{}'.format(i), suppress_all_buttons_around_pads)

        upper_matrix_row = self._elements.device_select_matrix.submatrix[:, :1]
        self._pad_modes.add_mode(u'device_select', (suppress_scene_launch_buttons, self._device.show_device_name_and_bank, AddLayerMode(self._device, layer=Layer(bank_select_buttons=upper_matrix_row, prev_button=u'up_button', next_button=u'down_button'))))
        self._pad_modes.selected_mode = u'session'
        self._pad_modes.set_enabled(True)
        self.__on_pad_mode_changed.subject = self._pad_modes
        self.__on_pad_mode_byte_changed.subject = self._pad_modes

    @listens(u'selected_mode')
    def __on_pad_mode_changed(self, mode):
        self._recording_modes.selected_mode = u'track' if mode == u'drum' else u'session'
        self._update_controlled_track()

    @listens(u'selected_mode')
    def __on_stop_solo_mute_mode_changed(self, mode):
        if mode:
            self._notification_component.show_notification(u'Lower Pad Mode', mode.title())

    @listens(u'mode_byte')
    def __on_pad_mode_byte_changed(self, mode_byte):
        self._last_pad_layout_byte = mode_byte

    def _on_pot_mode_byte_changed(self, mode_byte):
        self._last_pot_layout_byte = mode_byte

    def _on_fader_mode_byte_changed(self, mode_byte):
        self._last_fader_layout_byte = mode_byte

    def _drum_group_changed(self):
        self._drum_group.set_drum_group_device(self._drum_group_finder.drum_group)

    def _target_track_changed(self):
        super(Launchkey_MK3, self)._target_track_changed()
        self._notification_component.show_notification(u'Track', self._target_track.target_track.name)

    def _is_instrument_mode(self):
        return self._pad_modes.selected_mode == u'drum'

    def _extract_product_id_bytes(self, midi_bytes):
        u""" Extends standard to deal with each model having a different ID byte, determine
        whether the model is one of the small models and compose the target product ID
        bytes based on the bytes that were received. """
        id_bytes = super(Launchkey_MK3, self)._extract_product_id_bytes(midi_bytes)
        model_id_byte = id_bytes[3]
        if id_bytes[:3] == sysex.NOVATION_MANUFACTURER_ID and model_id_byte in midi.MODEL_ID_BYTES and id_bytes[4:] == midi.MODEL_ID_BYTE_SUFFIX:
            self._is_small_model = model_id_byte in midi.SMALL_MODEL_ID_BYTES
            self._product_id_bytes = sysex.NOVATION_MANUFACTURER_ID + id_bytes[3:]
        return id_bytes
Exemple #28
0
class DS1(LividControlSurface):

    _sysex_id = 16
    _model_name = 'DS1'

    def __init__(self, c_instance):
        super(DS1, self).__init__(c_instance)
        self._skin = Skin(DS1Colors)
        with self.component_guard():
            self._define_sysex()
            self._setup_controls()
            self._setup_background()
            self._setup_m4l_interface()
            self._setup_session_control()
            self._setup_mixer_control()
            self._setup_transport_control()
            self._setup_device_control()
            self._setup_session_recording_component()
            self._setup_main_modes()

    def _initialize_script(self):
        super(DS1, self)._initialize_script()
        self._main_modes.set_enabled(True)
        self._main_modes.selected_mode = 'Main'

    def _initialize_hardware(self):
        super(DS1, self)._initialize_hardware()
        self.local_control_off.enter_mode()
        self.encoder_absolute_mode.enter_mode()
        self.encoder_speed_sysex.enter_mode()

    def _define_sysex(self):
        self.encoder_speed_sysex = SendLividSysexMode(
            livid_settings=self._livid_settings,
            call='set_encoder_mapping',
            message=ENCODER_SPEED)
        self.encoder_absolute_mode = SendLividSysexMode(
            livid_settings=self._livid_settings,
            call='set_encoder_encosion_mode',
            message=[2])
        self.local_control_off = SendLividSysexMode(
            livid_settings=self._livid_settings,
            call='set_local_control',
            message=[0])

    def _setup_controls(self):
        is_momentary = True
        optimized = True
        resource = PrioritizedResource
        self._fader = [
            MonoEncoderElement(mapping_feedback_delay=-1,
                               msg_type=MIDI_CC_TYPE,
                               channel=CHANNEL,
                               identifier=DS1_FADERS[index],
                               name='Fader_' + str(index),
                               num=index,
                               script=self,
                               optimized_send_midi=optimized,
                               resource_type=resource) for index in range(8)
        ]
        self._dial = [[
            MonoEncoderElement(mapping_feedback_delay=-1,
                               msg_type=MIDI_CC_TYPE,
                               channel=CHANNEL,
                               identifier=DS1_DIALS[x][y],
                               name='Dial_' + str(x) + '_' + str(y),
                               num=x + (y * 5),
                               script=self,
                               optimized_send_midi=optimized,
                               resource_type=resource) for x in range(8)
        ] for y in range(5)]
        self._side_dial = [
            MonoEncoderElement(mapping_feedback_delay=-1,
                               msg_type=MIDI_CC_TYPE,
                               channel=CHANNEL,
                               identifier=DS1_SIDE_DIALS[x],
                               name='Side_Dial_' + str(x),
                               num=x,
                               script=self,
                               optimized_send_midi=optimized,
                               resource_type=resource) for x in range(4)
        ]
        self._encoder = [
            MonoEncoderElement(mapping_feedback_delay=-1,
                               msg_type=MIDI_CC_TYPE,
                               channel=CHANNEL,
                               identifier=DS1_ENCODERS[x],
                               name='Encoder_' + str(x),
                               num=x,
                               script=self,
                               optimized_send_midi=optimized,
                               resource_type=resource) for x in range(4)
        ]
        self._encoder_button = [
            MonoButtonElement(is_momentary=is_momentary,
                              msg_type=MIDI_NOTE_TYPE,
                              channel=CHANNEL,
                              identifier=DS1_ENCODER_BUTTONS[index],
                              name='EncoderButton_' + str(index),
                              script=self,
                              skin=self._skin,
                              optimized_send_midi=optimized,
                              resource_type=resource) for index in range(4)
        ]
        self._master_fader = MonoEncoderElement(msg_type=MIDI_CC_TYPE,
                                                channel=CHANNEL,
                                                identifier=DS1_MASTER,
                                                name='MasterFader',
                                                num=0,
                                                script=self,
                                                optimized_send_midi=optimized,
                                                resource_type=resource)
        self._button = [
            MonoButtonElement(is_momentary=is_momentary,
                              msg_type=MIDI_NOTE_TYPE,
                              channel=CHANNEL,
                              identifier=DS1_BUTTONS[index],
                              name='Button_' + str(index),
                              script=self,
                              skin=self._skin,
                              optimized_send_midi=optimized,
                              resource_type=resource) for index in range(16)
        ]
        self._grid = [[
            MonoButtonElement(is_momentary=is_momentary,
                              msg_type=MIDI_NOTE_TYPE,
                              channel=CHANNEL,
                              identifier=DS1_GRID[x][y],
                              name='Button_' + str(x) + '_' + str(y),
                              script=self,
                              skin=self._skin,
                              optimized_send_midi=optimized,
                              resource_type=resource) for x in range(3)
        ] for y in range(3)]
        self._dummy = [
            MonoEncoderElement(msg_type=MIDI_CC_TYPE,
                               channel=CHANNEL,
                               identifier=120 + x,
                               name='Dummy_Dial_' + str(x),
                               num=x,
                               script=self,
                               optimized_send_midi=optimized,
                               resource_type=resource) for x in range(5)
        ]

        self._fader_matrix = ButtonMatrixElement(name='FaderMatrix',
                                                 rows=[self._fader])
        self._top_buttons = ButtonMatrixElement(name='TopButtonMatrix',
                                                rows=[self._button[:8]])
        self._bottom_buttons = ButtonMatrixElement(name='BottomButtonMatrix',
                                                   rows=[self._button[8:]])
        self._dial_matrix = ButtonMatrixElement(name='DialMatrix',
                                                rows=self._dial)
        self._side_dial_matrix = ButtonMatrixElement(name='SideDialMatrix',
                                                     rows=[self._side_dial])
        self._encoder_matrix = ButtonMatrixElement(name='EncoderMatrix',
                                                   rows=[self._encoder])
        self._encoder_button_matrix = ButtonMatrixElement(
            name='EncoderButtonMatrix', rows=[self._encoder_button])
        self._grid_matrix = ButtonMatrixElement(name='GridMatrix',
                                                rows=self._grid)
        self._selected_parameter_controls = ButtonMatrixElement(
            name='SelectedParameterControls',
            rows=[self._dummy + self._encoder[:1] + self._encoder[2:]])

    def _setup_background(self):
        self._background = BackgroundComponent(name='Background')
        self._background.layer = Layer(
            priority=0,
            fader_matrix=self._fader_matrix,
            top_buttons=self._top_buttons,
            bottom_buttons=self._bottom_buttons,
            dial_matrix=self._dial_matrix,
            side_dial_matrix=self._side_dial_matrix,
            encoder_button_matrix=self._encoder_button_matrix,
            grid_matrix=self._grid_matrix)
        self._background.set_enabled(True)

    def _setup_autoarm(self):
        self._auto_arm = AutoArmComponent(name='Auto_Arm')
        self._auto_arm.can_auto_arm_track = self._can_auto_arm_track

    def _tracks_to_use(self):
        return self.song.visible_tracks + self.song.return_tracks

    def _setup_session_control(self):
        self._session_ring = SessionRingComponent(
            num_tracks=8, num_scenes=1, tracks_to_use=self._tracks_to_use)
        self._session_ring.set_enabled(True)

        self._session_navigation = DS1SessionNavigationComponent(
            name='SessionNavigation', session_ring=self._session_ring)
        self._session_navigation._vertical_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
        self._session_navigation._vertical_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
        self._session_navigation._horizontal_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
        self._session_navigation._horizontal_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
        self._session_navigation.layer = Layer(
            priority=4,
            track_select_dial=ComboElement(control=self._encoder[1],
                                           modifier=[self._encoder_button[1]]),
            up_button=self._grid[0][1],
            down_button=self._grid[0][2])
        self._session_navigation.set_enabled(False)

        self._session = DS1SessionComponent(session_ring=self._session_ring,
                                            auto_name=True)
        hasattr(self._session,
                '_enable_skinning') and self._session._enable_skinning()
        self._session.layer = Layer(
            priority=4,
            scene_launch_buttons=self._grid_matrix.submatrix[1:2, 1:2])
        self._session.clips_layer = AddLayerMode(
            self._session,
            Layer(priority=4,
                  clip_launch_buttons=self._top_buttons,
                  stop_track_clip_buttons=self._bottom_buttons))
        self._session.set_enabled(False)

    def _setup_mixer_control(self):

        self._mixer = MonoMixerComponent(
            name='Mixer',
            num_returns=2,
            tracks_provider=self._session_ring,
            track_assigner=SimpleTrackAssigner(),
            invert_mute_feedback=True,
            auto_name=True,
            enable_skinning=True,
            channel_strip_component_type=MonoChannelStripComponent)
        self._mixer.master_strip().set_volume_control(self._master_fader)
        self._mixer.set_prehear_volume_control(self._side_dial[3])
        self._mixer.layer = Layer(volume_controls=self._fader_matrix,
                                  track_select_dial=self._encoder[1])
        self._strip = [self._mixer.channel_strip(index) for index in range(8)]
        if KNOBS_ARE_SENDS:
            for index in range(8):
                self._strip[index].layer = Layer(
                    priority=4,
                    send_controls=self._dial_matrix.submatrix[index:index +
                                                              1, :4],
                    pan_control=self._dial[4][index])
        else:
            for index in range(8):
                self._strip[index].layer = Layer(
                    priority=4,
                    parameter_controls=self._dial_matrix.submatrix[
                        index:index + 1, :])
        self._mixer.selected_strip().layer = Layer(
            priority=4, parameter_controls=self._selected_parameter_controls)
        self._mixer.master_strip().layer = Layer(
            priority=4,
            parameter_controls=self._side_dial_matrix.submatrix[:3, :])
        self._mixer.main_layer = AddLayerMode(
            self._mixer,
            Layer(priority=4,
                  solo_buttons=self._bottom_buttons,
                  mute_buttons=self._top_buttons))
        self._mixer.select_layer = AddLayerMode(
            self._mixer,
            Layer(priority=4,
                  arm_buttons=self._bottom_buttons,
                  track_select_buttons=self._top_buttons))
        self.song.view.selected_track = self._mixer.channel_strip(0)._track
        self._mixer.set_enabled(False)

    def _setup_transport_control(self):
        self._transport = DS1TransportComponent()
        self._transport.name = 'Transport'
        self._transport._record_toggle.view_transform = lambda value: 'Transport.RecordOn' if value else 'Transport.RecordOff'
        self._transport.layer = Layer(priority=4,
                                      stop_button=self._grid[1][0],
                                      play_button=self._grid[0][0],
                                      record_button=self._grid[2][0])
        self._transport.set_enabled(True)

    def _setup_device_control(self):
        self._device = DeviceComponent(
            name='Device_Component',
            device_provider=self._device_provider,
            device_bank_registry=DeviceBankRegistry())

        self._device_navigator = DeviceNavigator(self._device_provider,
                                                 self._mixer, self)
        self._device_navigator.name = 'Device_Navigator'

    def _setup_session_recording_component(self):
        self._clip_creator = ClipCreator()
        self._clip_creator.name = 'ClipCreator'
        self._recorder = SessionRecordingComponent(ViewControlComponent())
        self._recorder.set_enabled(True)
        self._recorder.layer = Layer(
            priority=4,
            automation_button=self._grid[1][2],
            record_button=self._grid[2][1],
        )

    def _setup_m4l_interface(self):
        self._m4l_interface = M4LInterfaceComponent(
            controls=self.controls,
            component_guard=self.component_guard,
            priority=10)
        self._m4l_interface.name = "M4LInterface"
        self.get_control_names = self._m4l_interface.get_control_names
        self.get_control = self._m4l_interface.get_control
        self.grab_control = self._m4l_interface.grab_control
        self.release_control = self._m4l_interface.release_control

    def _setup_translations(self):
        controls = []
        for control in self.controls:
            controls.append(control)
        self._translations = TranslationComponent(controls, 10)
        self._translations.name = 'TranslationComponent'
        self._translations.set_enabled(False)

    def _setup_main_modes(self):
        self._main_modes = ModesComponent(name='MainModes')
        self._main_modes.add_mode('Main', [
            self._mixer, self._mixer.main_layer, self._session,
            self._session_navigation
        ],
                                  cycle_mode_button_color='ModeButtons.Main')
        self._main_modes.add_mode('Select', [
            self._mixer, self._mixer.select_layer, self._session,
            self._session_navigation
        ],
                                  cycle_mode_button_color='ModeButtons.Select')
        self._main_modes.add_mode('Clips', [
            self._mixer, self._session, self._session.clips_layer,
            self._session_navigation
        ],
                                  cycle_mode_button_color='ModeButtons.Clips')
        self._main_modes.layer = Layer(priority=4,
                                       cycle_mode_button=self._grid[2][2])
        self._main_modes.selected_mode = 'Main'
        self._main_modes.set_enabled(False)

    def _can_auto_arm_track(self, track):
        routing = track.current_input_routing
        return routing == 'Ext: All Ins' or routing == 'All Ins' or routing.startswith(
            'DS1 Input')
Exemple #29
0
class ATOMSQ(ControlSurface):
    def __init__(self, *a, **k):
        super(ATOMSQ, self).__init__(*a, **k)
        with self.component_guard():
            self._elements = Elements()
            with inject(element_container=const(self._elements)).everywhere():
                self._create_background()
                self._create_transport()
                self._create_undo()
                self._create_view_toggle()
                self._create_device_parameters()
                self._create_translating_background()
                self._create_device_navigation()
                self._create_launch_and_stop()
                self._create_session()
                self._create_mixer()
                self._create_view_control()
                self._create_button_labels()
                self._create_record_modes()
                self._create_lower_pad_modes()
                self._create_main_modes()
        self.__on_main_view_changed.subject = self.application.view

    def disconnect(self):
        super(ATOMSQ, self).disconnect()
        self._send_midi(midi.NATIVE_MODE_OFF_MESSAGE)

    def port_settings_changed(self):
        self._send_midi(midi.NATIVE_MODE_ON_MESSAGE)
        if self._main_modes.selected_mode == b'instrument':
            self.schedule_message(
                1, self._elements.upper_firmware_toggle_switch.send_value, 1)
        if self._main_modes.selected_mode != b'song':
            self.schedule_message(
                1, self._elements.lower_firmware_toggle_switch.send_value, 1)
        super(ATOMSQ, self).port_settings_changed()

    def _create_background(self):
        self._background = BackgroundComponent(
            name=b'Background',
            is_enabled=False,
            add_nop_listeners=True,
            layer=Layer(**{name: name
                           for name in BANK_BUTTON_NAMES}))
        self._background.set_enabled(True)

    def _create_transport(self):
        self._transport = TransportComponent(
            name=b'Transport',
            is_enabled=False,
            layer=Layer(scroll_encoder=b'display_encoder',
                        play_button=b'play_button',
                        loop_button=b'play_button_with_shift',
                        stop_button=b'stop_button',
                        metronome_button=b'click_button',
                        capture_midi_button=b'record_button_with_shift',
                        prev_cue_button=b'display_left_button',
                        next_cue_button=b'display_right_button',
                        shift_button=b'shift_button'))
        self._transport.set_enabled(True)

    def _create_undo(self):
        self._undo = UndoRedoComponent(
            name=b'Undo',
            is_enabled=False,
            layer=Layer(undo_button=b'stop_button_with_shift'))
        self._undo.set_enabled(True)

    def _create_view_toggle(self):
        self._view_toggle = ViewToggleComponent(
            name=b'View_Toggle',
            is_enabled=False,
            layer=Layer(main_view_toggle_button=b'bank_a_button',
                        browser_view_toggle_button=b'bank_b_button',
                        detail_view_toggle_button=b'bank_d_button',
                        clip_view_toggle_button=b'bank_h_button'))

    def _create_device_parameters(self):
        self._device_parameters = SimpleDeviceParameterComponent(
            name=b'Device_Parameters',
            device_bank_registry=self._device_bank_registry,
            toggle_lock=self.toggle_lock,
            layer=Layer(device_name_display=b'device_name_display'),
            is_enabled=False)
        self._device_parameters.set_enabled(True)

    def _create_translating_background(self):
        self._translating_background = TranslatingBackgroundComponent(
            name=b'Translating_Background',
            is_enabled=False,
            add_nop_listeners=True,
            layer=Layer(encoders=b'encoders',
                        channel_selection_buttons=b'display_buttons'))

    def _create_device_navigation(self):
        self._device_navigation = SimpleDeviceNavigationComponent(
            name=b'Device_Navigation',
            is_enabled=False,
            layer=Layer(prev_button=b'display_buttons_raw[1]',
                        next_button=b'display_buttons_raw[2]'))

    def _create_launch_and_stop(self):
        self._launch_and_stop = LaunchAndStopComponent(
            name=b'Launch_And_Stop',
            is_enabled=False,
            layer=Layer(clip_launch_button=b'display_buttons_raw[3]',
                        scene_launch_button=b'display_buttons_raw[4]',
                        track_stop_button=b'display_buttons_raw[5]'))

    def _create_session(self):
        self._session_ring = SessionRingComponent(name=b'Session_Ring',
                                                  num_tracks=SESSION_WIDTH,
                                                  num_scenes=SESSION_HEIGHT)
        self._session = SessionComponent(
            name=b'Session',
            is_enabled=False,
            session_ring=self._session_ring,
            layer=Layer(clip_launch_buttons=b'upper_pads'))
        self._session_navigation = SessionNavigationComponent(
            name=b'Session_Navigation',
            is_enabled=False,
            session_ring=self._session_ring,
            layer=Layer(up_button=b'up_button_with_shift',
                        down_button=b'down_button_with_shift'))
        self._session_navigation.set_enabled(True)

    def _create_mixer(self):
        self._mixer = MixerComponent(
            name=b'Mixer',
            auto_name=True,
            tracks_provider=self._session_ring,
            track_assigner=SimpleTrackAssigner(),
            channel_strip_component_type=ChannelStripComponent)
        self._mixer.selected_strip().layer = Layer(
            track_name_display=b'track_name_display')
        self._mixer.set_enabled(True)

    def _create_view_control(self):
        self._view_control = NotifyingViewControlComponent(
            name=b'View_Control',
            is_enabled=False,
            track_provider=self._session_ring,
            enable_skinning=False,
            layer=Layer(next_track_button=b'right_button',
                        prev_track_button=b'left_button',
                        next_scene_button=b'down_button',
                        prev_scene_button=b'up_button'))
        self._view_control.set_enabled(True)
        self._session_ring_selection_linking = self.register_disconnectable(
            SessionRingSelectionLinking(
                session_ring=self._session_ring,
                selection_changed_notifier=self._view_control))

    def _create_button_labels(self):
        self._button_labels = ButtonLabelsComponent(
            is_enabled=False,
            layer=Layer(display_lines=b'button_label_display_matrix'))
        self._button_labels.set_enabled(True)

    def _create_record_modes(self):
        self._session_record = SessionRecordingComponent(
            name=b'Session_Record',
            is_enabled=False,
            layer=Layer(record_button=b'record_button'))
        self._record_modes = ModesComponent(name=b'Record_Modes')
        self._record_modes.add_mode(b'session',
                                    EnablingMode(self._session_record))
        self._record_modes.add_mode(
            b'arrange',
            AddLayerMode(self._transport,
                         layer=Layer(record_button=b'record_button')))
        self.__on_main_view_changed()

    def _create_lower_pad_modes(self):
        self._lower_pad_modes = ModesComponent(
            name=b'Lower_Pad_Modes',
            is_enabled=False,
            layer=Layer(cycle_mode_button=b'minus_button'))
        self._lower_pad_modes.add_mode(
            b'select',
            AddLayerMode(self._mixer,
                         Layer(track_select_buttons=b'lower_pads')),
            cycle_mode_button_color=b'Session.StopClipDisabled')
        self._lower_pad_modes.add_mode(
            b'stop',
            AddLayerMode(self._session,
                         Layer(stop_track_clip_buttons=b'lower_pads')),
            cycle_mode_button_color=b'Session.StopClip')
        self._lower_pad_modes.selected_mode = b'select'

    def _create_main_modes(self):
        self._main_modes = ModesComponent(
            name=b'Main_Modes',
            is_enabled=False,
            layer=Layer(song_button=b'song_mode_button',
                        instrument_button=b'instrument_mode_button',
                        editor_button=b'editor_mode_button',
                        user_button=b'user_mode_button'))
        device_params_mode = AddLayerMode(
            self._device_parameters, Layer(parameter_controls=b'encoders'))
        enable_lower_fw_functions = partial(
            self._elements.lower_firmware_toggle_switch.send_value, 1)
        disable_upper_fw_functions = partial(
            self._elements.upper_firmware_toggle_switch.send_value, 0)
        self._main_modes.add_mode(
            b'song',
            (partial(self._elements.lower_firmware_toggle_switch.send_value,
                     0), disable_upper_fw_functions,
             self._elements.display_buttons.reset, self._view_toggle,
             self._launch_and_stop, self._session, self._lower_pad_modes,
             AddLayerMode(self._session.scene(0),
                          Layer(launch_button=b'plus_button')),
             AddLayerMode(
                 self._mixer.selected_strip(),
                 Layer(volume_control=b'encoders_raw[0]',
                       pan_control=b'encoders_raw[1]',
                       send_controls=self._elements.encoders.submatrix[2:, :],
                       solo_button=b'display_buttons_raw[0]',
                       mute_button=b'display_buttons_raw[1]',
                       arm_button=b'display_buttons_raw[2]')),
             AddLayerMode(self._mixer,
                          Layer(crossfader_control=b'touch_strip'))))
        self._main_modes.add_mode(
            b'instrument',
            (enable_lower_fw_functions,
             partial(self._elements.upper_firmware_toggle_switch.send_value,
                     1), device_params_mode))
        self._main_modes.add_mode(
            b'editor',
            (enable_lower_fw_functions, disable_upper_fw_functions,
             device_params_mode, self._device_navigation,
             AddLayerMode(
                 self._device_parameters,
                 Layer(device_lock_button=b'display_buttons_raw[0]',
                       device_on_off_button=b'display_buttons_raw[3]',
                       prev_bank_button=b'display_buttons_raw[4]',
                       next_bank_button=b'display_buttons_raw[5]'))))
        self._main_modes.add_mode(
            b'user', (enable_lower_fw_functions, disable_upper_fw_functions,
                      self._translating_background))
        self._main_modes.selected_mode = b'instrument'
        self._main_modes.set_enabled(True)
        self.__on_main_modes_changed.subject = self._main_modes

    @listens(b'selected_mode')
    def __on_main_modes_changed(self, mode):
        self._button_labels.show_button_labels_for_mode(mode)
        self._elements.track_name_display.clear_send_cache()
        self._elements.device_name_display.clear_send_cache()

    @listens(b'is_view_visible', b'Session')
    def __on_main_view_changed(self):
        if self.application.view.is_view_visible(b'Session'):
            self._record_modes.selected_mode = b'session'
        else:
            self._record_modes.selected_mode = b'arrange'
Exemple #30
0
	def _setup_background(self):
		self._background = BackgroundComponent(name = 'Background')
		self._background.layer = Layer(priority = 3, matrix = self._matrix.submatrix[:,:], faders = self._fader_matrix.submatrix[:,:], left_knobs = self._knob_left_matrix.submatrix[:,:], right_knobs = self._knob_right_matrix.submatrix[:,:], dials = self._dial_matrix, dial_buttons = self._dial_button_matrix.submatrix[:,:], keys = self._key_matrix.submatrix[:,:])
		self._background.set_enabled(True)
class Oxygen_Pro(IdentifiableControlSurface):
    session_height = 2
    session_width = 8
    live_mode_byte = midi.LIVE_MODE_BYTE
    pad_ids = ((40, 41, 42, 43, 48, 49, 50, 51), (36, 37, 38, 39, 44, 45, 46, 47))
    device_parameter_component = SimpleDeviceParameterComponent
    has_session_component = True

    def __init__(self, *a, **k):
        (super(Oxygen_Pro, self).__init__)(a, product_id_bytes=midi.M_AUDIO_MANUFACTURER_ID + (0, ), **k)
        self._last_selected_knob_mode = 'device'
        with self.component_guard():
            self._elements = Elements(self.session_height, self.session_width, self.pad_ids)
            with inject(element_container=(const(self._elements))).everywhere():
                self._create_background()
                self._create_transport()
                self._create_undo_redo()
                self._create_session()
                self._create_mixer()
                self._create_device_parameters()
                self._create_record_modes()
                self._create_button_modes()
                self._create_knob_modes()
                self._create_takeover_modes()
        self._Oxygen_Pro__on_main_view_changed.subject = self.application.view

    def on_identified(self, response_bytes):
        self._elements.firmware_mode_switch.send_value(self.live_mode_byte)
        self._elements.control_mode_switch.send_value(midi.RECORD_MODE_BYTE)
        self._elements.control_mode_switch.send_value(midi.DEVICE_MODE_BYTE)
        self._elements.led_control_switch.send_value(midi.LED_ENABLE_BYTE)
        self._elements.led_mode_switch.send_value(midi.SOFTWARE_CONTROL_BYTE)
        self._button_modes.selected_mode = 'arm'
        self._knob_modes.selected_mode = 'device'
        if self.has_session_component:
            self._session_ring.set_enabled(True)
        super(Oxygen_Pro, self).on_identified(response_bytes)

    def port_settings_changed(self):
        if self.has_session_component:
            self._session_ring.set_enabled(False)
        super(Oxygen_Pro, self).port_settings_changed()

    def _create_background(self):
        self._background = BackgroundComponent(name='Background',
          is_enabled=False,
          add_nop_listeners=True,
          layer=Layer(shift_button='shift_button'))
        self._background.set_enabled(True)

    def _create_transport(self):
        self._transport = TransportComponent(name='Transport',
          is_enabled=False,
          layer=Layer(loop_button='loop_button',
          stop_button='stop_button',
          play_button='play_button',
          metronome_button='metronome_button',
          seek_forward_button='fastforward_button',
          seek_backward_button='rewind_button'))
        self._transport.set_enabled(True)

    def _create_undo_redo(self):
        self._undo_redo = UndoRedoComponent(name='Undo_Redo',
          is_enabled=False,
          layer=Layer(undo_button='back_button'))
        self._undo_redo.set_enabled(True)

    def _create_session(self):
        self._session_ring = SessionRingComponent(name='Session_Ring',
          is_enabled=False,
          num_tracks=(self.session_width),
          num_scenes=(self.session_height))
        if self.has_session_component:
            self._session = SessionComponent(name='Session',
              is_enabled=False,
              session_ring=(self._session_ring),
              layer=Layer(clip_launch_buttons='pads',
              scene_launch_buttons='scene_launch_buttons',
              selected_scene_launch_button='encoder_push_button',
              scene_encoder='encoder_with_encoder_push'))
            self._session.set_enabled(True)
        self._session_navigation = SessionNavigationComponent(name='Session_Navigation',
          is_enabled=False,
          session_ring=(self._session_ring),
          layer=Layer(left_button='bank_left_button',
          right_button='bank_right_button',
          scene_encoder='encoder'))
        self._session_navigation.set_enabled(True)

    def _create_mixer(self):
        self._mixer = MixerComponent(name='Mixer',
          is_enabled=False,
          auto_name=True,
          channel_strip_component_type=ChannelStripComponent,
          tracks_provider=(self._session_ring),
          track_assigner=(SimpleTrackAssigner()),
          layer=Layer(volume_controls='faders'))
        self._mixer.master_strip().set_volume_control(self._elements.master_fader)
        self._mixer.set_enabled(True)

    def _create_device_parameters(self):
        self._device_parameters = self.device_parameter_component(name='Device_Parameters',
          is_enabled=False,
          layer=Layer(parameter_controls='knobs'))

    def _create_record_modes(self):
        self._session_record = SessionRecordingComponent(name='Session_Record',
          is_enabled=False,
          layer=Layer(record_button='record_button'))
        self._record_modes = ModesComponent(name='Record_Modes')
        self._record_modes.add_mode('session', EnablingMode(self._session_record))
        self._record_modes.add_mode('arrange', AddLayerMode((self._transport), layer=Layer(record_button='record_button')))
        self._Oxygen_Pro__on_main_view_changed()

    def _create_button_modes(self):
        self._button_modes = ModesComponent(name='Button_Modes',
          is_enabled=False,
          layer=Layer(off_button='off_mode_button',
          arm_button='arm_mode_button',
          track_select_button='track_select_mode_button',
          mute_button='mute_mode_button',
          solo_button='solo_mode_button'))
        self._button_modes.add_mode('off', None, behaviour=(ImmediateBehaviour()))
        self._button_modes.add_mode('arm',
          AddLayerMode((self._mixer), layer=Layer(arm_buttons='fader_buttons')),
          behaviour=(ImmediateBehaviour()))
        self._button_modes.add_mode('track_select',
          AddLayerMode((self._mixer), layer=Layer(track_select_buttons='fader_buttons')),
          behaviour=(ImmediateBehaviour()))
        self._button_modes.add_mode('mute',
          AddLayerMode((self._mixer), layer=Layer(mute_buttons='fader_buttons')),
          behaviour=(ImmediateBehaviour()))
        self._button_modes.add_mode('solo',
          AddLayerMode((self._mixer), layer=Layer(solo_buttons='fader_buttons')),
          behaviour=(ImmediateBehaviour()))
        self._button_modes.selected_mode = 'arm'
        self._button_modes.set_enabled(True)

    def _create_knob_modes(self):
        self._knob_modes = ModesComponent(name='Knob_Modes',
          is_enabled=False,
          layer=Layer(volume_button='volume_mode_button',
          pan_button='pan_mode_button',
          sends_button='sends_mode_button',
          device_button='device_mode_button'))
        self._knob_modes.add_mode('volume',
          AddLayerMode((self._mixer), layer=Layer(volume_controls='knobs')),
          behaviour=(ImmediateBehaviour()))
        self._knob_modes.add_mode('pan',
          AddLayerMode((self._mixer), layer=Layer(pan_controls='knobs')),
          behaviour=(ImmediateBehaviour()))
        self._knob_modes.add_mode('sends',
          AddLayerMode((self._mixer), layer=Layer(send_controls='knobs')),
          behaviour=ReenterBehaviour(on_reenter=(self._on_reenter_sends_mode)))
        self._knob_modes.add_mode('device',
          (self._device_parameters), behaviour=(self._get_device_mode_behaviour()))
        self._knob_modes.add_mode('takeover', None)
        self._knob_modes.selected_mode = 'device'
        self._Oxygen_Pro__on_knob_mode_changed.subject = self._knob_modes
        self._knob_modes.set_enabled(True)

    def _get_device_mode_behaviour(self):
        return ImmediateBehaviour()

    def _on_reenter_sends_mode(self):
        new_send_index = 1 if self._mixer.send_index == 0 else 0
        if new_send_index in range(self._mixer.num_sends):
            self._mixer.send_index = new_send_index

    def _create_takeover_modes(self):
        self._takeover_modes = ModesComponent(name='Takeover_Modes',
          is_enabled=False,
          layer=Layer(daw_button='daw_mode_button', preset_button='preset_mode_button'))
        self._takeover_modes.add_mode('daw', self._select_knob_mode)
        self._takeover_modes.add_mode('preset', (
         self._select_knob_mode,
         AddLayerMode((self._background),
           layer=Layer(faders='faders', knobs='knobs'))))
        self._takeover_modes.selected_mode = 'daw'
        self._takeover_modes.set_enabled(True)

    def _select_knob_mode(self):
        if self._takeover_modes.selected_mode == 'daw':
            self._knob_modes.selected_mode = self._last_selected_knob_mode
        else:
            self._knob_modes.selected_mode = 'takeover'

    @listens('selected_mode')
    def __on_knob_mode_changed(self, mode):
        if mode != 'takeover':
            self._last_selected_knob_mode = mode

    @listens('is_view_visible', 'Session')
    def __on_main_view_changed(self):
        if self.application.view.is_view_visible('Session'):
            self._record_modes.selected_mode = 'session'
        else:
            self._record_modes.selected_mode = 'arrange'
class SLMkIII(IdentifiableControlSurface):
    _sysex_message_cache = MidiMessageCache()

    def __init__(self, *a, **k):
        super(SLMkIII, self).__init__(
            product_id_bytes=(sysex.NOVATION_MANUFACTURER_ID +
                              sysex.DEVICE_FAMILY_CODE +
                              sysex.DEVICE_FAMILY_MEMBER_CODE),
            *a,
            **k)
        self._main_modes = NullModes()
        self._element_injector = inject(
            element_container=const(None)).everywhere()
        self._message_injector = inject(message=const(None)).everywhere()
        with self.component_guard():
            with inject(skin=const(skin),
                        message_cache=const(
                            self._sysex_message_cache)).everywhere():
                self._elements = Elements()
        self._element_injector = inject(
            element_container=const(self._elements)).everywhere()
        with self.component_guard():
            self._create_message()
        self._message_injector = inject(
            message=const(self._message)).everywhere()
        self._switch_display_layout(sysex.KNOB_SCREEN_LAYOUT_BYTE)
        self._device_bank_registry = DeviceBankRegistry()
        with self.component_guard():
            self._create_session()
            self._create_mixer()
            self._create_transport()
            self._create_session_recording()
            self._create_auto_arm()
            self._create_track_navigation()
            self._create_drums()
            self._create_device()
            self._create_device_navigation()
            self._create_actions()
            self._create_clip_actions()
            self._create_background()
            self._create_modes()
        self._drum_group_finder = self.register_disconnectable(
            PercussionInstrumentFinder(
                device_parent=self.song.view.selected_track))
        self.__on_drum_group_found.subject = self._drum_group_finder
        self.__on_drum_group_found()
        self.__on_selected_track_changed.subject = self.song.view
        self.__on_selected_track_changed()
        self.__on_session_record_changed.subject = self.song
        self.__on_record_mode_changed.subject = self.song
        self.set_feedback_channels([DRUM_FEEDBACK_CHANNEL])
        self._set_feedback_velocity()

    def on_identified(self, midi_bytes):
        self._switch_display_layout(sysex.KNOB_SCREEN_LAYOUT_BYTE, force=True)
        self._main_modes.selected_mode = u'device_control'
        self._auto_arm.set_enabled(True)
        self._session_ring.set_enabled(True)
        self.set_feedback_channels([DRUM_FEEDBACK_CHANNEL])
        super(SLMkIII, self).on_identified(midi_bytes)

    def disconnect(self):
        self._auto_arm.set_enabled(False)
        super(SLMkIII, self).disconnect()

    def port_settings_changed(self):
        self._auto_arm.set_enabled(False)
        self._session_ring.set_enabled(False)
        super(SLMkIII, self).port_settings_changed()

    @contextmanager
    def _component_guard(self):
        with super(SLMkIII, self)._component_guard():
            with self._element_injector:
                with self._message_injector:
                    yield
        self._format_and_send_sysex()

    def _format_and_send_sysex(self):
        messages_to_send = sysex.make_sysex_from_segments(
            self._sysex_message_cache.messages)
        for msg in messages_to_send:
            self._send_midi(msg)

        self._sysex_message_cache.clear()

    def _install_mapping(self, midi_map_handle, control, parameter,
                         feedback_delay, feedback_map):
        success = False
        if control.message_type() == MIDI_CC_TYPE:
            feedback_rule = Live.MidiMap.CCFeedbackRule()
            feedback_rule.cc_no = control.message_identifier()
            feedback_rule.cc_value_map = feedback_map
            feedback_rule.channel = getattr(control, u'feedback_channel',
                                            control.message_channel())
            feedback_rule.delay_in_ms = feedback_delay
            success = Live.MidiMap.map_midi_cc_with_feedback_map(
                midi_map_handle, parameter, control.message_channel(),
                control.message_identifier(), control.message_map_mode(),
                feedback_rule, not control.needs_takeover(),
                control.mapping_sensitivity)
            if success:
                Live.MidiMap.send_feedback_for_parameter(
                    midi_map_handle, parameter)
        return success

    def _create_message(self):
        self._message = MessageComponent(
            name=u'Message',
            is_enabled=False,
            layer=Layer(display=u'message_display'))
        self._message.set_enabled(True)

    def _switch_display_layout(self, layout_byte, force=False):
        display_layout_switch = self._elements.display_layout_switch
        if force:
            display_layout_switch.clear_send_cache()
        display_layout_switch.send_value(layout_byte)
        self._clear_display_send_cache()

    def _clear_display_send_cache(self):
        for display in self._elements.text_display_lines:
            display.clear_send_cache()

    def _create_session(self):
        self._session_ring = SessionRingComponent(
            is_enabled=False,
            num_tracks=SESSION_WIDTH,
            num_scenes=SESSION_HEIGHT,
            tracks_to_use=lambda: tuple(self.song.visible_tracks) + tuple(
                self.song.return_tracks) + (self.song.master_track, ),
            name=u'Session_Ring')
        self._session = SessionComponent(
            is_enabled=False,
            session_ring=self._session_ring,
            name=u'Session',
            layer=Layer(
                clip_launch_buttons=u'pads',
                scene_launch_buttons=u'scene_launch_buttons',
                stop_track_clip_buttons=u'shifted_pad_row_1',
                stop_all_clips_button=u'shifted_scene_launch_button_1'))
        self._session.set_rgb_mode(CLIP_COLOR_TABLE, RGB_COLOR_TABLE)
        self._session.set_enabled(True)
        self._session_navigation = SessionNavigationComponent(
            session_ring=self._session_ring, name=u'Session_Navigation')

    def _create_mixer(self):
        self._mixer = MixerComponent(
            name=u'Mixer',
            is_enabled=False,
            auto_name=True,
            tracks_provider=self._session_ring,
            track_assigner=RightAlignTracksTrackAssigner(
                song=self.song, include_master_track=True),
            invert_mute_feedback=True,
            layer=Layer(volume_controls=u'sliders',
                        volume_leds=u'slider_leds'))
        self._mixer.set_enabled(True)
        self._mixer_button_modes = DisplayingNavigatableModesComponent(
            name=u'Mixer_Button_Modes')
        self._mixer_button_modes.add_mode(
            u'mute_solo',
            AddLayerMode(
                self._mixer,
                Layer(mute_buttons=u'mixer_soft_button_row_0',
                      solo_buttons=u'mixer_soft_button_row_1')))
        self._mixer_button_modes.add_mode(
            u'monitor_arm',
            AddLayerMode(
                self._mixer,
                Layer(monitoring_state_buttons=u'mixer_soft_button_row_0',
                      arm_buttons=u'mixer_soft_button_row_1')))
        self._mixer_button_modes.layer = Layer(
            prev_mode_button=u'mixer_up_button',
            next_mode_button=u'mixer_down_button',
            display_1=u'mixer_display_1',
            display_2=u'mixer_display_2',
            color_field_1=u'mixer_color_field_1',
            color_field_2=u'mixer_color_field_2')
        self._mixer_button_modes.selected_mode = u'mute_solo'

    def _create_transport(self):
        self._transport = TransportComponent(
            name=u'Transport',
            is_enabled=False,
            layer=Layer(play_button=u'play_button',
                        stop_button=u'stop_button',
                        seek_backward_button=u'rw_button',
                        seek_forward_button=u'ff_button',
                        loop_button=u'loop_button',
                        record_button=u'record_button',
                        continue_playing_button=u'play_button_with_shift'))
        self._transport.set_enabled(True)

    def _create_session_recording(self):
        self._session_recording = SessionRecordingComponent(
            name=u'Session_Recording',
            is_enabled=False,
            layer=Layer(record_button=u'record_button_with_shift'))
        self._session_recording.set_enabled(True)

    def _create_auto_arm(self):
        self._auto_arm = AutoArmComponent(is_enabled=False, name=u'Auto_Arm')

    def _create_track_navigation(self):
        self._view_control = NotifyingViewControlComponent(
            name=u'view_control',
            is_enabled=False,
            track_provider=self._session_ring,
            layer=Layer(
                prev_track_button=u'track_left_button',
                next_track_button=u'track_right_button',
                prev_track_page_button=u'track_left_button_with_shift',
                next_track_page_button=u'track_right_button_with_shift',
                prev_scene_button=u'up_button_with_shift',
                next_scene_button=u'down_button_with_shift'))
        self._view_control.set_enabled(True)
        self._session_ring_selection_linking = self.register_disconnectable(
            SessionRingSelectionLinking(
                session_ring=self._session_ring,
                selection_changed_notifier=self._view_control))

    def _create_drums(self):
        self._drum_group = DrumGroupComponent(
            name=u'Drum_Group', translation_channel=DRUM_FEEDBACK_CHANNEL)

    def _create_device(self):
        self._banking_info = BankingInfo(BANK_DEFINITIONS)
        self._device = DeviceComponent(
            device_decorator_factory=DeviceDecoratorFactory(),
            device_bank_registry=self._device_bank_registry,
            banking_info=self._banking_info,
            name=u'Device')
        self._device_parameters = DeviceParameterComponent(
            parameter_provider=self._device, name=u'Device_Parameters')

    def _create_device_navigation(self):
        self._device_navigation = DisplayingDeviceNavigationComponent(
            banking_info=self._banking_info,
            device_bank_registry=self._device_bank_registry,
            device_component=self._device,
            num_visible_items=NUM_VISIBLE_ITEMS,
            name=u'Device_Navigation')

    def _create_actions(self):
        self._actions = ActionsComponent(
            name=u'Actions',
            is_enabled=False,
            layer=Layer(
                actions_color_fields=u'color_field_line_2_with_shift',
                undo_button=u'select_buttons_with_shift_raw[0]',
                redo_button=u'select_buttons_with_shift_raw[1]',
                metronome_button=u'select_buttons_with_shift_raw[2]',
                capture_midi_button=u'select_buttons_with_shift_raw[7]'))
        self._actions.set_enabled(True)

    def _create_clip_actions(self):
        self._clip_actions = ClipActionsComponent(
            name=u'Clip_Actions',
            is_enabled=False,
            layer=Layer(delete_button=u'clear_button',
                        duplicate_button=u'duplicate_button',
                        double_loop_button=u'duplicate_button_with_shift'))
        self._clip_actions.set_enabled(True)

    def _create_background(self):
        self._background = BackgroundComponent(
            name=u'Background',
            is_enabled=False,
            add_nop_listeners=True,
            layer=Layer(
                select_button_7_with_shift=u'select_buttons_with_shift_raw[3]',
                select_button_4_with_shift=u'select_buttons_with_shift_raw[4]',
                select_button_5_with_shift=u'select_buttons_with_shift_raw[5]',
                select_button_6_with_shift=u'select_buttons_with_shift_raw[6]')
        )
        self._background.set_enabled(True)

    def _create_modes(self):
        self._encoder_modes = DisplayingSkinableModesComponent(
            name=u'Encoder_Modes')
        self._encoder_modes.add_mode(u'devices', [
            partial(self._switch_display_layout, sysex.BOX_SCREEN_LAYOUT_BYTE),
            AddLayerMode(
                self._encoder_modes,
                Layer(mode_display=self._elements.text_display_line_5,
                      mode_color_fields=self._elements.color_field_line_2,
                      mode_selection_fields=self._elements.
                      selection_field_line_2)),
            LayerMode(
                self._device_navigation,
                Layer(select_buttons=u'pads_flattened',
                      device_color_fields=u'color_field_lines_0_1_flattened',
                      device_name_display_1=u'text_display_line_0',
                      device_name_display_2=u'text_display_line_2',
                      device_bank_name_display_1=u'text_display_line_1',
                      device_bank_name_display_2=u'text_display_line_3',
                      device_selection_fields=
                      u'selection_field_lines_0_1_flattened',
                      selected_device_name_display=u'center_display_1')),
            SetAttributeMode(self._device_navigation, u'scroll_left_layer',
                             Layer(button=u'up_button')),
            SetAttributeMode(self._device_navigation, u'scroll_right_layer',
                             Layer(button=u'down_button')),
            LayerMode(
                self._device,
                Layer(prev_bank_button=u'display_up_button',
                      next_bank_button=u'display_down_button')),
            AddLayerMode(
                self._mixer,
                Layer(selected_track_color_field=u'center_color_field',
                      selected_track_name_display=u'center_display_1')),
            AddLayerMode(
                self._background,
                Layer(center_display_2=u'center_display_2',
                      scene_launch_buttons=u'scene_launch_buttons',
                      encoders=u'encoders')),
            AddLayerMode(
                self._actions,
                Layer(actions_display=u'text_display_line_5_with_shift',
                      actions_selection_fields=
                      u'selection_field_line_2_with_shift'))
        ])
        self._encoder_modes.add_mode(u'pan', [
            partial(self._switch_display_layout,
                    sysex.KNOB_SCREEN_LAYOUT_BYTE),
            AddLayerMode(
                self._encoder_modes,
                Layer(mode_display=self._elements.text_display_line_3,
                      mode_color_fields=self._elements.color_field_line_2,
                      mode_selection_fields=self._elements.
                      selection_field_line_1,
                      selected_mode_color_field=u'center_color_field')),
            AddLayerMode(
                self._mixer,
                Layer(pan_controls=u'encoders',
                      track_names_display=u'text_display_line_0',
                      pan_value_display=u'text_display_line_1',
                      pan_encoder_color_fields=u'encoder_color_fields',
                      track_color_fields=u'color_field_line_0',
                      mixer_display=u'center_display_1',
                      pan_display=u'center_display_2')),
            AddLayerMode(
                self._background,
                Layer(display_up_button=u'display_up_button',
                      display_down_button=u'display_down_button')),
            AddLayerMode(
                self._actions,
                Layer(actions_display=u'text_display_line_3_with_shift',
                      actions_selection_fields=
                      u'selection_field_line_1_with_shift'))
        ])
        self._encoder_modes.add_mode(u'sends', [
            partial(self._switch_display_layout,
                    sysex.KNOB_SCREEN_LAYOUT_BYTE),
            AddLayerMode(
                self._encoder_modes,
                Layer(mode_display=self._elements.text_display_line_3,
                      mode_color_fields=self._elements.color_field_line_2,
                      mode_selection_fields=self._elements.
                      selection_field_line_1,
                      selected_mode_color_field=u'center_color_field')),
            AddLayerMode(
                self._mixer,
                Layer(send_controls=u'encoders',
                      send_up_button=u'display_up_button',
                      send_down_button=u'display_down_button',
                      track_names_display=u'text_display_line_0',
                      track_color_fields=u'color_field_line_0',
                      mixer_display=u'center_display_1',
                      send_index_display=u'center_display_2',
                      send_value_display=u'text_display_line_1',
                      send_encoder_color_fields=u'encoder_color_fields')),
            AddLayerMode(
                self._actions,
                Layer(actions_display=u'text_display_line_3_with_shift',
                      actions_selection_fields=
                      u'selection_field_line_1_with_shift'))
        ])
        self._pad_modes = ModesComponent(name=u'Pad_Modes')
        self._pad_modes.add_mode(
            u'drum',
            LayerMode(
                self._drum_group,
                Layer(matrix=u'pads_quadratic',
                      scroll_up_button=u'up_button',
                      scroll_down_button=u'down_button')))
        self._pad_modes.add_mode(
            u'disabled',
            AddLayerMode(
                self._background,
                Layer(matrix=u'pads_quadratic',
                      scroll_up_button=u'up_button',
                      scroll_down_button=u'down_button')))
        self._main_modes = ModesComponent(name=u'Encoder_Modes')
        set_main_mode = partial(setattr, self._main_modes, u'selected_mode')
        self._main_modes.add_mode(u'device_control', [
            partial(self._switch_display_layout,
                    sysex.KNOB_SCREEN_LAYOUT_BYTE),
            AddLayerMode(
                self._mixer,
                Layer(track_select_buttons=u'select_buttons',
                      track_names_display=u'text_display_line_3',
                      track_color_fields=u'color_field_line_2',
                      track_selection_fields=u'selection_field_line_1',
                      selected_track_color_field=u'center_color_field')),
            LayerMode(
                self._device_parameters,
                Layer(parameter_controls=u'encoders',
                      name_display_line=u'text_display_line_0',
                      value_display_line=u'text_display_line_1',
                      parameter_color_fields=u'color_field_line_0',
                      encoder_color_fields=u'encoder_color_fields')),
            LayerMode(
                self._session_navigation,
                Layer(up_button=u'up_button', down_button=u'down_button')),
            LayerMode(
                self._device,
                Layer(prev_bank_button=u'display_up_button',
                      next_bank_button=u'display_down_button')),
            LayerMode(
                self._device_navigation,
                Layer(selected_device_name_display=u'center_display_1',
                      selected_device_bank_name_display=u'center_display_2')),
            AddLayerMode(
                self._actions,
                Layer(actions_display=u'text_display_line_3_with_shift',
                      actions_selection_fields=
                      u'selection_field_line_1_with_shift'))
        ])
        self._main_modes.add_mode(
            u'options', [
                self._encoder_modes,
                LayerMode(
                    self._encoder_modes,
                    Layer(devices_button=u'select_buttons_raw[0]',
                          pan_button=u'select_buttons_raw[1]',
                          sends_button=u'select_buttons_raw[2]')),
                SetAttributeMode(self._encoder_modes, u'selected_mode',
                                 u'devices'),
                AddLayerMode(
                    self._background,
                    Layer(select_button_3=u'select_buttons_raw[3]',
                          select_button_4=u'select_buttons_raw[4]',
                          select_button_5=u'select_buttons_raw[5]',
                          select_button_6=u'select_buttons_raw[6]',
                          select_button_7=u'select_buttons_raw[7]'))
            ],
            behaviour=ReenterBehaviour(
                on_reenter=partial(set_main_mode, u'device_control')))
        self._main_modes.add_mode(u'grid', [
            partial(self._switch_display_layout,
                    sysex.KNOB_SCREEN_LAYOUT_BYTE), self._pad_modes,
            AddLayerMode(
                self._mixer,
                Layer(track_select_buttons=u'select_buttons',
                      track_names_display=u'text_display_line_3',
                      track_color_fields=u'color_field_line_2',
                      track_selection_fields=u'selection_field_line_1',
                      selected_track_color_field=u'center_color_field')),
            self._select_grid_mode,
            LayerMode(
                self._device_parameters,
                Layer(parameter_controls=u'encoders',
                      name_display_line=u'text_display_line_0',
                      value_display_line=u'text_display_line_1',
                      parameter_color_fields=u'color_field_line_0',
                      encoder_color_fields=u'encoder_color_fields')),
            LayerMode(
                self._device,
                Layer(prev_bank_button=u'display_up_button',
                      next_bank_button=u'display_down_button')),
            LayerMode(
                self._device_navigation,
                Layer(selected_device_name_display=u'center_display_1',
                      selected_device_bank_name_display=u'center_display_2')),
            AddLayerMode(self._background,
                         Layer(scene_launch_buttons=u'scene_launch_buttons')),
            AddLayerMode(
                self._actions,
                Layer(actions_display=u'text_display_line_3_with_shift',
                      actions_selection_fields=
                      u'selection_field_line_1_with_shift'))
        ],
                                  behaviour=ReenterBehaviour(
                                      on_reenter=partial(
                                          set_main_mode, u'device_control')))
        self._main_modes.layer = Layer(options_button=u'options_button',
                                       grid_button=u'grid_button')
        self._main_modes.selected_mode = u'device_control'

    @listens(u'instrument')
    def __on_drum_group_found(self):
        self._drum_group.set_drum_group_device(
            self._drum_group_finder.drum_group)
        self._select_grid_mode()

    @listens(u'selected_track')
    def __on_selected_track_changed(self):
        track = self.song.view.selected_track
        self.__on_selected_track_implicit_arm_changed.subject = track
        self._drum_group_finder.device_parent = track
        self._select_grid_mode()

    @listens(u'session_record')
    def __on_session_record_changed(self):
        self._set_feedback_velocity()

    @listens(u'implicit_arm')
    def __on_selected_track_implicit_arm_changed(self):
        self._set_feedback_velocity()

    @listens(u'record_mode')
    def __on_record_mode_changed(self):
        self._set_feedback_velocity()

    def _select_grid_mode(self):
        if self._main_modes.selected_mode == u'grid':
            drum_device = self._drum_group_finder.drum_group
            self._pad_modes.selected_mode = u'drum' if drum_device else u'disabled'
            if drum_device:
                self.set_controlled_track(self.song.view.selected_track)
                self._set_feedback_velocity()
            else:
                self.release_controlled_track()

    def _set_feedback_velocity(self):
        if is_song_recording(
                self.song) and self.song.view.selected_track.implicit_arm:
            feedback_velocity = Rgb.RED.midi_value
        else:
            feedback_velocity = Rgb.GREEN.midi_value
        self._c_instance.set_feedback_velocity(int(feedback_velocity))
 def _create_background(self):
     self._background = BackgroundComponent(name='Background',
       is_enabled=False,
       add_nop_listeners=True,
       layer=Layer(shift_button='shift_button'))
     self._background.set_enabled(True)
class PushBase(ControlSurface):
    preferences_key = 'Push'
    session_component_type = SpecialSessionComponent
    drum_group_note_editor_skin = 'NoteEditor'
    note_editor_velocity_range_thresholds = DEFAULT_VELOCITY_RANGE_THRESHOLDS
    device_component_class = None
    bank_definitions = None
    note_editor_class = None

    def __init__(self, *a, **k):
        super(PushBase, self).__init__(*a, **k)
        self.register_slot(self.song.view, self._on_selected_track_changed, 'selected_track')
        self._device_decorator_factory = self._create_device_decorator_factory()
        self.register_disconnectable(self._device_decorator_factory)
        self._double_press_context = DoublePressContext()
        injecting = self._create_injector()
        self._push_injector = injecting.everywhere()
        self._element_injector = inject(element_container=const(None)).everywhere()
        with self.component_guard():
            self._suppress_sysex = False
            self._skin = self._create_skin()
            self._clip_creator = ClipCreator()
            self._note_editor_settings = []
            self._notification = None
            self._user = None
            with inject(skin=const(self._skin)).everywhere():
                self._create_controls()
        self._element_injector = inject(element_container=const(self.elements)).everywhere()

    def initialize(self):
        self._setup_accidental_touch_prevention()
        self._create_components()
        self._init_main_modes()
        self._on_selected_track_changed()
        self.__on_session_record_changed.subject = self.song
        self.__on_session_record_changed()
        self.__on_selected_track_is_frozen_changed.subject = self.song.view
        self.set_feedback_channels(FEEDBACK_CHANNELS)

    def disconnect(self):
        if self._user is not None:
            with self.component_guard():
                self._user.mode = sysex.USER_MODE
        super(PushBase, self).disconnect()

    @contextmanager
    def _component_guard(self):
        with super(PushBase, self)._component_guard():
            with self._push_injector:
                with self._element_injector:
                    song_view = self.song.view
                    old_selected_track = song_view.selected_track
                    yield
                    if song_view.selected_track != old_selected_track:
                        self._track_selection_changed_by_action()

    def _create_device_decorator_factory(self):
        raise NotImplementedError

    def _create_components(self):
        self._init_settings()
        self._init_notification()
        self._init_message_box()
        self._init_background()
        self._init_user()
        self._init_touch_strip_controller()
        self._init_accent()
        self._init_track_frozen()
        self._init_undo_redo_actions()
        self._init_duplicate_actions()
        self._init_delete_actions()
        self._init_quantize_actions()
        self._init_session_ring()
        self._init_fixed_length()
        self._init_transport_and_recording()
        self._init_stop_clips_action()
        self._init_value_components()
        self._init_track_list()
        self._init_mixer()
        self._init_track_mixer()
        self._init_session()
        self._init_grid_resolution()
        self._init_drum_component()
        self._init_slicing_component()
        self._init_automation_component()
        self._init_note_settings_component()
        self._init_note_editor_settings_component()
        self._init_step_sequencer()
        self._init_instrument()
        self._init_scales()
        self._init_note_repeat()
        self._init_matrix_modes()
        self._init_device()
        self._init_m4l_interface()

    def _create_injector(self):
        return inject(double_press_context=const(self._double_press_context), expect_dialog=const(self.expect_dialog), show_notification=const(self.show_notification), selection=lambda : PushSelection(application=self.application(), device_component=self._device_component, navigation_component=self._device_navigation))

    def _create_skin(self):
        return make_default_skin()

    def _needs_to_deactivate_session_recording(self):
        return self._matrix_modes.selected_mode == 'note' and self.song.exclusive_arm

    def _track_selection_changed_by_action(self):
        if self._needs_to_deactivate_session_recording():
            self._session_recording.deactivate_recording()
        if self._auto_arm.needs_restore_auto_arm:
            self._auto_arm.restore_auto_arm()

    def port_settings_changed(self):
        self._switch_to_live_mode()

    def _switch_to_live_mode(self):
        self._user.mode = sysex.LIVE_MODE
        self._user.force_send_mode()

    def _init_settings(self):
        self._settings = self._create_settings()

    def _create_settings(self):
        raise RuntimeError

    def update(self):
        self.__on_session_record_changed()
        self.reset_controlled_track()
        self.set_feedback_channels(FEEDBACK_CHANNELS)
        super(PushBase, self).update()

    def _create_controls(self):
        raise NotImplementedError

    def _with_shift(self, button):
        return ComboElement(button, modifier='shift_button')

    def _with_firmware_version(self, major_version, minor_version, control_element):
        raise NotImplementedError

    def _init_background(self):
        self._background = BackgroundComponent(is_root=True)
        self._background.layer = self._create_background_layer()
        self._matrix_background = BackgroundComponent()
        self._matrix_background.set_enabled(False)
        self._matrix_background.layer = Layer(matrix='matrix')
        self._mod_background = ModifierBackgroundComponent(is_root=True)
        self._mod_background.layer = Layer(shift_button='shift_button', select_button='select_button', delete_button='delete_button', duplicate_button='duplicate_button', quantize_button='quantize_button')

    def _create_background_layer(self):
        return Layer(top_buttons='select_buttons', bottom_buttons='track_state_buttons', scales_button='scale_presets_button', octave_up='octave_up_button', octave_down='octave_down_button', side_buttons='side_buttons', repeat_button='repeat_button', accent_button='accent_button', double_button='double_button', param_controls='global_param_controls', param_touch='global_param_touch_buttons', touch_strip='touch_strip_control', nav_up_button='nav_up_button', nav_down_button='nav_down_button', nav_left_button='nav_left_button', nav_right_button='nav_right_button', aftertouch='aftertouch_control', _notification=self._notification.use_single_line(2), priority=consts.BACKGROUND_PRIORITY)

    def _init_track_list(self):
        pass

    def _can_auto_arm_track(self, track):
        routing = track.current_input_routing
        return routing == 'Ext: All Ins' or routing == 'All Ins' or routing.startswith(self.input_target_name_for_auto_arm)

    def _init_touch_strip_controller(self):
        strip_controller = TouchStripControllerComponent()
        strip_controller.set_enabled(False)
        strip_controller.layer = Layer(touch_strip='touch_strip_control')
        strip_controller.layer.priority = consts.DIALOG_PRIORITY
        self._strip_connection = TouchStripEncoderConnection(strip_controller, self.elements.touch_strip_tap, is_root=True)
        self.elements.tempo_control.set_observer(self._strip_connection)
        self.elements.swing_control.set_observer(self._strip_connection)
        self.elements.master_volume_control.set_observer(self._strip_connection)
        for encoder in self.elements.global_param_controls.nested_control_elements():
            encoder.set_observer(self._strip_connection)

        self._pitch_mod_touch_strip = TouchStripPitchModComponent()
        self._pitch_mod_touch_strip_layer = Layer(touch_strip='touch_strip_control', touch_strip_indication=self._with_firmware_version(1, 16, ComboElement('touch_strip_control', modifier='select_button')), touch_strip_toggle=self._with_firmware_version(1, 16, ComboElement('touch_strip_tap', modifier='select_button')))

    def _create_session_mode(self):
        raise NotImplementedError

    def _create_slicing_modes(self):
        slicing_modes = ModesComponent(name='Slicing_Modes', is_enabled=False)
        slicing_modes.add_mode('64pads', [AddLayerMode(self._slicing_component, Layer(matrix='matrix')), LayerMode(self._pitch_mod_touch_strip, self._pitch_mod_touch_strip_layer)])
        slicing_modes.add_mode('sequencer', [self._slice_step_sequencer, self._note_editor_settings_component, AddLayerMode(self._slicing_component, Layer(matrix=self.elements.matrix.submatrix[:4, 4:8], page_strip='touch_strip_control', scroll_strip=self._with_shift('touch_strip_control')))])
        slicing_modes.selected_mode = '64pads'
        return slicing_modes

    def _init_matrix_modes(self):
        self._auto_arm = AutoArmComponent(name='Auto_Arm')
        self._auto_arm.can_auto_arm_track = self._can_auto_arm_track
        self._auto_arm.layer = Layer(_notification=self._notification.use_single_line(2))
        self._select_playing_clip = SelectPlayingClipComponent(name='Select_Playing_Clip', playing_clip_above_layer=Layer(action_button='nav_up_button'), playing_clip_below_layer=Layer(action_button='nav_down_button'))
        self._select_playing_clip.layer = Layer(_notification=self._notification.use_single_line(2))
        self._percussion_instrument_finder = PercussionInstrumentFinderComponent(device_parent=self.song.view.selected_track)
        self.__on_percussion_instrument_changed.subject = self._percussion_instrument_finder
        self._drum_modes = ModesComponent(name='Drum_Modes', is_enabled=False)
        self._drum_modes.add_mode('sequencer', [self._drum_step_sequencer, self._note_editor_settings_component, AddLayerMode(self._drum_component, Layer(matrix=self.elements.matrix.submatrix[:4, 4:8]))])
        self._drum_modes.add_mode('64pads', [AddLayerMode(self._drum_component, Layer(matrix='matrix'))])
        self._drum_modes.selected_mode = 'sequencer'
        self._slicing_modes = self._create_slicing_modes()
        self._note_modes = ModesComponent(name='Note_Modes')
        self._note_modes.add_mode('drums', [self._drum_component,
         self._note_repeat_enabler,
         self._accent_component,
         self._drum_modes])
        self._note_modes.add_mode('slicing', [self._slicing_component,
         self._note_repeat_enabler,
         self._accent_component,
         self._slicing_modes])
        self._note_modes.add_mode('looper', self._audio_loop if consts.PROTO_AUDIO_NOTE_MODE else self._matrix_background)
        self._note_modes.add_mode('instrument', [self._note_repeat_enabler,
         self._accent_component,
         self._instrument,
         self._scales_enabler])
        self._note_modes.add_mode('disabled', self._matrix_background)
        self._note_modes.selected_mode = 'disabled'
        self._note_modes.set_enabled(False)
        self._matrix_modes = ModesComponent(name='Matrix_Modes', is_root=True)
        self._matrix_modes.add_mode('session', self._create_session_mode())
        self._matrix_modes.add_mode('note', self._create_note_mode(), behaviour=self._create_note_mode_behaviour())
        self._matrix_modes.selected_mode = 'note'
        self._matrix_modes.layer = Layer(session_button='session_mode_button', note_button='note_mode_button')
        self.__on_matrix_mode_changed.subject = self._matrix_modes
        self._matrix_modes.selected_mode = 'note'

    def _switch_note_mode_layout(self):
        cyclable_mode = {'instrument': self._instrument,
         'drums': self._drum_modes,
         'slicing': self._slicing_modes}.get(self._note_modes.selected_mode, None)
        getattr(cyclable_mode, 'cycle_mode', nop)()

    def _create_note_mode(self):
        return [self._percussion_instrument_finder,
         self._view_control,
         self._note_modes,
         self._delete_clip,
         self._select_playing_clip]

    def _create_note_mode_behaviour(self):
        raise NotImplementedError

    def _init_accent(self):
        self._accent_component = AccentComponent()
        self._accent_component.set_full_velocity(self._c_instance.full_velocity)
        self._accent_component.set_enabled(False)
        self._accent_component.layer = Layer(cycle_mode_button='accent_button')
        self.__on_accent_mode_changed.subject = self._accent_component

    def _create_user_component(self):
        raise NotImplementedError

    def _init_user(self):
        self._user = self._create_user_component()
        self.__on_hardware_mode_changed.subject = self._user
        self.__on_before_hardware_mode_sent.subject = self._user
        self.__on_after_hardware_mode_sent.subject = self._user

    def _create_session_layer(self):
        return Layer(clip_launch_buttons='matrix', scene_launch_buttons='side_buttons', duplicate_button='duplicate_button', touch_strip='touch_strip_control')

    def _set_session_skin(self, session):
        pass

    def _create_session(self):
        session = self.session_component_type(session_ring=self._session_ring, enable_skinning=True, is_enabled=False, auto_name=True, layer=self._create_session_layer())
        self._set_session_skin(session)
        for scene_index in xrange(8):
            scene = session.scene(scene_index)
            scene.layer = Layer(select_button='select_button', delete_button='delete_button')
            scene._do_select_scene = self.on_select_scene
            for track_index in xrange(8):
                clip_slot = scene.clip_slot(track_index)
                clip_slot._do_select_clip = self.on_select_clip_slot
                clip_slot.layer = Layer(delete_button='delete_button', select_button='select_button', duplicate_button='duplicate_button')

        session.duplicate_layer = Layer(scene_buttons='side_buttons')
        return session

    def on_select_clip_slot(self, clip_slot):
        """
        Called when a clip slot is selected from Push. Override to create specific
        behaviour.
        """
        pass

    def on_select_scene(self, scene):
        """
        Called when a scene is selected from Push. Override to create specific behaviour.
        """
        pass

    def on_select_track(self, track):
        """
        Called when a track is selected from Push's channel strip components. Override
        to create specific behaviour.
        """
        pass

    def _create_session_overview(self):
        return SessionOverviewComponent(session_ring=self._session_ring, name='Session_Overview', enable_skinning=True, is_enabled=False, layer=self._create_session_overview_layer())

    def _create_session_overview_layer(self):
        raise NotImplementedError

    def _init_session_ring(self):
        self._session_ring = SessionRingComponent(num_tracks=NUM_TRACKS, num_scenes=NUM_SCENES, tracks_to_use=partial(tracks_to_use_from_song, self.song), is_enabled=True, is_root=True)

    def _init_session(self):
        self._session_mode = LazyComponentMode(self._create_session)
        self._session_overview_mode = LazyComponentMode(self._create_session_overview)
        self._session_navigation = SessionNavigationComponent(session_ring=self._session_ring, is_enabled=False, layer=self._create_session_navigation_layer())

    def _create_session_navigation_layer(self):
        return Layer(left_button='nav_left_button', right_button='nav_right_button', up_button='nav_up_button', down_button='nav_down_button', page_left_button=self._with_shift('nav_left_button'), page_right_button=self._with_shift('nav_right_button'), page_up_button=MultiElement('octave_up_button', self._with_shift('nav_up_button')), page_down_button=MultiElement('octave_down_button', self._with_shift('nav_down_button')))

    def _create_track_modes_layer(self):
        return Layer(stop_button='global_track_stop_button', mute_button='global_mute_button', solo_button='global_solo_button')

    def _when_track_is_not_frozen(self, *modes):
        return TrackFrozenModesComponent(default_mode=[modes], frozen_mode=self._track_frozen_info, is_enabled=False)

    def _create_device_mode(self):
        raise NotImplementedError

    def _create_main_mixer_modes(self):
        self._main_modes.add_mode('volumes', [self._track_modes, (self._mixer, self._mixer_volume_layer), self._track_note_editor_mode])
        self._main_modes.add_mode('pan_sends', [self._track_modes, (self._mixer, self._mixer_pan_send_layer), self._track_note_editor_mode])
        self._main_modes.add_mode('track', [self._track_modes,
         self._track_mixer,
         (self._mixer, self._mixer_track_layer),
         self._track_note_editor_mode])

    def _create_clip_mode(self):
        return [self._when_track_is_not_frozen(partial(self._view_control.show_view, 'Detail/Clip'), LazyComponentMode(self._create_clip_control))]

    def _init_main_modes(self):

        def configure_note_editor_settings(parameter_provider, mode):
            for note_editor_setting in self._note_editor_settings:
                note_editor_setting.component.parameter_provider = parameter_provider
                note_editor_setting.component.automation_layer = getattr(note_editor_setting, mode + '_automation_layer')

        self._track_note_editor_mode = partial(configure_note_editor_settings, self._track_parameter_provider, 'track')
        self._device_note_editor_mode = partial(configure_note_editor_settings, self._device_component, 'device')
        self._enable_stop_mute_solo_as_modifiers = AddLayerMode(self._mod_background, Layer(stop='global_track_stop_button', mute='global_mute_button', solo='global_solo_button'))
        self._main_modes = ModesComponent(is_root=True)
        self._create_main_mixer_modes()
        self._main_modes.add_mode('clip', self._create_clip_mode())
        self._main_modes.add_mode('device', self._create_device_mode(), behaviour=ReenterBehaviour(self._device_navigation.back_to_top))
        self._init_browse_mode()
        self._main_modes.selected_mode = 'device'
        self._main_modes.layer = self._create_main_modes_layer()

    def _init_browse_mode(self):
        raise NotImplementedError

    def _create_main_modes_layer(self):
        return Layer(volumes_button='vol_mix_mode_button', pan_sends_button='pan_send_mix_mode_button', track_button='single_track_mix_mode_button', clip_button='clip_mode_button', device_button='device_mode_button', browse_button='browse_mode_button', add_effect_right_button='create_device_button', add_effect_left_button=self._with_shift('create_device_button'), add_instrument_track_button='create_track_button')

    def _init_track_frozen(self):
        self._track_frozen_info = InfoComponent(info_text=consts.MessageBoxText.TRACK_FROZEN_INFO, is_enabled=False, layer=self._create_track_frozen_layer())

    def _create_track_frozen_layer(self):
        return Layer()

    def _init_mixer(self):
        pass

    def _init_track_mixer(self):
        self._track_parameter_provider = self.register_disconnectable(SelectedTrackParameterProvider())
        self._track_mixer = DeviceParameterComponent(parameter_provider=self._track_parameter_provider, is_enabled=False, layer=self._create_track_mixer_layer())

    def _create_track_mixer_layer(self):
        return Layer(parameter_controls='fine_grain_param_controls')

    def _create_device_component(self):
        return self.device_component_class(device_decorator_factory=self._device_decorator_factory, device_bank_registry=self._device_bank_registry, banking_info=self._banking_info, name='DeviceComponent', is_enabled=True, is_root=True)

    def _create_device_parameter_component(self):
        return DeviceParameterComponent(parameter_provider=self._device_component, is_enabled=False, layer=self._create_device_parameter_layer())

    def _create_device_parameter_layer(self):
        return Layer(parameter_controls='fine_grain_param_controls')

    def _create_device_navigation(self):
        raise NotImplementedError

    def _init_device(self):
        self._device_bank_registry = DeviceBankRegistry()
        self._banking_info = BankingInfo(self.bank_definitions)
        self._device_component = self._create_device_component()
        self._device_parameter_component = self._create_device_parameter_component()
        self._device_navigation = self._create_device_navigation()

    def _create_view_control_component(self):
        return ViewControlComponent(name='View_Control')

    def _init_fixed_length(self):
        self._fixed_length_setting = FixedLengthSetting()
        self._fixed_length_setting.enabled = self.preferences.setdefault('fixed_length_enabled', False)
        self._fixed_length_setting.selected_index = self.preferences.setdefault('fixed_length_option', DEFAULT_LENGTH_OPTION_INDEX)
        self.__on_fixed_length_enabled_changed.subject = self._fixed_length_setting
        self.__on_fixed_length_selected_index_changed.subject = self._fixed_length_setting
        self._fixed_length_settings_component = FixedLengthSettingComponent(fixed_length_setting=self._fixed_length_setting, is_enabled=False)
        self._fixed_length = FixedLengthComponent(settings_component=self._fixed_length_settings_component, fixed_length_setting=self._fixed_length_setting)
        self._fixed_length.layer = Layer(fixed_length_toggle_button='fixed_length_button')

    def _create_session_recording(self):
        raise NotImplementedError

    def _init_transport_and_recording(self):
        self._view_control = self._create_view_control_component()
        self._view_control.set_enabled(False)
        self._view_control.layer = Layer(prev_track_button='nav_left_button', next_track_button='nav_right_button', prev_scene_button=OptionalElement('nav_up_button', self._settings['workflow'], False), next_scene_button=OptionalElement('nav_down_button', self._settings['workflow'], False), prev_scene_list_button=OptionalElement('nav_up_button', self._settings['workflow'], True), next_scene_list_button=OptionalElement('nav_down_button', self._settings['workflow'], True))
        self._session_recording = self._create_session_recording()
        new_button = MultiElement(self.elements.new_button, self.elements.foot_pedal_button.double_press)
        self._session_recording.layer = Layer(new_button=OptionalElement(new_button, self._settings['workflow'], False), scene_list_new_button=OptionalElement(new_button, self._settings['workflow'], True), record_button='record_button', arrangement_record_button=self._with_shift('record_button'), automation_button='automation_button', new_scene_button=self._with_shift('new_button'), re_enable_automation_button=self._with_shift('automation_button'), delete_automation_button=ComboElement('automation_button', 'delete_button'), foot_switch_button=self.elements.foot_pedal_button.single_press, _uses_foot_pedal='foot_pedal_button')
        self._transport = TransportComponent(name='Transport', is_root=True)
        self._transport.layer = Layer(play_button='play_button', stop_button=self._with_shift('play_button'), tap_tempo_button='tap_tempo_button', metronome_button='metronome_button')

    def _create_clip_control(self):
        return ClipControlComponent(loop_layer=self._create_clip_loop_layer(), audio_layer=self._create_clip_audio_layer(), clip_name_layer=self._create_clip_name_layer(), name='Clip_Control', is_enabled=False)

    def _create_clip_loop_layer(self):
        return Layer(encoders=self.elements.global_param_controls.submatrix[:4, :], shift_button='shift_button')

    def _create_clip_audio_layer(self):
        return Layer(warp_mode_encoder='parameter_controls_raw[4]', transpose_encoder='parameter_controls_raw[5]', detune_encoder='parameter_controls_raw[6]', gain_encoder='parameter_controls_raw[7]', shift_button='shift_button')

    def _create_clip_name_layer(self):
        return Layer()

    def _init_grid_resolution(self):
        self._grid_resolution = self.register_disconnectable(GridResolution())

    def _init_note_settings_component(self):
        raise NotImplementedError

    def _init_automation_component(self):
        self._automation_component = AutomationComponent()

    def _init_note_editor_settings_component(self):
        self._note_editor_settings_component = NoteEditorSettingsComponent(note_settings_component=self._note_settings_component, automation_component=self._automation_component, initial_encoder_layer=Layer(initial_encoders='global_param_controls', priority=consts.MOMENTARY_DIALOG_PRIORITY), encoder_layer=Layer(encoders='global_param_controls', priority=consts.MOMENTARY_DIALOG_PRIORITY))
        self._note_editor_settings_component.mode_selector_layer = self._create_note_editor_mode_selector_layer()
        self._note_editor_settings.append(NamedTuple(component=self._note_editor_settings_component, track_automation_layer=self._create_note_editor_track_automation_layer(), device_automation_layer=self._create_note_editor_track_automation_layer()))

    def _create_note_editor_mode_selector_layer(self):
        return Layer(select_buttons='select_buttons', state_buttons='track_state_buttons', priority=consts.MOMENTARY_DIALOG_PRIORITY)

    def _create_note_editor_track_automation_layer(self):
        return Layer(priority=consts.MOMENTARY_DIALOG_PRIORITY)

    def _create_note_editor_device_automation_layer(self):
        return Layer(priority=consts.MOMENTARY_DIALOG_PRIORITY)

    def _create_instrument_layer(self):
        return Layer(playhead='playhead_element', mute_button='global_mute_button', quantization_buttons='side_buttons', loop_selector_matrix=self.elements.double_press_matrix.submatrix[:, 0], short_loop_selector_matrix=self.elements.double_press_event_matrix.submatrix[:, 0], note_editor_matrices=ButtonMatrixElement([[ self.elements.matrix.submatrix[:, 7 - row] for row in xrange(7) ]]))

    def _init_instrument(self):
        self._note_layout = NoteLayout(song=self.song, preferences=self.preferences)
        instrument_basic_layer = Layer(octave_strip=self._with_shift('touch_strip_control'), octave_up_button='octave_up_button', octave_down_button='octave_down_button', scale_up_button=self._with_shift('octave_up_button'), scale_down_button=self._with_shift('octave_down_button'))
        self._instrument = MelodicComponent(skin=self._skin, is_enabled=False, clip_creator=self._clip_creator, name='Melodic_Component', grid_resolution=self._grid_resolution, note_layout=self._note_layout, note_editor_settings=self._note_editor_settings_component, note_editor_class=self.note_editor_class, velocity_range_thresholds=self.note_editor_velocity_range_thresholds, layer=self._create_instrument_layer(), instrument_play_layer=instrument_basic_layer + Layer(matrix='matrix', aftertouch_control='aftertouch_control', delete_button='delete_button'), instrument_sequence_layer=instrument_basic_layer + Layer(note_strip='touch_strip_control'), pitch_mod_touch_strip_mode=LayerMode(self._pitch_mod_touch_strip, self._pitch_mod_touch_strip_layer))
        self.__on_note_editor_layout_changed.subject = self._instrument

    def _create_scales_enabler(self):
        raise NotImplementedError

    def _init_scales(self):
        self._scales_enabler = self._create_scales_enabler()

    def _create_step_sequencer_layer(self):
        return Layer(playhead='playhead_element', button_matrix=self.elements.matrix.submatrix[:8, :4], loop_selector_matrix=self.elements.double_press_matrix.submatrix[4:8, 4:8], short_loop_selector_matrix=self.elements.double_press_event_matrix.submatrix[4:8, 4:8], quantization_buttons='side_buttons', solo_button='global_solo_button', select_button='select_button', delete_button='delete_button', shift_button='shift_button', mute_button='global_mute_button')

    def _init_step_sequencer(self):
        drum_note_editor = self.note_editor_class(clip_creator=self._clip_creator, grid_resolution=self._grid_resolution, skin_base_key=self.drum_group_note_editor_skin, velocity_range_thresholds=self.note_editor_velocity_range_thresholds)
        self._note_editor_settings_component.add_editor(drum_note_editor)
        self._drum_step_sequencer = StepSeqComponent(self._clip_creator, self._skin, name='Drum_Step_Sequencer', grid_resolution=self._grid_resolution, note_editor_component=drum_note_editor, instrument_component=self._drum_component)
        self._drum_step_sequencer.set_enabled(False)
        self._drum_step_sequencer.layer = self._create_step_sequencer_layer()
        self._audio_loop = LoopSelectorComponent(follow_detail_clip=True, measure_length=1.0, name='Loop_Selector')
        self._audio_loop.set_enabled(False)
        self._audio_loop.layer = Layer(loop_selector_matrix='matrix')
        slice_note_editor = self.note_editor_class(clip_creator=self._clip_creator, grid_resolution=self._grid_resolution, skin_base_key=self.drum_group_note_editor_skin, velocity_range_thresholds=self.note_editor_velocity_range_thresholds)
        self._note_editor_settings_component.add_editor(slice_note_editor)
        self._slice_step_sequencer = StepSeqComponent(self._clip_creator, self._skin, name='Slice_Step_Sequencer', grid_resolution=self._grid_resolution, note_editor_component=slice_note_editor, instrument_component=self._slicing_component, is_enabled=False)
        self._slice_step_sequencer.layer = Layer(playhead='playhead_element', button_matrix=self.elements.matrix.submatrix[:8, :4], loop_selector_matrix=self.elements.double_press_matrix.submatrix[4:8, 4:8], short_loop_selector_matrix=self.elements.double_press_event_matrix.submatrix[4:8, 4:8], quantization_buttons='side_buttons', select_button='select_button')

    def _drum_pad_notification_formatter(self):
        return lambda x: adjust_string(x, 8)

    def _create_drum_component(self):
        raise NotImplementedError

    def _init_drum_component(self):
        self._drum_component = self._create_drum_component()
        self._drum_component.layer = Layer(page_strip='touch_strip_control', scroll_strip=self._with_shift('touch_strip_control'), solo_button='global_solo_button', select_button='select_button', delete_button='delete_button', scroll_page_up_button='octave_up_button', scroll_page_down_button='octave_down_button', quantize_button='quantize_button', duplicate_button='duplicate_button', mute_button='global_mute_button', scroll_up_button=self._with_shift('octave_up_button'), scroll_down_button=self._with_shift('octave_down_button'))

    def _init_slicing_component(self):
        self._slicing_component = SlicedSimplerComponent(is_enabled=False)
        self._slicing_component.layer = Layer(scroll_page_up_button='octave_up_button', scroll_page_down_button='octave_down_button', scroll_up_button=self._with_shift('octave_up_button'), scroll_down_button=self._with_shift('octave_down_button'), delete_button='delete_button', select_button='select_button')

    def _init_note_repeat(self):
        self._note_repeat = NoteRepeatComponent(name='Note_Repeat')
        self._note_repeat.set_enabled(False)
        self._note_repeat.set_note_repeat(self._c_instance.note_repeat)
        self._note_repeat.layer = self._create_note_repeat_layer()
        self._note_repeat_enabler = EnablingModesComponent(name='Note_Repeat_Enabler', component=self._note_repeat, enabled_color='DefaultButton.Alert', disabled_color='DefaultButton.On')
        self._note_repeat_enabler.set_enabled(False)
        self._note_repeat_enabler.layer = Layer(cycle_mode_button='repeat_button')

    def _create_note_repeat_layer(self):
        return Layer(aftertouch_control='aftertouch_control', select_buttons='side_buttons', priority=consts.DIALOG_PRIORITY)

    def _init_notification(self):
        self._notification = self._create_notification_component()

    def _create_notification_component(self):
        raise NotImplementedError

    def _create_message_box_background_layer(self):
        return BackgroundLayer('select_buttons', 'track_state_buttons', 'scale_presets_button', 'octave_up_button', 'octave_down_button', 'side_buttons', 'repeat_button', 'accent_button', 'global_param_controls', 'global_param_touch_buttons', 'touch_strip_control', 'touch_strip_tap', 'matrix', 'nav_up_button', 'nav_down_button', 'nav_left_button', 'nav_right_button', 'shift_button', 'select_button', 'delete_button', 'duplicate_button', 'double_button', 'quantize_button', 'play_button', 'new_button', 'automation_button', 'tap_tempo_button', 'metronome_button', 'fixed_length_button', 'record_button', 'undo_button', 'tempo_control', 'swing_control', 'master_volume_control', 'global_param_controls', 'vol_mix_mode_button', 'pan_send_mix_mode_button', 'single_track_mix_mode_button', 'clip_mode_button', 'device_mode_button', 'browse_mode_button', 'user_button', 'master_select_button', 'create_device_button', 'create_track_button', 'global_track_stop_button', 'global_mute_button', 'global_solo_button', 'note_mode_button', 'session_mode_button', priority=consts.MESSAGE_BOX_PRIORITY)

    def _create_message_box_layer(self):
        raise RuntimeError

    def _init_message_box(self):
        self._dialog = DialogComponent(is_enabled=True, is_root=True)
        self._dialog.message_box_layer = (self._create_message_box_background_layer(), self._create_message_box_layer())

    def _for_non_frozen_tracks(self, component, **k):
        """ Wrap component into a mode that will only enable it when
        the track is not frozen """
        TrackFrozenModesComponent(default_mode=component, frozen_mode=self._track_frozen_info, **k)
        return component

    def _init_undo_redo_actions(self):
        self._undo_redo = UndoRedoComponent(name='Undo_Redo', is_root=True)
        self._undo_redo.layer = Layer(undo_button='undo_button', redo_button=self._with_shift('undo_button'))

    def _init_stop_clips_action(self):
        pass

    def _create_capture_and_insert_scene_component(self):
        return CaptureAndInsertSceneComponent(name='Capture_And_Insert_Scene', is_root=True)

    def _init_duplicate_actions(self):
        capture_element = ChoosingElement(self._settings['workflow'], 'duplicate_button', self._with_shift('duplicate_button'))
        self._capture_and_insert_scene = self._create_capture_and_insert_scene_component()
        self._capture_and_insert_scene.set_enabled(True)
        self._capture_and_insert_scene.layer = Layer(action_button=capture_element)
        duplicate_element = OptionalElement('duplicate_button', self._settings['workflow'], False)
        self._duplicate_detail_clip = DuplicateDetailClipComponent(name='Duplicate_Detail_Clip', is_root=True)
        self._duplicate_detail_clip.set_enabled(True)
        self._duplicate_detail_clip.layer = Layer(action_button=duplicate_element)
        self._duplicate_loop = self._for_non_frozen_tracks(DuplicateLoopComponent(name='Duplicate_Loop', layer=Layer(action_button='double_button'), is_enabled=False), is_root=True)

    def _init_delete_actions(self):
        self._delete_component = DeleteComponent(name='Deleter', is_root=True)
        self._delete_component.layer = Layer(delete_button='delete_button')
        self._delete_default_component = DeleteAndReturnToDefaultComponent(name='DeleteAndDefault', is_root=True)
        self._delete_default_component.layer = Layer(delete_button='delete_button')
        self._delete_clip = DeleteSelectedClipComponent(name='Selected_Clip_Deleter', is_root=True)
        self._delete_clip.layer = Layer(action_button='delete_button')
        self._delete_scene = DeleteSelectedSceneComponent(name='Selected_Scene_Deleter', is_root=True)
        self._delete_scene.layer = Layer(action_button=self._with_shift('delete_button'))

    def _init_quantize_actions(self):
        raise NotImplementedError

    def _init_value_components(self):
        self._swing_amount = ValueComponent('swing_amount', self.song, display_label='Swing Amount:', display_format='%d%%', model_transform=lambda x: clamp(x / 200.0, 0.0, 0.5), view_transform=lambda x: x * 200.0, encoder_factor=100.0, encoder_touch_delay=TEMPO_SWING_TOUCH_DELAY, is_root=True)
        self._swing_amount.layer = Layer(encoder='swing_control')
        self._tempo = ValueComponent('tempo', self.song, display_label='Tempo:', display_format='%0.2f BPM', encoder_factor=128.0, encoder_touch_delay=TEMPO_SWING_TOUCH_DELAY, is_root=True)
        self._tempo.layer = Layer(encoder='tempo_control', shift_button='shift_button')
        self._master_vol = ParameterValueComponent(self.song.master_track.mixer_device.volume, display_label='Master Volume:', display_seg_start=3, name='Master_Volume_Display', is_root=True)
        self._master_vol.layer = Layer(encoder='master_volume_control')
        self._master_cue_vol = ParameterValueComponent(self.song.master_track.mixer_device.cue_volume, display_label='Cue Volume:', display_seg_start=3, name='Cue_Volume_Display', is_root=True)
        self._master_cue_vol.layer = Layer(encoder=self._with_shift('master_volume_control'))

    def _init_m4l_interface(self):
        self._m4l_interface = M4LInterfaceComponent(controls=self.controls, component_guard=self.component_guard, priority=consts.M4L_PRIORITY, is_root=True)
        self.get_control_names = self._m4l_interface.get_control_names
        self.get_control = self._m4l_interface.get_control
        self.grab_control = self._m4l_interface.grab_control
        self.release_control = self._m4l_interface.release_control

    @listens('selected_mode')
    def __on_note_editor_layout_changed(self, mode):
        self.reset_controlled_track(mode)

    def reset_controlled_track(self, mode = None):
        if mode == None:
            mode = self._instrument.selected_mode
        if self._instrument.is_enabled() and mode == 'sequence':
            self.release_controlled_track()
        else:
            self.set_controlled_track(self.song.view.selected_track)

    @listens('selected_track.is_frozen')
    def __on_selected_track_is_frozen_changed(self):
        self._select_note_mode()

    def _on_selected_track_changed(self):
        self.reset_controlled_track()
        self._select_note_mode()
        self._note_repeat_enabler.selected_mode = 'disabled'

    def _send_midi(self, midi_event_bytes, optimized = True):
        if not self._suppress_sysex or not midi.is_sysex(midi_event_bytes):
            return super(PushBase, self)._send_midi(midi_event_bytes, optimized)

    def _update_full_velocity(self, accent_is_active):
        self._drum_step_sequencer.full_velocity = accent_is_active
        self._instrument.full_velocity = accent_is_active

    def _update_playhead_color(self, color):
        self._instrument.playhead_color = color
        self._drum_step_sequencer.playhead_color = color

    @listens('session_record')
    def __on_session_record_changed(self):
        status = self.song.session_record
        self._update_playhead_color('PlayheadRecord' if status else 'Playhead')
        feedback_color = int(to_midi_value(self._skin['Instrument.FeedbackRecord']) if status else to_midi_value(self._skin['Instrument.Feedback']))
        self._c_instance.set_feedback_velocity(feedback_color)

    @listens('selected_mode')
    def __on_accent_mode_changed(self, mode_name):
        accent_is_active = mode_name == 'enabled'
        self._update_full_velocity(accent_is_active)

    @listens('enabled')
    def __on_fixed_length_enabled_changed(self, enabled):
        self.preferences['fixed_length_enabled'] = enabled

    @listens('selected_index')
    def __on_fixed_length_selected_index_changed(self, index):
        self.preferences['fixed_length_option'] = index

    @listens('before_mode_sent')
    def __on_before_hardware_mode_sent(self, mode):
        self._suppress_sysex = False

    @listens('after_mode_sent')
    def __on_after_hardware_mode_sent(self, mode):
        if mode == sysex.USER_MODE:
            self._suppress_sysex = True

    @listens('mode')
    def __on_hardware_mode_changed(self, mode):
        if mode == sysex.USER_MODE:
            self._suppress_sysex = True
        self._update_auto_arm()

    @listens('selected_mode')
    def __on_matrix_mode_changed(self, mode):
        self._update_auto_arm(selected_mode=mode)

    def _update_auto_arm(self, selected_mode = None):
        self._auto_arm.set_enabled(self._user.mode == sysex.LIVE_MODE and (selected_mode or self._matrix_modes.selected_mode) == 'note')

    @listens('instrument')
    def __on_percussion_instrument_changed(self):
        self._select_note_mode()

    def _select_note_mode(self):
        """
        Selects which note mode to use depending on the kind of
        current selected track and its device chain...
        """
        track = self.song.view.selected_track
        drum_device, sliced_simpler = self._percussion_instruments_for_track(track)
        self._drum_component.set_drum_group_device(drum_device)
        self._slicing_component.set_simpler(sliced_simpler)
        if track == None or track.is_foldable or track in self.song.return_tracks or track == self.song.master_track or track.is_frozen:
            self._note_modes.selected_mode = 'disabled'
        elif track and track.has_audio_input:
            self._note_modes.selected_mode = 'looper'
        elif drum_device:
            self._note_modes.selected_mode = 'drums'
        elif sliced_simpler:
            self._note_modes.selected_mode = 'slicing'
        else:
            self._note_modes.selected_mode = 'instrument'
        self.reset_controlled_track()

    def _percussion_instruments_for_track(self, track):
        self._percussion_instrument_finder.device_parent = track
        drum_device = self._percussion_instrument_finder.drum_group
        sliced_simpler = self._percussion_instrument_finder.sliced_simpler
        return (drum_device, sliced_simpler)

    def _setup_accidental_touch_prevention(self):
        self._accidental_touch_prevention_layer = BackgroundLayer('tempo_control_tap', 'swing_control_tap', 'master_volume_control_tap', priority=consts.MOMENTARY_DIALOG_PRIORITY)
        self.__on_param_encoder_touched.replace_subjects(self.elements.global_param_touch_buttons_raw)

    @listens_group('value')
    def __on_param_encoder_touched(self, value, encoder):
        """
        When using the parameter encoders, other encoders around it are often accidentally
        touched and will take over the screen.
        By stealing the touch buttons from the encoders, we ensure they are not triggered
        while using any of the parameter encoders.
        """
        if any(imap(lambda e: e.is_pressed(), self.elements.global_param_touch_buttons_raw)):
            self._accidental_touch_prevention_layer.grab(self)
        else:
            self._accidental_touch_prevention_layer.release(self)

    def get_matrix_button(self, column, row):
        return self.elements.matrix_rows_raw[7 - row][column]

    def expect_dialog(self, message):
        self.schedule_message(1, partial(self._dialog.expect_dialog, message))

    def show_notification(self, message, blink_text = None, notification_time = None):
        return self._notification.show_notification(message, blink_text, notification_time)

    def process_midi_bytes(self, midi_bytes, midi_processor):
        if not midi.is_sysex(midi_bytes):
            recipient = self.get_recipient_for_nonsysex_midi_message(midi_bytes)
            if isinstance(recipient, ButtonElement) and midi.extract_value(midi_bytes) != 0 and self._notification is not None:
                self._notification.hide_notification()
        super(PushBase, self).process_midi_bytes(midi_bytes, midi_processor)
Exemple #35
0
class OhmModes(LividControlSurface):

    _sysex_id = 2
    _alt_sysex_id = 7
    _model_name = 'Ohm'
    _version_check = 'b996'
    _host_name = 'Ohm'
    device_provider_class = ModDeviceProvider

    def __init__(self, c_instance):
        super(OhmModes, self).__init__(c_instance)
        self._skin = Skin(OhmColors)
        with self.component_guard():
            self._define_sysex()
            self._setup_controls()
            self._setup_background()
            self._setup_m4l_interface()
            self._setup_translations()
            self._setup_session_control()
            self._setup_mixer_control()
            self._setup_device_control()
            self._setup_transport_control()
            self._setup_drumgroup()
            self._setup_keygroup()
            self._setup_bassgroup()
            self._setup_mod()
            self._setup_modswitcher()
            self._setup_modes()
        self._on_device_changed.subject = self._device_provider

    def _define_sysex(self):
        #self._send_midi(tuple(switchxfader))
        self._reverse_crossfader = SendLividSysexMode(
            self._livid_settings, call='reverse crossfader', message=[1])

    def update_display(self):
        super(OhmModes, self).update_display()
        #self.strobe()

    def _initialize_hardware(self):
        super(OhmModes, self)._initialize_hardware()
        #self._reverse_crossfader.enter_mode()

    def _initialize_script(self):
        super(OhmModes, self)._initialize_script()
        self._main_modes.selected_mode = 'Mix'
        self._session.update()
        self._mixer.update()

    def _setup_controls(self):
        is_momentary = True
        optimized = True
        resource = PrioritizedResource
        self._fader = [
            MonoEncoderElement(msg_type=MIDI_CC_TYPE,
                               channel=CHANNEL,
                               identifier=OHM_FADERS[index],
                               name='Fader_' + str(index),
                               num=index,
                               script=self,
                               optimized_send_midi=optimized,
                               resource_type=resource) for index in range(8)
        ]
        self._button = [
            MonoButtonElement(is_momentary=is_momentary,
                              msg_type=MIDI_NOTE_TYPE,
                              channel=CHANNEL,
                              identifier=OHM_BUTTONS[index],
                              name='Button_' + str(index),
                              script=self,
                              skin=self._skin,
                              optimized_send_midi=optimized,
                              resource_type=resource) for index in range(8)
        ]
        self._dial = [
            MonoEncoderElement(msg_type=MIDI_CC_TYPE,
                               channel=CHANNEL,
                               identifier=OHM_DIALS[index],
                               name='Encoder_' + str(index),
                               num=index,
                               script=self,
                               optimized_send_midi=optimized,
                               resource_type=resource) for index in range(16)
        ]
        self._menu = [
            MonoButtonElement(is_momentary=is_momentary,
                              msg_type=MIDI_NOTE_TYPE,
                              channel=CHANNEL,
                              identifier=OHM_MENU[index],
                              name='Menu_' + str(index),
                              script=self,
                              skin=self._skin,
                              optimized_send_midi=optimized,
                              resource_type=resource) for index in range(6)
        ]
        self._crossfader = MonoEncoderElement(msg_type=MIDI_CC_TYPE,
                                              channel=CHANNEL,
                                              identifier=CROSSFADER,
                                              name='Crossfader',
                                              script=self,
                                              optimized_send_midi=optimized,
                                              resource_type=resource)
        self._livid = MonoButtonElement(is_momentary=is_momentary,
                                        msg_type=MIDI_NOTE_TYPE,
                                        channel=CHANNEL,
                                        identifier=LIVID,
                                        name='Livid_Button',
                                        skin=self._skin,
                                        script=self,
                                        optimized_send_midi=optimized,
                                        resource_type=resource)
        self._shift_l = MonoButtonElement(is_momentary=is_momentary,
                                          msg_type=MIDI_NOTE_TYPE,
                                          channel=CHANNEL,
                                          identifier=SHIFT_L,
                                          name='Page_Button_Left',
                                          script=self,
                                          skin=self._skin,
                                          optimized_send_midi=optimized,
                                          resource_type=resource)
        self._shift_r = MonoButtonElement(is_momentary=is_momentary,
                                          msg_type=MIDI_NOTE_TYPE,
                                          channel=CHANNEL,
                                          identifier=SHIFT_R,
                                          name='Page_Button_Right',
                                          script=self,
                                          skin=self._skin,
                                          optimized_send_midi=optimized,
                                          resource_type=resource)
        self._grid = [[
            MonoButtonElement(is_momentary=is_momentary,
                              msg_type=MIDI_NOTE_TYPE,
                              channel=CHANNEL,
                              identifier=column * 8 + row,
                              name='Grid_' + str(column + (row * 8)),
                              script=self,
                              skin=self._skin,
                              optimized_send_midi=optimized,
                              resource_type=resource) for column in range(8)
        ] for row in range(8)]
        self._matrix = ButtonMatrixElement(
            name='Matrix',
            rows=[[self._grid[row][column] for column in range(8)]
                  for row in range(8)])
        self._dial_matrix = ButtonMatrixElement(
            name='DialMatrix',
            rows=[self._dial[index * 4:(index * 4) + 4] for index in range(4)])
        self._menu_matrix = ButtonMatrixElement(name='MenuMatrix',
                                                rows=[self._menu])
        self._fader_matrix = ButtonMatrixElement(name='FaderMatrix',
                                                 rows=[self._fader])
        self._button_matrix = ButtonMatrixElement(name='ButtonMatrix',
                                                  rows=[self._button])

        self._parameter_controls = ButtonMatrixElement(
            rows=[self._dial[:4], self._dial[4:8]])

    def _setup_background(self):
        self._background = BackgroundComponent(name='Background')
        self._background.layer = Layer(
            priority=3,
            matrix=self._matrix.submatrix[:, :],
            livid_button=self._livid,
            shift_l_button=self._shift_l,
            shift_r_button=self._shift_r,
            crossfader=self._crossfader,
            dial_matrix=self._dial_matrix.submatrix[:, :],
            menu_matrix=self._menu_matrix.submatrix[:, :],
            fader_matrix=self._fader_matrix.submatrix[:, :],
            button_matrix=self._button_matrix.submatrix[:, :])
        self._background.set_enabled(False)

    def _setup_m4l_interface(self):
        self._m4l_interface = M4LInterfaceComponent(
            controls=self.controls, component_guard=self.component_guard)
        self.get_control_names = self._m4l_interface.get_control_names
        self.get_control = self._m4l_interface.get_control
        self.grab_control = self._m4l_interface.grab_control
        self.release_control = self._m4l_interface.release_control

    def _setup_translations(self):
        controls = []
        for array in self._grid:
            for button in array:
                controls.append(button)
        if FADER_BANKING:
            controls = controls + self._dial
        if DIAL_BANKING:
            controls = controls + self._dial
        self._translations = TranslationComponent(
            controls=controls, user_channel_offset=USER_CHANNEL, channel=8)
        self._translations.layer = Layer(
            priority=5,
            channel_selector_buttons=self._menu_matrix.submatrix[:, :])
        self._translations.set_enabled(False)

        dj_controls = [self._grid[7][index] for index in range(7)]
        self._dj_translation = TranslationComponent(controls=dj_controls,
                                                    channel=12)

    def _setup_session_control(self):
        self._session_ring = SessionRingComponent(num_tracks=7, num_scenes=5)
        self._session_ring.set_enabled(True)

        self._session_navigation = SessionNavigationComponent(
            session_ring=self._session_ring)
        self._session_navigation.scroll_navigation_layer = AddLayerMode(
            self._session_navigation,
            Layer(priority=5,
                  up_button=self._menu[2],
                  down_button=self._menu[5],
                  left_button=self._menu[3],
                  right_button=self._menu[4]))
        self._session_navigation.page_navigation_layer = AddLayerMode(
            self._session_navigation,
            Layer(priority=5,
                  page_up_button=self._menu[2],
                  page_down_button=self._menu[5],
                  page_left_button=self._menu[3],
                  page_right_button=self._menu[4]))
        self._session_navigation._vertical_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
        self._session_navigation._vertical_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
        self._session_navigation._horizontal_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
        self._session_navigation._horizontal_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
        self._session_navigation._vertical_paginator.scroll_up_button.color = 'Session.PageNavigationButtonOn'
        self._session_navigation._vertical_paginator.scroll_down_button.color = 'Session.PageNavigationButtonOn'
        self._session_navigation._horizontal_paginator.scroll_up_button.color = 'Session.PageNavigationButtonOn'
        self._session_navigation._horizontal_paginator.scroll_down_button.color = 'Session.PageNavigationButtonOn'
        self._session_navigation.set_enabled(False)

        self._session = OhmSessionComponent(name='Session',
                                            session_ring=self._session_ring,
                                            auto_name=True)
        hasattr(self._session,
                '_enable_skinning') and self._session._enable_skinning()
        self._session.set_enabled(False)
        self._session.clip_launch_layer = AddLayerMode(
            self._session,
            Layer(priority=5,
                  clip_launch_buttons=self._matrix.submatrix[:7, :5]))
        self._session.scene_launch_layer = AddLayerMode(
            self._session,
            Layer(priority=5,
                  scene_launch_buttons=self._matrix.submatrix[7, :5]))

        self._session_zoom = SessionOverviewComponent(
            name='Session_Overview',
            session_ring=self._session_ring,
            enable_skinning=True)
        self._session_zoom.layer = Layer(
            priority=5, button_matrix=self._matrix.submatrix[:7, :5])
        self._session_zoom.set_enabled(False)

        self._session_modes = ModesComponent(name='Session_Modes')
        self._session_modes.add_mode('disabled', [
            self._session, self._session.clip_launch_layer,
            self._session.scene_launch_layer, self._session_navigation,
            self._session_navigation.scroll_navigation_layer
        ])
        self._session_modes.add_mode('enabled', [
            self._session, self._session.scene_launch_layer,
            self._session_zoom, self._session_navigation,
            self._session_navigation.page_navigation_layer
        ],
                                     behaviour=DefaultedBehaviour())
        self._session_modes.layer = Layer(priority=5,
                                          enabled_button=self._grid[7][7])
        self._session_modes.selected_mode = 'disabled'
        self._session_modes.set_enabled(False)

    def _setup_mixer_control(self):
        self._mixer = OhmMixerComponent(
            name='Mixer',
            tracks_provider=self._session_ring,
            track_assigner=SimpleTrackAssigner(),
            invert_mute_feedback=True,
            auto_name=True,
            enable_skinning=True,
            channel_strip_component_type=MonoChannelStripComponent)
        self._mixer.layer = Layer(
            priority=5,
            volume_controls=self._fader_matrix.submatrix[:7, :],
            prehear_volume_control=self._dial[15],
            crossfader_control=self._crossfader)
        self._mixer.master_strip().layer = Layer(priority=5,
                                                 volume_control=self._fader[7],
                                                 select_button=self._button[7])
        self._mixer.mix_layer = AddLayerMode(
            self._mixer,
            Layer(
                priority=5,
                mute_buttons=self._matrix.submatrix[:7, 5],
                solo_buttons=self._matrix.submatrix[:7, 6],
                arm_buttons=self._matrix.submatrix[:7, 7],
                send_controls=self._dial_matrix.submatrix[:, :2],
                pan_controls=self._dial_matrix.submatrix[:7, 2:],
                track_select_buttons=self._button_matrix.submatrix[:7, :],
            ))
        self._mixer.dj_layer = AddLayerMode(
            self._mixer,
            Layer(
                priority=5,
                mute_buttons=self._matrix.submatrix[:7, 5],
                crossfade_toggles=self._matrix.submatrix[:7, 6],
                end_pan_controls=self._dial_matrix.submatrix[:3, 3],
                eq_gain_controls=self._dial_matrix.submatrix[:, :3],
                track_select_buttons=self._button_matrix.submatrix[:7, :],
            ))
        self._mixer.instrument_layer = AddLayerMode(
            self._mixer,
            Layer(priority=5,
                  instrument_send_controls=self._dial_matrix.submatrix[:, 2:],
                  arming_track_select_buttons=self._button_matrix.
                  submatrix[:7, :]))

    def _setup_device_control(self):
        self._device = OhmDeviceComponent(
            script=self,
            name='Device_Component',
            device_provider=self._device_provider,
            device_bank_registry=DeviceBankRegistry())
        self._device.layer = Layer(priority=5,
                                   parameter_controls=self._parameter_controls)
        self._device.set_enabled(False)

        self._device_navigator = DeviceNavigator(
            self._device_provider,
            self._mixer,
            self,
            name='Device_Navigator',
        )
        self._device_navigator.layer = Layer(priority=5,
                                             prev_button=self._menu[3],
                                             next_button=self._menu[4])
        self._device_navigator.set_enabled(False)

    def _setup_transport_control(self):
        self._transport = OhmTransportComponent()
        self._transport.name = 'Transport'
        self._transport.layer = Layer(priority=5,
                                      play_button=self._menu[0],
                                      stop_button=self._menu[1])
        self._transport.set_enabled(False)

    def _setup_drumgroup(self):
        self._drumgroup = MonoDrumGroupComponent(
            translation_channel=PAGE1_DRUM_CHANNEL,
            set_pad_translations=self.set_pad_translations)
        self._drumgroup._on_selected_track_changed.subject = None
        self._drumgroup.translation_channel = PAGE1_DRUM_CHANNEL
        self._drumgroup.layer = Layer(priority=6,
                                      matrix=self._matrix.submatrix[:4, :4])
        self._drumgroup.set_enabled(False)

    def _setup_keygroup(self):
        self._scale_mode = ModesComponent(name='ScaleMode')
        for scale in SCALES:
            debug('making scale mode:', scale, str(scale))
            self._scale_mode.add_mode(str(scale), [])
        self._scale_mode.layer = Layer(priority=5,
                                       ionian_button=self._grid[7][0],
                                       dorian_button=self._grid[7][1],
                                       phrygian_button=self._grid[7][2],
                                       lydian_button=self._grid[7][3],
                                       mixolydian_button=self._grid[7][4],
                                       aeolian_button=self._grid[7][5],
                                       locrian_button=self._grid[7][6],
                                       major_button=self._grid[7][7])
        self._scale_mode.selected_mode = 'ionian'
        self._scale_mode.set_enabled(False)
        self._on_scale_change.subject = self._scale_mode

        self._octave_offset_component = ScrollingChannelizedSettingsComponent(
            name='NoteOffset',
            parent_task_group=self._task_group,
            value_dict=range(104),
            default_value_index=36,
            default_channel=0,
            bank_increment=12,
            bank_on_color='MonoInstrument.OffsetOnValue',
            bank_off_color='MonoInstrument.OffsetOffValue')
        self._octave_offset_component.layer = Layer(
            priority=5,
            bank_up_button=self._menu[2],
            bank_down_button=self._menu[5])
        self._on_octave_change.subject = self._octave_offset_component

        self._keygroup = OhmKeyGroupComponent()
        self._keygroup._on_selected_track_changed.subject = None
        self._keygroup.translation_channel = PAGE1_KEYS_CHANNEL
        self._keygroup.layer = Layer(priority=6,
                                     matrix=self._matrix.submatrix[:, 4:7])
        self._keygroup.set_enabled(False)

    def _setup_bassgroup(self):
        self._bassgroup = OhmBassGroupComponent()
        self._bassgroup._on_selected_track_changed.subject = None
        self._bassgroup.translation_channel = PAGE1_BASS_CHANNEL
        self._bassgroup.layer = Layer(priority=6,
                                      matrix=self._matrix.submatrix[4:, :4])
        self._bassgroup.set_enabled(False)

    def _setup_mod(self):
        self.monomodular = get_monomodular(self)
        self.monomodular.name = 'monomodular_switcher'
        self.modhandler = OhmModHandler(script=self,
                                        device_provider=self._device_provider)
        self.modhandler.name = 'ModHandler'
        self.modhandler.layer = Layer(
            priority=5,
            grid=self._matrix.submatrix[:, :],
            nav_up_button=self._menu[2],
            nav_down_button=self._menu[5],
            nav_left_button=self._menu[3],
            nav_right_button=self._menu[4],
            shift_button=self._menu[1],
            alt_button=self._menu[0],
        )
        #parameter_controls = self._dial_matrix)
        self.modhandler.legacy_shift_mode = AddLayerMode(
            self.modhandler,
            Layer(priority=6,
                  channel_buttons=self._matrix.submatrix[:, 1],
                  nav_matrix=self._matrix.submatrix[4:8, 2:6]))
        self.modhandler.shift_mode = AddLayerMode(
            self.modhandler,
            Layer(priority=6,
                  device_selector_matrix=self._matrix.submatrix[:, 0],
                  lock_button=self._livid,
                  key_buttons=self._matrix.submatrix[:, 7]))

        self.modhandler.set_enabled(False)
        self.modhandler.set_mod_button(self._livid)

    def _setup_modswitcher(self):
        self._modswitcher = ModesComponent(name='ModSwitcher')
        self._modswitcher.add_mode('mod', [
            self.modhandler, self._device,
            DelayMode(self.modhandler.update, delay=.5)
        ])
        self._modswitcher.add_mode('translations', [self._translations])
        self._modswitcher.selected_mode = 'translations'
        self._modswitcher.set_enabled(False)

    def _setup_modes(self):

        self._main_modes = ModesComponent(name='MainModes')
        self._main_modes.add_mode('disabled', [self._background])
        self._main_modes.add_mode('Mix', [
            self._session_modes, self._mixer, self._mixer.mix_layer,
            self._transport
        ])

        self._main_modes.add_mode(
            'DJ', [
                self._session_modes, self._mixer, self._mixer.dj_layer,
                self._dj_translation,
                tuple([self._assign_tempo, self._deassign_tempo])
            ],
            behaviour=DefaultedBehaviour(default_mode='Mix'))
        #tuple([ lambda:self._set_tempo_buttons([self._grid[7][5], self._grid[7][6]]), self._set_tempo_buttons([])])],

        self._main_modes.add_mode(
            'Instrument', [
                self._update_keygroup_colors, self._bassgroup, self._keygroup,
                self._scale_mode, self._octave_offset_component, self._device,
                self._device_navigator, self._mixer,
                self._mixer.instrument_layer, self._drumgroup
            ],
            behaviour=DefaultedBehaviour(default_mode='Mix'))

        self._main_modes.add_mode(
            'Mod', [
                self._modswitcher, self._device, self._mixer,
                self._mixer.instrument_layer
            ],
            behaviour=DefaultedBehaviour(default_mode='Mix'))
        self._main_modes.layer = Layer(priority=5,
                                       Instrument_button=self._shift_l,
                                       DJ_button=self._shift_r,
                                       Mod_button=self._livid)
        self._main_modes.selected_mode = 'disabled'
        self._main_modes.set_enabled(True)

    def disconnect(self):
        super(OhmModes, self).disconnect()

    def strobe(self):
        if self._backlight_type != 'static':
            if self._backlight_type is 'pulse':
                self._backlight = int(
                    math.fabs(self._timer * 16 % 64 - 32) + 32)
            if self._backlight_type is 'up':
                self._backlight = int(self._timer * 8 % 64 + 16)
            if self._backlight_type is 'down':
                self._backlight = int(
                    math.fabs(int(self._timer * 8 % 64 - 64)) + 16)
        self._send_midi(tuple([176, 27, int(self._backlight)]))
        if self._ohm_type != 'static':
            if self._ohm_type is 'pulse':
                self._ohm = int(math.fabs(self._timer * 16 % 64 - 32) + 32)
            if self._ohm_type is 'up':
                self._ohm = int(self._timer * 8 % 64 + 16)
            if self._ohm_type is 'down':
                self._ohm = int(math.fabs(int(self._timer * 8 % 64 - 64)) + 16)
        self._send_midi(tuple([176, 63, int(self._ohm)]))
        self._send_midi(tuple([176, 31, int(self._ohm)]))

    def handle_sysex(self, midi_bytes):
        debug('sysex: ', str(midi_bytes))
        if len(midi_bytes) > 14:
            if midi_bytes[:6] == tuple([240, 0, 1, 97, 12, 64]):
                self._register_pad_pressed(midi_bytes[6:14])
            elif midi_bytes[:6] == tuple([240, 0, 1, 97, 17, 64]):
                self._register_pad_pressed(midi_bytes[6:14])
            elif midi_bytes[3:11] == tuple(
                [6, 2, 0, 1, 97, 1, 0] +
                [self._sysex_id]) or midi_bytes[3:11] == tuple(
                    [6, 2, 0, 1, 97, 1, 0] + [self._alt_sysex_id]):
                if not self._connected:
                    #self._connection_routine.kill()
                    self._connected = True
                    self._livid_settings.set_model(midi_bytes[11])
                    self._initialize_hardware()
                    self.schedule_message(1, self._initialize_script)

    @listens('device')
    def _on_device_changed(self):
        self.schedule_message(1, self._update_modswitcher)
        #debug('base on_device_changed')
        self._update_modswitcher()

    def _on_selected_track_changed(self):
        super(OhmModes, self)._on_selected_track_changed()
        if not len(self.song.view.selected_track.devices):
            self._update_modswitcher()

    def _update_modswitcher(self):
        debug('update modswitcher, mod is:', self.modhandler.active_mod())
        if self.modhandler.active_mod():
            self._modswitcher.selected_mode = 'mod'
        else:
            self._modswitcher.selected_mode = 'translations'

    @listens('selected_mode')
    def _on_scale_change(self, mode):
        debug('new scale is:', mode, self._scale_mode.selected_mode)
        self._keygroup.scale = SCALES.index(self._scale_mode.selected_mode)

    @listens('value')
    def _on_octave_change(self, value):
        self._keygroup.offset = value

    #stupid hack....4 hours wasted on two buttons is too long, so we're doing this instead
    def _update_keygroup_colors(self):
        self._grid[5][7].send_value(2, force=True)
        self._grid[6][7].send_value(2, force=True)

    #everything below needs to be consolidated into transport component
    def _assign_tempo(self):
        self._grid[5][7].send_value(4, True)
        self._grid[6][7].send_value(4, True)
        self._tempo_up_value.subject = self._grid[5][7]
        self._tempo_down_value.subject = self._grid[6][7]

    def _deassign_tempo(self):
        self._tempo_up_value.subject and self._tempo_up_value.subject.turn_off(
        )
        self._tempo_down_value.subject and self._tempo_down_value.subject.turn_off(
        )
        self._tempo_up_value.subject = None
        self._tempo_down_value.subject = None

    @listens('value')
    def _tempo_up_value(self, value):
        if value:
            self.song.tempo = round(min(self.song.tempo + 1, 999))

    @listens('value')
    def _tempo_down_value(self, value):
        if value:
            self.song.tempo = round(max(self.song.tempo - 1, 20))
Exemple #36
0
class Cntrlr(LividControlSurface):
	__module__ = __name__
	__doc__ = " Monomodular controller script for Livid CNTRLR "


	_sysex_id = 8
	_model_name = 'Cntrlr'
	_host_name = 'Cntrlr'
	_version_check = 'b996'
	monomodular = None
	device_provider_class = ModDeviceProvider


	def __init__(self, *a, **k):
		super(Cntrlr, self).__init__(*a, **k)
		self._skin = Skin(CntrlrColors)
		self._device_selection_follows_track_selection = FOLLOW
		with self.component_guard():
			self._setup_monobridge()
			self._setup_controls()
			self._define_sysex()
			self._setup_background()
			self._setup_translations()
			#self._setup_autoarm()
			self._setup_session_control()
			self._setup_send_reset_controls()
			self._setup_mixer_control()
			self._setup_transport_control()
			self._setup_device_control()
			self._setup_mod_device_control()
			self._setup_device_selector()
			#self._setup_session_recording_component()
			#self._setup_viewcontrol()
			#self._setup_instrument()
			self._setup_mod()
			self._setup_modswitcher()
			self._setup_translations()
			self._setup_modes()
			self._setup_m4l_interface()
			self._on_device_changed.subject = self.song
			#self.set_feedback_channels(range(14, 15))


	def _initialize_script(self):
		super(Cntrlr, self)._initialize_script()
		self._connected = True
		self._main_modes.selected_mode = 'MixMode'
		self._main_modes.set_enabled(True)
		#self._instrument.set_enabled(True)
		#self._main_modes.selected_mode = 'disabled'
		#self._main_modes.selected_mode = 'MixMode'
		self._session_ring._update_highlight()
		self._session_ring.track_offset = 0
		if liveobj_valid(self.song.visible_tracks[0]):
			self.song.view.selected_track = self.song.visible_tracks[0]


	def _initialize_hardware(self):
		super(Cntrlr, self)._initialize_hardware()
		for index in range(4):
			self._encoder[index].send_value(0)


	def port_settings_changed(self):
		self._main_modes.selected_mode = 'disabled'
		super(Cntrlr, self).port_settings_changed()


	def _setup_monobridge(self):
		self._monobridge = MonoBridgeElement(self)
		self._monobridge.name = 'MonoBridge'


	def _setup_controls(self):
		is_momentary = True
		optimized = True
		resource = PrioritizedResource
		self._fader = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_FADERS[index], name = 'Fader_' + str(index), num = index, script = self,  optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(8)]
		self._dial_left = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_KNOBS_LEFT[index], name = 'Dial_Left_' + str(index), num = CNTRLR_KNOBS_LEFT[index], script = self, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)]
		self._dial_right = [MonoEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_KNOBS_RIGHT[index], name = 'Dial_Right_' + str(index), num = CNTRLR_KNOBS_RIGHT[index], script = self, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)]
		self._encoder = [CodecEncoderElement(msg_type = MIDI_CC_TYPE, channel = CHANNEL, identifier = CNTRLR_DIALS[index], name = 'Encoder_' + str(index), num = CNTRLR_DIALS[index], script = self, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)]
		self._encoder_button = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CNTRLR_DIAL_BUTTONS[index], name = 'Encoder_Button_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(12)]
		self._grid = [MonoButtonElement(is_momentary = is_momentary, msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CNTRLR_GRID[index], name = 'Grid_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(16)]
		self._button = [MonoButtonElement(is_momentary = is_momentary,msg_type = MIDI_NOTE_TYPE, channel = CHANNEL, identifier = CNTRLR_BUTTONS[index], name = 'Button_' + str(index), script = self, skin = self._skin, color_map = COLOR_MAP, optimized_send_midi = optimized, resource_type = resource, monobridge = self._monobridge) for index in range(32)]
		self._knobs = self._dial_left + self._dial_right

		self._fader_matrix = ButtonMatrixElement(name = 'Fader_Matrix', rows = [self._fader])
		self._matrix = ButtonMatrixElement(name = 'Matrix', rows = [self._grid[index*4:(index*4)+4] for index in range(4)])
		self._knob_left_matrix = ButtonMatrixElement(name = 'Knob_Left_Matrix', rows = [self._dial_left[index*4:(index*4)+4] for index in range(3)])
		self._knob_right_matrix = ButtonMatrixElement(name = 'Knob_Right_Matrix', rows = [self._dial_right[index*4:(index*4)+4] for index in range(3)])
		self._dial_matrix = ButtonMatrixElement(name = 'Dial_Matrix', rows = [self._encoder[index*4:(index*4)+4] for index in range(3)])
		self._dial_button_matrix = ButtonMatrixElement(name = 'Dial_Button_Matrix', rows = [self._encoder_button[index*4:(index*4)+4] for index in range(1,3)])
		self._key_matrix = ButtonMatrixElement(name = 'Key_Matrix', rows = [self._button[0:16], self._button[16:32]])

		self._translated_controls = self._grid + self._button


	def _setup_background(self):
		self._background = BackgroundComponent(name = 'Background')
		self._background.layer = Layer(priority = 3, matrix = self._matrix.submatrix[:,:], faders = self._fader_matrix.submatrix[:,:], left_knobs = self._knob_left_matrix.submatrix[:,:], right_knobs = self._knob_right_matrix.submatrix[:,:], dials = self._dial_matrix, dial_buttons = self._dial_button_matrix.submatrix[:,:], keys = self._key_matrix.submatrix[:,:])
		self._background.set_enabled(True)


	def _define_sysex(self):
		self.encoder_navigation_on = SendLividSysexMode(livid_settings = self._livid_settings, call = 'set_encoder_encosion_mode', message = [0, 0, 0, 0])


	def _setup_transport_control(self):
		self._transport = CntrlrTransportComponent(name = 'Transport')
		self._transport._play_toggle.view_transform = lambda value: 'Transport.PlayOn' if value else 'Transport.PlayOff'
		self._transport._record_toggle.view_transform = lambda value: 'Transport.RecordOn' if value else 'Transport.RecordOff'
		self._transport.layer = Layer(priority = 4,
									play_button = self._button[28],
									stop_button = self._button[29],
									record_button = self._button[30])
		self._transport.set_enabled(False)


	def _setup_autoarm(self):
		self._auto_arm = CntrlrAutoArmComponent(name='Auto_Arm')
		#self._auto_arm._update_notification = lambda a: None
		self._auto_arm.can_auto_arm_track = self._can_auto_arm_track


	def _setup_session_recording_component(self):
		self._clip_creator = ClipCreator()
		self._clip_creator.name = 'ClipCreator'
		self._recorder = FixedLengthSessionRecordingComponent(clip_creator = self._clip_creator, view_controller = ViewControlComponent(), name = 'SessionRecorder') # is_enabled = False)
		self._recorder.main_layer = AddLayerMode(self._recorder, Layer(priority = 4, record_button = self._button[29]))
		self._recorder.shift_layer = AddLayerMode(self._recorder, Layer(priority = 4, automation_button = self._button[29]))
		self._recorder.set_enabled(False)


	def _setup_session_control(self):
		self._session_ring = SessionRingComponent(num_tracks = 4, num_scenes = 4)
		self._session_ring.set_enabled(False)

		self._session_navigation = CntrlrSessionNavigationComponent(name = 'SessionNavigation', session_ring = self._session_ring)

		self._session_navigation._vertical_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._vertical_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._horizontal_banking.scroll_up_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._horizontal_banking.scroll_down_button.color = 'Session.NavigationButtonOn'
		self._session_navigation._vertical_paginator.scroll_up_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._vertical_paginator.scroll_down_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._horizontal_paginator.scroll_up_button.color = 'Session.PageNavigationButtonOn'
		self._session_navigation._horizontal_paginator.scroll_down_button.color = 'Session.PageNavigationButtonOn'

		self._session_navigation.layer = Layer(priority = 4,
									down_button = self._button[14],
									up_button = self._button[15],
									left_button = self._button[12],
									right_button = self._button[13])

		self._session_navigation.set_enabled(False)

		self._session = SessionComponent(session_ring = self._session_ring, auto_name = True)
		hasattr(self._session, '_enable_skinning') and self._session._enable_skinning()

		self._session.layer = Layer(priority = 4, clip_launch_buttons = self._matrix.submatrix[:,:])
		self._session.set_enabled(False)

		self._session_zoom = SessionOverviewComponent(name = 'SessionZoom', session_ring = self._session_ring, enable_skinning = True)
		self._session_zoom.layer = Layer(priority = 4, button_matrix = self._matrix.submatrix[:,:])
		self._session_zoom.set_enabled(False)


	def _setup_send_reset_controls(self):
		self._send_reset = ResetSendsComponent(script = self)
		self._send_reset.layer = Layer(priority = 4, buttons = self._key_matrix.submatrix[8:12, :1])
		self._send_reset.set_enabled(False)


	def _setup_mixer_control(self):
		self._mixer = MonoMixerComponent(name = 'Mixer', num_returns = 2,tracks_provider = self._session_ring, track_assigner = SimpleTrackAssigner(), invert_mute_feedback = True, auto_name = True, enable_skinning = True)
		self._mixer.fader_layer = AddLayerMode(self._mixer, Layer(priority = 4, volume_controls = self._fader_matrix.submatrix[:4, :],
											return_controls = self._fader_matrix.submatrix[4:6, :],
											prehear_volume_control = self._fader[6],
											send_controls = self._knob_left_matrix,
											eq_gain_controls = self._knob_right_matrix))
		self._mixer.button_layer = AddLayerMode(self._mixer, Layer(priority = 4, mute_buttons = self._key_matrix.submatrix[:4, 1:],
											stop_clip_buttons = self._key_matrix.submatrix[8:12, 1:],
											solo_buttons = self._key_matrix.submatrix[:4, :1],
											arm_buttons = self._key_matrix.submatrix[4:8, :1],
											track_select_buttons = self._key_matrix.submatrix[4:8, 1:],))
		self._mixer.master_strip().layer = Layer(priority = 4, volume_control = self._fader[7],)

		self._mixer.set_enabled(False)


	def _setup_device_control(self):
		self._device_selection_follows_track_selection = FOLLOW
		self._device = CntrlrDeviceComponent(script = self, name = 'Device_Component', device_provider = self._device_provider, device_bank_registry = DeviceBankRegistry())
		self._device.layer = Layer(priority = 4, parameter_controls = self._dial_matrix.submatrix[:, 1:],
													on_off_button = self._encoder_button[4],
													bank_prev_button = self._encoder_button[8],
													bank_next_button = self._encoder_button[9],)
													#lock_button = self._encoder_button[7])
		self._device.set_enabled(False)

		self._device_navigator = DeviceNavigator(self._device_provider, self._mixer, self)
		self._device_navigator.name = 'Device_Navigator'
		self._device_navigator.layer = Layer(priority = 4,
											prev_button = self._encoder_button[10],
											next_button = self._encoder_button[11],)
		self._device_navigator.set_enabled(False)


	def _setup_mod_device_control(self):
		self._mod_device = SpecialCntrlrDeviceComponent(script = self, name = 'Device_Component', device_provider = self._device_provider, device_bank_registry = DeviceBankRegistry())
		self._mod_device.layer = Layer(priority = 4, parameter_controls = self._dial_matrix.submatrix[:, :],)
		self._mod_device.set_enabled(False)


	def _setup_device_selector(self):
		self._device_selector = CntrlrDeviceSelector(self)
		self._device_selector.name = 'Device_Selector'
		#self._device_selector.select_layer = AddLayerMode(self._device_selector, Layer(priority = 6 , matrix = self._matrix.submatrix[:, :]))
		#self._device_selector.select_layer = AddLayerMode(self._device_selector, Layer(priority = 6, matrix = ButtonMatrixElement(rows = [self._grid[:4],self._grid[4:8],self._grid[8:12],self._grid[12:14]])))
		#self._device_selector.assign_layer = AddLayerMode(self._device_selector, Layer(priority = 7, assign_button = self._grid[14]))
		self._device_selector.set_enabled(False)


	def _setup_translations(self):
		self._translations = TranslationComponent(self._translated_controls, user_channel_offset = 4, channel = 4)	# is_enabled = False)
		self._translations.name = 'TranslationComponent'
		self._translations.layer = Layer(priority = 10,)
		self._translations._color = 127
		self._translations.selector_layer = AddLayerMode(self._translations, Layer(priority = 10, channel_selector_buttons = self._dial_button_matrix))
		self._translations.set_enabled(False)

		#self._optional_translations = CompoundMode(TranslationComponent(controls = self._fader, user_channel_offset = 4, channel = 4, name = 'FaderTranslation', is_enabled = False, layer = Layer(priority = 10)) if FADER_BANKING else None
		#TranslationComponent(controls = self._knobs, user_channel_offset = 4, channel = 4, name = 'DialTranslation', is_enabled = False, layer = Layer(priority = 10)) if DIAL_BANKING else None)


	def _setup_mod(self):
		self.monomodular = get_monomodular(self)
		self.monomodular.name = 'monomodular_switcher'
		self.modhandler = CntrlrModHandler(self, device_provider = self._device_provider) # is_enabled = False)
		self.modhandler.name = 'ModHandler'
		self.modhandler.lock_layer = AddLayerMode(self.modhandler, Layer(priority=8, lock_button=self._grid[15]))
		self.modhandler.layer = Layer(priority = 8,
										cntrlr_encoder_button_grid = self._dial_button_matrix.submatrix[:,:],
										cntrlr_grid = self._matrix.submatrix[:,:],
										cntrlr_keys = self._key_matrix.submatrix[:,:],)
										#parameter_controls = self._dial_matrix.submatrix[:,:])
		self.modhandler.set_enabled(False)


	def _setup_modswitcher(self):
		self._modswitcher = ModesComponent(name = 'ModSwitcher')  # is_enabled = False)
		self._modswitcher.set_enabled(False)


	def _setup_viewcontrol(self):
		self._view_control = CntrlrViewControlComponent(name='View_Control')
		self._view_control.main_layer = AddLayerMode(self._view_control, Layer(scene_select_dial = self._encoder[2],
																				track_select_dial = self._encoder[3],))
		#self._view_control.main_layer = AddLayerMode(self._view_control, Layer(prev_track_button=self._button[24],
		#											next_track_button= self._button[25],
		#											next_scene_button=self._button[27],
		#											prev_scene_button = self._button[26]))
		self._view_control.set_enabled(False)


	def _setup_modes(self):

		self._modswitcher = ModesComponent(name = 'ModSwitcher')
		self._modswitcher.add_mode('mod', [self._mixer,
													self._mixer.fader_layer,
													self.modhandler,
													self._mod_device,
													self._device_selector,])
		self._modswitcher.add_mode('translations', [self._translations,
													self._device,
													self._mixer,
													self._mixer.fader_layer,
													self._device_navigator,
													self._device_selector])
		self._modswitcher.selected_mode = 'translations'
		self._modswitcher.set_enabled(False)

		self._session_modes = ModesComponent(name = 'SessionModes')
		self._session_modes.add_mode('Launch', [self._session])
		self._session_modes.add_mode('Zoom', [self._session_zoom])
		self._session_modes.layer = Layer(priority = 4, cycle_mode_button = self._button[31])
		self._session_modes.set_enabled(False)

		self._main_modes = ModesComponent(name = 'MainModes')
		self._main_modes.add_mode('disabled', [self._background, self.encoder_navigation_on])
		self._main_modes.add_mode('MixMode', [self._mixer,
													self._mixer.fader_layer,
													self._mixer.button_layer,
													self._session_modes,
													self._session_navigation,
													self._session_ring,
													self._device,
													self._device_navigator,
													self._send_reset,
													self._transport])

		self._main_modes.add_mode('ModMode1', [self._modswitcher,
													self._choose_mod,
													DelayMode(self._update_modswitcher, delay = .1, parent_task_group = self._task_group),
													DelayMode(self.modhandler.update, delay = .2, parent_task_group = self._task_group)],
													behaviour = DefaultedBehaviour(default_mode = 'MixMode'))
		self._main_modes.add_mode('ModMode2', [self._modswitcher,
													self._choose_mod,
													DelayMode(self._update_modswitcher, delay = .1, parent_task_group = self._task_group),
													DelayMode(self.modhandler.update, delay = .2, parent_task_group = self._task_group)],
													behaviour = DefaultedBehaviour(default_mode = 'MixMode'))
		self._main_modes.add_mode('ModMode3', [self._modswitcher,
													self._choose_mod,
													DelayMode(self._update_modswitcher, delay = .1, parent_task_group = self._task_group),
													DelayMode(self.modhandler.update, delay = .2, parent_task_group = self._task_group)],
													behaviour = DefaultedBehaviour(default_mode = 'MixMode'))
		self._main_modes.add_mode('ModMode4', [self._modswitcher,
													self._choose_mod,
													DelayMode(self._update_modswitcher, delay = .1, parent_task_group = self._task_group),
													DelayMode(self.modhandler.update, delay = .2, parent_task_group = self._task_group)],
													behaviour = DefaultedBehaviour(default_mode = 'MixMode'))

		self._main_modes.layer = Layer(priority = 4, ModMode1_button = self._encoder_button[0], ModMode2_button = self._encoder_button[1], ModMode3_button = self._encoder_button[2], ModMode4_button = self._encoder_button[3]) #,
		self._main_modes.selected_mode = 'disabled'
		self._main_modes.set_enabled(True)


	def _choose_mod(self):
		modes = ('ModMode1', 'ModMode2', 'ModMode3', 'ModMode4')
		mode = self._main_modes.selected_mode
		debug('choose_mod:', self._main_modes.selected_mode)
		if mode in modes:
			index = modes.index(mode)
			self._translations._channel = index + self._translations._user_channel_offset
			self._translations.update()
			self._device_selector.select_device(index)


	def _setup_m4l_interface(self):
		self._m4l_interface = M4LInterfaceComponent(controls=self.controls, component_guard=self.component_guard, priority = 10)
		self._m4l_interface.name = "M4LInterface"
		self.get_control_names = self._m4l_interface.get_control_names
		self.get_control = self._m4l_interface.get_control
		self.grab_control = self._m4l_interface.grab_control
		self.release_control = self._m4l_interface.release_control


	def _can_auto_arm_track(self, track):
		routing = track.current_input_routing
		return routing == 'Ext: All Ins' or routing == 'All Ins' or routing.startswith('Cntrlr Input')


	@listens('appointed_device')
	def _on_device_changed(self):
		debug('appointed device changed, script')
		#self._main_modes.selected_mode is 'ModSwitcher' and self._update_modswitcher()


	def _on_selected_track_changed(self):
		super(Cntrlr, self)._on_selected_track_changed()
		#self._drum_group_finder.device_parent = self.song.veiw.selected_track
		#if not len(self.song.view.selected_track.devices):
		#	self._main_modes.selected_mode is 'ModSwitcher' and self._update_modswitcher()


	def _update_modswitcher(self):
		debug('update modswitcher', self.modhandler.active_mod())
		if self.modhandler.active_mod() and self._device_selector.has_mod_entry(['ModMode1', 'ModMode2', 'ModMode3', 'ModMode4'].index(self._main_modes.selected_mode)):
			self._modswitcher.selected_mode = 'mod'
		else:
			self._modswitcher.selected_mode = 'translations'


	def update_display(self):
		super(Cntrlr, self).update_display()
		self.modhandler.send_ring_leds()


	def restart_monomodular(self):
		#debug('restart monomodular')
		self.modhandler.disconnect()
		with self.component_guard():
			self._setup_mod()
Exemple #37
0
class Twister(LividControlSurface):
    __module__ = __name__
    __doc__ = " Monomodular controller script for Livid CNTRLR "

    _sysex_id = 8
    _model_name = 'Twister'
    _host_name = 'Twister'
    _version_check = 'b996'
    monomodular = None

    device_provider_class = ModDeviceProvider

    def __init__(self, *a, **k):
        super(Twister, self).__init__(*a, **k)
        self._skin = Skin(TwisterColors)
        self._device_selection_follows_track_selection = True
        with self.component_guard():
            self._setup_monobridge()
            self._setup_controls()
            #self._define_sysex()
            self._setup_background()
            self._setup_m4l_interface()
            self._setup_mod()
            self._setup_device_control()
            self._setup_modes()
        self._on_device_changed.subject = self.song
        self._on_selected_track_changed.subject = self.song.view

    def _initialize_script(self):
        super(Twister, self)._initialize_script()
        self._connected = True

    def _setup_controls(self):
        is_momentary = True
        optimized = True
        resource = PrioritizedResource
        self._encoder = [
            CodecEncoderElement(msg_type=MIDI_CC_TYPE,
                                channel=CHANNEL,
                                identifier=TWISTER_DIALS[index],
                                name='Encoder_' + str(index),
                                num=TWISTER_DIALS[index],
                                script=self,
                                optimized_send_midi=optimized,
                                resource_type=resource,
                                monobridge=self._monobridge)
            for index in range(16)
        ]
        self._encoder_button = [
            TwisterButtonElement(is_momentary=is_momentary,
                                 msg_type=MIDI_CC_TYPE,
                                 channel=1,
                                 identifier=TWISTER_DIAL_BUTTONS[index],
                                 name='Encoder_Button_' + str(index),
                                 script=self,
                                 skin=self._skin,
                                 color_map=COLOR_MAP,
                                 optimized_send_midi=optimized,
                                 resource_type=resource,
                                 monobridge=self._monobridge)
            for index in range(16)
        ]

        self._dial_matrix = ButtonMatrixElement(
            name='Dial_Matrix',
            rows=[
                self._encoder[index * 4:(index * 4) + 4] for index in range(4)
            ])
        self._dial_button_matrix = ButtonMatrixElement(
            name='Dial_Button_Matrix',
            rows=[
                self._encoder_button[index * 4:(index * 4) + 4]
                for index in range(4)
            ])

    def _setup_background(self):
        self._background = BackgroundComponent(name='Background')
        self._background.layer = Layer(
            priority=3,
            dials=self._dial_matrix,
            dial_buttons=self._dial_button_matrix.submatrix[:, :])
        self._background.set_enabled(True)

    def _setup_m4l_interface(self):
        self._m4l_interface = M4LInterfaceComponent(
            controls=self.controls,
            component_guard=self.component_guard,
            priority=10)
        self._m4l_interface.name = "M4LInterface"
        self.get_control_names = self._m4l_interface.get_control_names
        self.get_control = self._m4l_interface.get_control
        self.grab_control = self._m4l_interface.grab_control
        self.release_control = self._m4l_interface.release_control

    def _define_sysex(self):
        pass

    def _check_connection(self):
        self._connected = True
        self._initialize_hardware()
        self._initialize_script()

    def _setup_mixer_control(self):
        self._mixer_session_ring = SessionRingComponent(num_tracks=4,
                                                        num_scenes=4)
        self._mixer = MonoMixerComponent(
            name='Mixer',
            tracks_provider=self._mixer_session_ring,
            track_assigner=simple_track_assigner,
            invert_mute_feedback=True,
            auto_name=True,
            enable_skinning=True)

        self._mixer.layer = Layer(
            priority=4,
            solo_buttons=self._dial_button_matrix.submatrix[:, 0],
            stop_clip_buttons=self._dial_button_matrix.submatrix[:, 1],
            track_select_buttons=self._dial_button_matrix.submatrix[:, 2])
        self._mixer.set_enabled(True)

    def _setup_device_control(self):
        self._device = SpecialDeviceComponent(
            name='Device_Component',
            device_provider=self._device_provider,
            device_bank_registry=DeviceBankRegistry(),
            script=self)
        self._device.layer = Layer(
            priority=4,
            parameter_controls=self._dial_matrix.submatrix[:, :],
        )
        self._device.bank_layer = AddLayerMode(
            self._device,
            Layer(priority=4,
                  bank_prev_button=self._encoder_button[12],
                  bank_next_button=self._encoder_button[13]))
        self._device.set_enabled(False)

    def _setup_mod(self):
        self.monomodular = get_monomodular(self)
        self.monomodular.name = 'monomodular_switcher'
        self.modhandler = TwisterModHandler(
            self, device_provider=self._device_provider)
        self.modhandler.name = 'ModHandler'
        self.modhandler.layer = Layer(
            priority=8,
            twister_encoder_button_grid=self._dial_button_matrix.
            submatrix[:, :],
        )
        #twister_encoder_grid = self._dial_matrix.submatrix[:,:],)
        self.modhandler.set_enabled(False)

    def _setup_modes(self):
        self._modswitcher = ModesComponent(name='ModSwitcher')
        self._modswitcher.add_mode('mod', [self.modhandler, self._device])
        self._modswitcher.add_mode('device',
                                   [self._device, self._device.bank_layer])
        self._modswitcher.selected_mode = 'device'
        self._modswitcher.set_enabled(True)

    def _update_modswitcher(self):
        debug('update modswitcher', self.modhandler.active_mod())
        if self.modhandler.active_mod():
            self._modswitcher.selected_mode = 'mod'
        else:
            self._modswitcher.selected_mode = 'device'

    @listens('appointed_device')
    def _on_device_changed(self):
        debug('appointed device changed, script')
        self._update_modswitcher()

    @listens('selected_track')
    def _on_selected_track_changed(self):
        debug('_on_selected_track_changed')
        #super(Cntrlr, self)._on_selected_track_changed()
        #self._drum_group_finder.device_parent = self.song.veiw.selected_track
        if not len(self.song.view.selected_track.devices):
            self._update_modswitcher()

    def restart_monomodular(self):
        #debug('restart monomodular')
        self.modhandler.disconnect()
        with self.component_guard():
            self._setup_mod()