summaryrefslogtreecommitdiff
path: root/libs/surfaces/launch_control_xl/launch_control_xl.cc
blob: 35d56298d390ccd02210cb050c3efa178e9e765b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
/*
  Copyright (C) 2016 Paul Davis

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include <stdlib.h>
#include <pthread.h>

#include "pbd/compose.h"
#include "pbd/convert.h"
#include "pbd/debug.h"
#include "pbd/failed_constructor.h"
#include "pbd/file_utils.h"
#include "pbd/search_path.h"
#include "pbd/enumwriter.h"

#include "midi++/parser.h"

#include "ardour/amp.h"
#include "ardour/async_midi_port.h"
#include "ardour/audioengine.h"
#include "ardour/debug.h"
#include "ardour/midiport_manager.h"
#include "ardour/midi_track.h"
#include "ardour/midi_port.h"
#include "ardour/session.h"
#include "ardour/solo_isolate_control.h"
#include "ardour/tempo.h"
#include "ardour/types_convert.h"
#include "ardour/vca_manager.h"


#include "gtkmm2ext/gui_thread.h"

#include "gui.h"
#include "launch_control_xl.h"

#include "pbd/i18n.h"

#ifdef PLATFORM_WINDOWS
#define random() rand()
#endif

using namespace ARDOUR;
using namespace std;
using namespace PBD;
using namespace Glib;
using namespace ArdourSurface;
#include "pbd/abstract_ui.cc" // instantiate template

/* init global object */
LaunchControlXL* lcxl = 0;

LaunchControlXL::LaunchControlXL (ARDOUR::Session& s)
	: ControlProtocol (s, string (X_("Novation Launch Control XL")))
	, AbstractUI<LaunchControlRequest> (name())
	, in_use (false)
	, _track_mode(TrackMute)
	, _template_number(8) // default template (factory 1)
	, _fader8master (false)
	, _refresh_leds_flag (false)
	, bank_start (0)
	, connection_state (ConnectionState (0))
	, gui (0)
	, in_range_select (false)
{
	lcxl = this;
	/* we're going to need this */

	build_maps ();

	/* master cannot be removed, so no need to connect to going-away signal */
	master = session->master_out ();

	run_event_loop ();

	/* Ports exist for the life of this instance */

	ports_acquire ();

	/* catch arrival and departure of LaunchControlXL itself */
	ARDOUR::AudioEngine::instance()->PortRegisteredOrUnregistered.connect (port_reg_connection, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::port_registration_handler, this), this);

	/* Catch port connections and disconnections */
	ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (port_connection, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::connection_handler, this, _1, _2, _3, _4, _5), this);

	/* Launch Control XL ports might already be there */
	port_registration_handler ();

	session->RouteAdded.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::stripables_added, this), lcxl);
	session->vca_manager().VCAAdded.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::stripables_added, this), lcxl);

	switch_bank (bank_start);
}

LaunchControlXL::~LaunchControlXL ()
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, "Launch Control XL  control surface object being destroyed\n");

	/* do this before stopping the event loop, so that we don't get any notifications */
	port_reg_connection.disconnect ();
	port_connection.disconnect ();
	session_connections.drop_connections ();
	stripable_connections.drop_connections ();

	stop_using_device ();
	ports_release ();

	stop_event_loop ();
	tear_down_gui ();
}


void
LaunchControlXL::run_event_loop ()
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, "start event loop\n");
	BaseUI::run ();
}

void
LaunchControlXL::stop_event_loop ()
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, "stop event loop\n");
	BaseUI::quit ();
}

int
LaunchControlXL::begin_using_device ()
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, "begin using device\n");

	switch_template(template_number()); // first factory template

	connect_session_signals ();

	init_buttons (true);

	in_use = true;

	DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose("fader8master inital value  '%1'\n", fader8master()));
	set_fader8master (fader8master());

	return 0;
}

int
LaunchControlXL::stop_using_device ()
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, "stop using device\n");

	if (!in_use) {
		DEBUG_TRACE (DEBUG::LaunchControlXL, "nothing to do, device not in use\n");
		return 0;
	}

	init_buttons (false);

	session_connections.drop_connections ();

	in_use = false;
	return 0;
}

int
LaunchControlXL::ports_acquire ()
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, "acquiring ports\n");

	/* setup ports */

	_async_in  = AudioEngine::instance()->register_input_port (DataType::MIDI, X_("Launch Control XL in"), true);
	_async_out = AudioEngine::instance()->register_output_port (DataType::MIDI, X_("Launch Control XL out"), true);

	if (_async_in == 0 || _async_out == 0) {
		DEBUG_TRACE (DEBUG::LaunchControlXL, "cannot register ports\n");
		return -1;
	}

	/* We do not add our ports to the input/output bundles because we don't
	 * want users wiring them by hand. They could use JACK tools if they
	 * really insist on that (and use JACK)
	 */

	_input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in).get();
	_output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_out).get();

	session->BundleAddedOrRemoved ();

	connect_to_parser ();

	/* Connect input port to event loop */

	AsyncMIDIPort* asp;

	asp = static_cast<AsyncMIDIPort*> (_input_port);
	asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &LaunchControlXL::midi_input_handler), _input_port));
	asp->xthread().attach (main_loop()->get_context());

	return 0;
}

void
LaunchControlXL::ports_release ()
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, "releasing ports\n");

	/* wait for button data to be flushed */
	AsyncMIDIPort* asp;
	asp = static_cast<AsyncMIDIPort*> (_output_port);
	asp->drain (10000, 500000);

	{
		Glib::Threads::Mutex::Lock em (AudioEngine::instance()->process_lock());
		AudioEngine::instance()->unregister_port (_async_in);
		AudioEngine::instance()->unregister_port (_async_out);
	}

	_async_in.reset ((ARDOUR::Port*) 0);
	_async_out.reset ((ARDOUR::Port*) 0);
	_input_port = 0;
	_output_port = 0;
}

list<boost::shared_ptr<ARDOUR::Bundle> >
LaunchControlXL::bundles ()
{
	list<boost::shared_ptr<ARDOUR::Bundle> > b;

	if (_output_bundle) {
		b.push_back (_output_bundle);
	}

	return b;
}


void
LaunchControlXL::init_buttons (bool startup)
{
	reset(template_number());

	if (startup) {
		switch_bank(bank_start);
	}
}

bool
LaunchControlXL::probe ()
{
	return true;
}

void*
LaunchControlXL::request_factory (uint32_t num_requests)
{
	/* AbstractUI<T>::request_buffer_factory() is a template method only
	   instantiated in this source module. To provide something visible for
	   use in the interface/descriptor, we have this static method that is
	   template-free.
	*/
	return request_buffer_factory (num_requests);
}

void
LaunchControlXL::do_request (LaunchControlRequest * req)
{
	if (req->type == CallSlot) {

		call_slot (MISSING_INVALIDATOR, req->the_slot);

	} else if (req->type == Quit) {

		stop_using_device ();
	}
}

void
LaunchControlXL::reset(uint8_t chan)
{
	MidiByteArray msg (3, 176 + chan, 0, 0); // turn off all leds, reset buffer settings and duty cycle

	write(msg);
}
int
LaunchControlXL::set_active (bool yn)
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose("LaunchControlProtocol::set_active init with yn: '%1'\n", yn));

	if (yn == active()) {
		return 0;
	}

	if (yn) {
		if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
			begin_using_device ();
		} else {
			/* begin_using_device () will get called once we're connected */
		}

	} else {
		/* Control Protocol Manager never calls us with false, but
		 * insteads destroys us.
		 */
	}

	ControlProtocol::set_active (yn);

	DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose("LaunchControlProtocol::set_active done with yn: '%1'\n", yn));

	return 0;
}

void
LaunchControlXL::write (const MidiByteArray& data)
{
	/* immediate delivery */
	_output_port->write (&data[0], data.size(), 0);
}

/* Device to Ardour message handling */

bool
LaunchControlXL::midi_input_handler (IOCondition ioc, MIDI::Port* port)
{
	if (ioc & ~IO_IN) {
		DEBUG_TRACE (DEBUG::LaunchControlXL, "MIDI port closed\n");
		return false;
	}

	if (ioc & IO_IN) {

		DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("something happened on  %1\n", port->name()));

		AsyncMIDIPort* asp = static_cast<AsyncMIDIPort*>(port);
		if (asp) {
			asp->clear ();
		}

		DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("data available on %1\n", port->name()));
		if (in_use) {
			samplepos_t now = AudioEngine::instance()->sample_time();
			port->parse (now);
		}
	}

	return true;
}


void
LaunchControlXL::connect_to_parser ()
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("Connecting to signals on port %1\n", _input_port->name()));

	MIDI::Parser* p = _input_port->parser();

	/* Incoming sysex */
	p->sysex.connect_same_thread (*this, boost::bind (&LaunchControlXL::handle_midi_sysex, this, _1, _2, _3));

 for (MIDI::channel_t n = 0; n < 16; ++n) {
	/* Controller */
		p->channel_controller[(int)n].connect_same_thread (*this, boost::bind (&LaunchControlXL::handle_midi_controller_message, this, _1, _2, n));
		/* Button messages are NoteOn */
		p->channel_note_on[(int)n].connect_same_thread (*this, boost::bind (&LaunchControlXL::handle_midi_note_on_message, this, _1, _2, n));
		/* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
		p->channel_note_off[(int)n].connect_same_thread (*this, boost::bind (&LaunchControlXL::handle_midi_note_off_message, this, _1, _2, n));
	}
}

void
LaunchControlXL::handle_midi_sysex (MIDI::Parser&, MIDI::byte* raw_bytes, size_t sz)
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("Sysex, %1 bytes\n", sz));

	if (sz < 8) {
		return;
	}

	MidiByteArray msg (sz, raw_bytes);
	MidiByteArray lcxl_sysex_header (6, 0xF0, 0x00, 0x20, 0x29, 0x02, 0x11);

	if (!lcxl_sysex_header.compare_n (msg, 6)) {
		return;
	}


	switch (msg[6]) {
	case 0x77: /* template change */
		DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("Template change: %1 n", msg[7]));
		_template_number = msg[7];
		break;
	}
}


void
LaunchControlXL::handle_button_message(boost::shared_ptr<Button> button, MIDI::EventTwoBytes* ev)
{
  if (ev->value) {
    /* any press cancels any pending long press timeouts */
    for (set<ButtonID>::iterator x = buttons_down.begin(); x != buttons_down.end(); ++x) {
	    boost::shared_ptr<ControllerButton> cb = id_controller_button_map[*x];
	    boost::shared_ptr<NoteButton>	nb = id_note_button_map[*x];
			if (cb != 0) {
				cb->timeout_connection.disconnect();
			} else if (nb != 0) {
					nb->timeout_connection.disconnect();
			}
    }

    buttons_down.insert(button->id());
    DEBUG_TRACE(DEBUG::LaunchControlXL, string_compose("button pressed: %1\n", LaunchControlXL::button_name_by_id(button->id())));
    start_press_timeout(button, button->id());
  } else {
    DEBUG_TRACE(DEBUG::LaunchControlXL, string_compose("button depressed: %1\n", LaunchControlXL::button_name_by_id(button->id())));
    buttons_down.erase(button->id());
    button->timeout_connection.disconnect();
    if (button ==  id_note_button_map[Device] && refresh_leds_flag()) {
	    switch_bank (bank_start);
    }
  }

	set<ButtonID>::iterator c = consumed.find(button->id());

  if (c == consumed.end()) {
    if (ev->value == 0) {
      (this->*button->release_method)();
    } else {
      (this->*button->press_method)();
    }
  } else {
    DEBUG_TRACE(DEBUG::LaunchControlXL, "button was consumed, ignored\n");
    consumed.erase(c);
  }
}

bool
LaunchControlXL::check_pick_up(boost::shared_ptr<Controller> controller, boost::shared_ptr<AutomationControl> ac)
{
	/* returns false until the controller value matches with the current setting of the stripable's ac */
	return ( abs( controller->value() / 127.0 -  ac->internal_to_interface(ac->get_value()) ) < 0.007875 );
}

void
LaunchControlXL::handle_knob_message (boost::shared_ptr<Knob> knob)
{
	uint8_t chan = knob->id() % 8; // get the strip channel number
	if (!stripable[chan]) {
		return;
	}

	boost::shared_ptr<AutomationControl> ac;

	if (knob->id() < 8) { // sendA knob
		if (buttons_down.find(Device) != buttons_down.end()) { // Device button hold
			ac = stripable[chan]->trim_control();
		} else {
			ac = stripable[chan]->send_level_controllable (0);
		}
	} else if (knob->id() >= 8 && knob->id() < 16) { // sendB knob
		if (buttons_down.find(Device) != buttons_down.end()) { // Device button hold
#ifdef MIXBUS
			ac = stripable[chan]->filter_freq_controllable (true);
#else
			/* something */
#endif
		} else {
			ac = stripable[chan]->send_level_controllable (1);
		}
	} else if (knob->id() >= 16 && knob->id() < 24) { // pan knob
		if (buttons_down.find(Device) != buttons_down.end()) { // Device button hold
#ifdef MIXBUS
			ac = stripable[chan]->comp_threshold_controllable();
#else
			ac = stripable[chan]->pan_width_control();
#endif
		} else {
			ac = stripable[chan]->pan_azimuth_control();
		}
	}

	if (ac && check_pick_up(knob, ac)) {
		ac->set_value ( ac->interface_to_internal( knob->value() / 127.0), PBD::Controllable::UseGroup );
	}
}

void
LaunchControlXL::handle_fader_message (boost::shared_ptr<Fader> fader)
{

	if (!stripable[fader->id()]) {
		return;
	}

	boost::shared_ptr<AutomationControl> ac = stripable[fader->id()]->gain_control();
	if (ac && check_pick_up(fader, ac)) {
		ac->set_value ( ac->interface_to_internal( fader->value() / 127.0), PBD::Controllable::UseGroup );
	}
}

void
LaunchControlXL::handle_midi_controller_message (MIDI::Parser& parser, MIDI::EventTwoBytes* ev, MIDI::channel_t chan)
{
	_template_number = (int)chan;

	if (template_number() < 8) {
		return; // only treat factory templates
	}
	// DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("CC %1 (value %2)\n", (int) ev->controller_number, (int) ev->value));

	CCControllerButtonMap::iterator b = cc_controller_button_map.find (ev->controller_number);
	CCFaderMap::iterator f = cc_fader_map.find (ev->controller_number);
	CCKnobMap::iterator k = cc_knob_map.find (ev->controller_number);

	if (b != cc_controller_button_map.end()) {
		boost::shared_ptr<Button> button = b->second;
		handle_button_message(button, ev);
	} else if (f != cc_fader_map.end()) {
		boost::shared_ptr<Fader> fader = f->second;
		fader->set_value(ev->value);
		handle_fader_message(fader);

	} else if (k != cc_knob_map.end()) {
		boost::shared_ptr<Knob> knob = k->second;
		knob->set_value(ev->value);
		handle_knob_message(knob);
	}
}

void
LaunchControlXL::handle_midi_note_on_message (MIDI::Parser& parser, MIDI::EventTwoBytes* ev, MIDI::channel_t chan)
{
	_template_number = (int)chan;

	if (template_number() < 8) {
		return; // only treat factory templates
	}

	 //DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("Note On %1 (velocity %2)\n", (int) ev->note_number, (int) ev->velocity));

	 NNNoteButtonMap::iterator b = nn_note_button_map.find (ev->controller_number);

	 if (b != nn_note_button_map.end()) {
		 boost::shared_ptr<Button> button = b->second;
		handle_button_message(button, ev);
	}
}

void LaunchControlXL::handle_midi_note_off_message(MIDI::Parser & parser, MIDI::EventTwoBytes *ev, MIDI::channel_t chan)
{
  //DEBUG_TRACE(DEBUG::LaunchControlXL, string_compose("Note Off %1 (velocity %2)\n",(int)ev->note_number, (int)ev->velocity));
	handle_midi_note_on_message(parser, ev, chan); /* we handle both case in handle_midi_note_on_message */
}

/* Ardour session signals connection */

void
LaunchControlXL::thread_init ()
{
	pthread_set_name (event_loop_name().c_str());

	PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
	ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);

	set_thread_priority ();
}

void
LaunchControlXL::connect_session_signals()
{
	// receive transport state changed
	session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_transport_state_changed, this), this);
	session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_loop_state_changed, this), this);
	// receive punch-in and punch-out
	Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_parameter_changed, this, _1), this);
	session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_parameter_changed, this, _1), this);

	// receive rude solo changed
	//session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_solo_active_changed, this, _1), this);
	// receive record state toggled
	//session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_record_state_changed, this), this);

}


void
LaunchControlXL::notify_transport_state_changed ()
{ /*
	Button* b = id_button_map[Play];

	if (session->transport_rolling()) {
		b->set_state (LED::OneShot24th);
		b->set_color (LED::GreenFull);
	} else {

		 disable any blink on FixedLength from pending edit range op
		Button* fl = id_button_map[FixedLength];

		fl->set_color (LED::Black);
		fl->set_state (LED::NoTransition);
		write (fl->state_msg());

		b->set_color (LED::White);
		b->set_state (LED::NoTransition);
	}

	write (b->state_msg()); */
}

void
LaunchControlXL::notify_loop_state_changed ()
{
}

void
LaunchControlXL::notify_parameter_changed (std::string param)
{ /*
	IDButtonMap::iterator b;

	if (param == "clicking") {
		if ((b = id_button_map.find (Metronome)) == id_button_map.end()) {
			return;
		}
		if (Config->get_clicking()) {
			b->second->set_state (LED::Blinking4th);
			b->second->set_color (LED::White);
		} else {
			b->second->set_color (LED::White);
			b->second->set_state (LED::NoTransition);
		}
		write (b->second->state_msg ()) ;
	} */
}

/* connection handling */

XMLNode&
LaunchControlXL::get_state()
{
	XMLNode& node (ControlProtocol::get_state());
	XMLNode* child;

	child = new XMLNode (X_("Input"));
	child->add_child_nocopy (_async_in->get_state());
	node.add_child_nocopy (*child);
	child = new XMLNode (X_("Output"));
	child->add_child_nocopy (_async_out->get_state());
	node.add_child_nocopy (*child);

	child = new XMLNode (X_("Configuration"));
	child->set_property ("fader8master", fader8master());
	node.add_child_nocopy (*child);

	return node;
}

int
LaunchControlXL::set_state (const XMLNode & node, int version)
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("LaunchControlXL::set_state: active %1\n", active()));

	int retval = 0;

	if (ControlProtocol::set_state (node, version)) {
		return -1;
	}

	XMLNode* child;

	if ((child = node.child (X_("Input"))) != 0) {
		XMLNode* portnode = child->child (Port::state_node_name.c_str());
		if (portnode) {
			_async_in->set_state (*portnode, version);
		}
	}

	if ((child = node.child (X_("Output"))) != 0) {
		XMLNode* portnode = child->child (Port::state_node_name.c_str());
		if (portnode) {
			_async_out->set_state (*portnode, version);
		}
	}

	if ((child = node.child (X_("Configuration"))) !=0) {
		/* this should propably become a for-loop at some point */
		child->get_property ("fader8master", _fader8master);
	}

	return retval;
}

void
LaunchControlXL::port_registration_handler ()
{
	if (!_async_in || !_async_out) {
		/* ports not registered yet */
		return;
	}

	if (_async_in->connected() && _async_out->connected()) {
		/* don't waste cycles here */
		return;
	}

#ifdef __APPLE__
	/* the origin of the numeric magic identifiers is known only to Ableton
	   and may change in time. This is part of how CoreMIDI works.
	*/
	string input_port_name = X_("system:midi_capture_1319078870");
	string output_port_name = X_("system:midi_playback_3409210341");
#else
	string input_port_name = X_("Novation Launch Control XL MIDI 1 in");
	string output_port_name = X_("Novation Launch Control XL MIDI 1 out");
#endif
	vector<string> in;
	vector<string> out;

	AudioEngine::instance()->get_ports (string_compose (".*%1", input_port_name), DataType::MIDI, PortFlags (IsPhysical|IsOutput), in);
	AudioEngine::instance()->get_ports (string_compose (".*%1", output_port_name), DataType::MIDI, PortFlags (IsPhysical|IsInput), out);

	if (!in.empty() && !out.empty()) {
		cerr << "LaunchControlXL: both ports found\n";
		cerr << "\tconnecting to " << in.front() <<  " + " << out.front() << endl;
		if (!_async_in->connected()) {
			AudioEngine::instance()->connect (_async_in->name(), in.front());
		}
		if (!_async_out->connected()) {
			AudioEngine::instance()->connect (_async_out->name(), out.front());
		}
	}
}

bool
LaunchControlXL::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, "LaunchControlXL::connection_handler start\n");
	if (!_input_port || !_output_port) {
		return false;
	}

	string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_async_in)->name());
	string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_async_out)->name());

	if (ni == name1 || ni == name2) {
		if (yn) {
			connection_state |= InputConnected;
		} else {
			connection_state &= ~InputConnected;
		}
	} else if (no == name1 || no == name2) {
		if (yn) {
			connection_state |= OutputConnected;
		} else {
			connection_state &= ~OutputConnected;
		}
	} else {
		DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("Connections between %1 and %2 changed, but I ignored it\n", name1, name2));
		// not our ports
		return false;
	}

	DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("our ports changed connection state: %1 -> %2 connected ? %3\n",
	                                           name1, name2, yn));

	if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {

		/* XXX this is a horrible hack. Without a short sleep here,
		   something prevents the device wakeup messages from being
		   sent and/or the responses from being received.
		*/

		g_usleep (100000);
                DEBUG_TRACE (DEBUG::LaunchControlXL, "device now connected for both input and output\n");

                begin_using_device ();

	} else {
		DEBUG_TRACE (DEBUG::LaunchControlXL, "Device disconnected (input or output or both) or not yet fully connected\n");
		stop_using_device ();
	}

	ConnectionChange (); /* emit signal for our GUI */

	DEBUG_TRACE (DEBUG::LaunchControlXL, "LaunchControlXL::connection_handler  end\n");

	return true; /* connection status changed */
}


boost::shared_ptr<Port>
LaunchControlXL::output_port()
{
	return _async_out;
}

boost::shared_ptr<Port>
LaunchControlXL::input_port()
{
	return _async_in;
}

/* Stripables handling */

void
LaunchControlXL::stripable_selection_changed () // we don't need it but it's needs to be declared...
{
}


void
LaunchControlXL::stripable_property_change (PropertyChange const& what_changed, uint32_t which)
{

	if (what_changed.contains (Properties::hidden)) {
		switch_bank (bank_start);
	}

	if (what_changed.contains (Properties::selected)) {

		if (!stripable[which]) {
			return;
		}
		if (which < 8) {
			update_track_focus_led ((uint8_t) which);
			update_knob_led((uint8_t) which);
		}
	}
}

void
LaunchControlXL::switch_template (uint8_t t)
{
	MidiByteArray msg (9, 0xf0, 0x00, 0x20, 0x29, 0x02, 0x11, 0x77, t, 0xf7);
	write (msg);
}

void
LaunchControlXL::switch_bank (uint32_t base)
{
	boost::shared_ptr<SelectButton> sl = boost::dynamic_pointer_cast<SelectButton>(id_controller_button_map[SelectLeft]);
	boost::shared_ptr<SelectButton> sr = boost::dynamic_pointer_cast<SelectButton>(id_controller_button_map[SelectRight]);

	/* work backwards so we can tell if we should actually switch banks */

	boost::shared_ptr<Stripable> s[8];
	uint32_t different = 0;


	int stripable_counter = get_amount_of_tracks();

	for (int n = 0; n < stripable_counter; ++n) {
		s[n] = session->get_remote_nth_stripable (base+n, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
		if (s[n] != stripable[n]) {
			different++;
		}
	}

	if (!s[0]) {
		/* not even the first stripable exists, do nothing */
		return;
	}

	if (sl && sr) {
		boost::shared_ptr<Stripable> next_base = session->get_remote_nth_stripable (base+8, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
		write(sl->state_msg((base)));
		write(sr->state_msg((next_base != 0)));
	}

	stripable_connections.drop_connections ();

	for (int n = 0; n < stripable_counter; ++n) {
		stripable[n] = s[n];
	}

	/* at least one stripable in this bank */

	bank_start = base;

	for (int n = 0; n < 8; ++n) {

		if (stripable[n]) {
			/* stripable goes away? refill the bank, starting at the same point */

			stripable[n]->DropReferences.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::switch_bank, this, bank_start), lcxl);
			stripable[n]->presentation_info().PropertyChanged.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::stripable_property_change, this, _1, n), lcxl);
			stripable[n]->solo_control()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::solo_changed, this, n), lcxl);
			stripable[n]->mute_control()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::mute_changed, this, n), lcxl);
			if (stripable[n]->solo_isolate_control()) {	/*VCAs are stripables without isolate solo */
				stripable[n]->solo_isolate_control()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::solo_iso_changed, this,n ), lcxl);
			}
#ifdef MIXBUS
			if (stripable[n]->master_send_enable_controllable()) {
				stripable[n]->master_send_enable_controllable()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::master_send_changed, this,n ), lcxl);
			}
#endif
			if (stripable[n]->rec_enable_control()) {
				stripable[n]->rec_enable_control()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::rec_changed, this, n), lcxl);
			}
		}
		update_track_focus_led(n);
		button_track_mode(track_mode());
		update_knob_led(n);
	}
}

void
LaunchControlXL::stripables_added ()
{
	DEBUG_TRACE (DEBUG::LaunchControlXL, "LaunchControlXL::new stripable added!\n");
	/* reload current bank */
	switch_bank (bank_start);
}


void LaunchControlXL::set_track_mode (TrackMode mode) {
	_track_mode = mode;

	// now do led stuffs to signify the change
	switch(mode) {
		case TrackMute:

			break;
		case TrackSolo:

			break;
		case TrackRecord:

			break;
	default:
		break;
	}
}

void
LaunchControlXL::set_fader8master (bool yn)
{
	_fader8master = yn;
	if (_fader8master) {
		stripable[7] = master;
		bank_start -= 1;  
	} else {
		bank_start += 1;
	}

	switch_bank (bank_start);
}

int
LaunchControlXL::get_amount_of_tracks ()
{
	int no_of_tracks;
	if (fader8master ()) {
		no_of_tracks = 7;
        } else {
                no_of_tracks = 8;
	}

	return no_of_tracks;
}

void
LaunchControlXL::set_refresh_leds_flag (bool yn)
{
	_refresh_leds_flag = yn;
}