Correct formatting for if/else statements
[ardour.git] / libs / surfaces / launch_control_xl / launch_control_xl.cc
1 /*
2   Copyright (C) 2016 Paul Davis
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12   GNU General Public License for more details.
13
14   You should have received a copy of the GNU General Public License
15   along with this program; if not, write to the Free Software
16   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include <stdlib.h>
20 #include <pthread.h>
21
22 #include "pbd/compose.h"
23 #include "pbd/convert.h"
24 #include "pbd/debug.h"
25 #include "pbd/failed_constructor.h"
26 #include "pbd/file_utils.h"
27 #include "pbd/search_path.h"
28 #include "pbd/enumwriter.h"
29
30 #include "midi++/parser.h"
31
32 #include "temporal/time.h"
33 #include "temporal/bbt_time.h"
34
35 #include "ardour/amp.h"
36 #include "ardour/async_midi_port.h"
37 #include "ardour/audioengine.h"
38 #include "ardour/debug.h"
39 #include "ardour/midiport_manager.h"
40 #include "ardour/midi_track.h"
41 #include "ardour/midi_port.h"
42 #include "ardour/session.h"
43 #include "ardour/tempo.h"
44 #include "ardour/types_convert.h"
45 #include "ardour/vca_manager.h"
46
47
48 #include "gtkmm2ext/gui_thread.h"
49
50 #include "gui.h"
51 #include "launch_control_xl.h"
52
53 #include "pbd/i18n.h"
54
55 #ifdef PLATFORM_WINDOWS
56 #define random() rand()
57 #endif
58
59 using namespace ARDOUR;
60 using namespace std;
61 using namespace PBD;
62 using namespace Glib;
63 using namespace ArdourSurface;
64 #include "pbd/abstract_ui.cc" // instantiate template
65
66 /* init global object */
67 LaunchControlXL* lcxl = 0;
68
69 LaunchControlXL::LaunchControlXL (ARDOUR::Session& s)
70         : ControlProtocol (s, string (X_("Novation Launch Control XL")))
71         , AbstractUI<LaunchControlRequest> (name())
72         , in_use (false)
73         , _track_mode(TrackMute)
74         , _template_number(8) // default template (factory 1)
75         , bank_start (0)
76         , connection_state (ConnectionState (0))
77         , gui (0)
78         , in_range_select (false)
79 {
80         lcxl = this;
81         /* we're going to need this */
82
83         build_maps ();
84
85         /* master cannot be removed, so no need to connect to going-away signal */
86         master = session->master_out ();
87         /* the master bus will always be on the last channel on the lcxl */
88         stripable[7] = master;
89
90
91         run_event_loop ();
92
93         /* Ports exist for the life of this instance */
94
95         ports_acquire ();
96
97         /* catch arrival and departure of LaunchControlXL itself */
98         ARDOUR::AudioEngine::instance()->PortRegisteredOrUnregistered.connect (port_reg_connection, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::port_registration_handler, this), this);
99
100         /* Catch port connections and disconnections */
101         ARDOUR::AudioEngine::instance()->PortConnectedOrDisconnected.connect (port_connection, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::connection_handler, this, _1, _2, _3, _4, _5), this);
102
103         /* Launch Control XL ports might already be there */
104         port_registration_handler ();
105
106         session->RouteAdded.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::stripables_added, this), lcxl);
107         session->vca_manager().VCAAdded.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::stripables_added, this), lcxl);
108
109         switch_bank (bank_start);
110 }
111
112 LaunchControlXL::~LaunchControlXL ()
113 {
114         DEBUG_TRACE (DEBUG::LaunchControlXL, "Launch Control XL  control surface object being destroyed\n");
115
116         /* do this before stopping the event loop, so that we don't get any notifications */
117         port_reg_connection.disconnect ();
118         port_connection.disconnect ();
119         session_connections.drop_connections ();
120         stripable_connections.drop_connections ();
121
122         stop_using_device ();
123         ports_release ();
124
125         stop_event_loop ();
126 }
127
128
129 void
130 LaunchControlXL::run_event_loop ()
131 {
132         DEBUG_TRACE (DEBUG::LaunchControlXL, "start event loop\n");
133         BaseUI::run ();
134 }
135
136 void
137 LaunchControlXL::stop_event_loop ()
138 {
139         DEBUG_TRACE (DEBUG::LaunchControlXL, "stop event loop\n");
140         BaseUI::quit ();
141 }
142
143 int
144 LaunchControlXL::begin_using_device ()
145 {
146         DEBUG_TRACE (DEBUG::LaunchControlXL, "begin using device\n");
147
148         switch_template(template_number()); // first factory template
149
150         connect_session_signals ();
151
152
153         init_buttons (true);
154
155         in_use = true;
156
157         return 0;
158 }
159
160 int
161 LaunchControlXL::stop_using_device ()
162 {
163         DEBUG_TRACE (DEBUG::LaunchControlXL, "stop using device\n");
164
165         if (!in_use) {
166                 DEBUG_TRACE (DEBUG::LaunchControlXL, "nothing to do, device not in use\n");
167                 return 0;
168         }
169
170         init_buttons (false);
171
172         session_connections.drop_connections ();
173
174         in_use = false;
175         return 0;
176 }
177
178 int
179 LaunchControlXL::ports_acquire ()
180 {
181         DEBUG_TRACE (DEBUG::LaunchControlXL, "acquiring ports\n");
182
183         /* setup ports */
184
185         _async_in  = AudioEngine::instance()->register_input_port (DataType::MIDI, X_("Launch Control XL in"), true);
186         _async_out = AudioEngine::instance()->register_output_port (DataType::MIDI, X_("Launch Control XL out"), true);
187
188         if (_async_in == 0 || _async_out == 0) {
189                 DEBUG_TRACE (DEBUG::LaunchControlXL, "cannot register ports\n");
190                 return -1;
191         }
192
193         /* We do not add our ports to the input/output bundles because we don't
194          * want users wiring them by hand. They could use JACK tools if they
195          * really insist on that (and use JACK)
196          */
197
198         _input_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_in).get();
199         _output_port = boost::dynamic_pointer_cast<AsyncMIDIPort>(_async_out).get();
200
201         session->BundleAddedOrRemoved ();
202
203         connect_to_parser ();
204
205         /* Connect input port to event loop */
206
207         AsyncMIDIPort* asp;
208
209         asp = static_cast<AsyncMIDIPort*> (_input_port);
210         asp->xthread().set_receive_handler (sigc::bind (sigc::mem_fun (this, &LaunchControlXL::midi_input_handler), _input_port));
211         asp->xthread().attach (main_loop()->get_context());
212
213         return 0;
214 }
215
216 void
217 LaunchControlXL::ports_release ()
218 {
219         DEBUG_TRACE (DEBUG::LaunchControlXL, "releasing ports\n");
220
221         /* wait for button data to be flushed */
222         AsyncMIDIPort* asp;
223         asp = static_cast<AsyncMIDIPort*> (_output_port);
224         asp->drain (10000, 500000);
225
226         {
227                 Glib::Threads::Mutex::Lock em (AudioEngine::instance()->process_lock());
228                 AudioEngine::instance()->unregister_port (_async_in);
229                 AudioEngine::instance()->unregister_port (_async_out);
230         }
231
232         _async_in.reset ((ARDOUR::Port*) 0);
233         _async_out.reset ((ARDOUR::Port*) 0);
234         _input_port = 0;
235         _output_port = 0;
236 }
237
238 list<boost::shared_ptr<ARDOUR::Bundle> >
239 LaunchControlXL::bundles ()
240 {
241         list<boost::shared_ptr<ARDOUR::Bundle> > b;
242
243         if (_output_bundle) {
244                 b.push_back (_output_bundle);
245         }
246
247         return b;
248 }
249
250
251 void
252 LaunchControlXL::init_buttons (bool startup)
253 {
254         if (startup) {
255                 button_track_mode(track_mode());
256         }
257 }
258
259 bool
260 LaunchControlXL::probe ()
261 {
262         return true;
263 }
264
265 void*
266 LaunchControlXL::request_factory (uint32_t num_requests)
267 {
268         /* AbstractUI<T>::request_buffer_factory() is a template method only
269            instantiated in this source module. To provide something visible for
270            use in the interface/descriptor, we have this static method that is
271            template-free.
272         */
273         return request_buffer_factory (num_requests);
274 }
275
276 void
277 LaunchControlXL::do_request (LaunchControlRequest * req)
278 {
279         if (req->type == CallSlot) {
280
281                 call_slot (MISSING_INVALIDATOR, req->the_slot);
282
283         } else if (req->type == Quit) {
284
285                 stop_using_device ();
286         }
287 }
288
289 int
290 LaunchControlXL::set_active (bool yn)
291 {
292         DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose("LaunchControlProtocol::set_active init with yn: '%1'\n", yn));
293
294         if (yn == active()) {
295                 return 0;
296         }
297
298         if (yn) {
299                 if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
300                         begin_using_device ();
301                 } else {
302                         /* begin_using_device () will get called once we're connected */
303                 }
304
305         } else {
306                 /* Control Protocol Manager never calls us with false, but
307                  * insteads destroys us.
308                  */
309         }
310
311         ControlProtocol::set_active (yn);
312
313         DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose("LaunchControlProtocol::set_active done with yn: '%1'\n", yn));
314
315         return 0;
316 }
317
318 void
319 LaunchControlXL::write (const MidiByteArray& data)
320 {
321         /* immediate delivery */
322         _output_port->write (&data[0], data.size(), 0);
323 }
324
325 /* Device to Ardour message handling */
326
327 bool
328 LaunchControlXL::midi_input_handler (IOCondition ioc, MIDI::Port* port)
329 {
330         if (ioc & ~IO_IN) {
331                 DEBUG_TRACE (DEBUG::LaunchControlXL, "MIDI port closed\n");
332                 return false;
333         }
334
335         if (ioc & IO_IN) {
336
337                 DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("something happened on  %1\n", port->name()));
338
339                 AsyncMIDIPort* asp = static_cast<AsyncMIDIPort*>(port);
340                 if (asp) {
341                         asp->clear ();
342                 }
343
344                 DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("data available on %1\n", port->name()));
345                 if (in_use) {
346                         samplepos_t now = AudioEngine::instance()->sample_time();
347                         port->parse (now);
348                 }
349         }
350
351         return true;
352 }
353
354
355 void
356 LaunchControlXL::connect_to_parser ()
357 {
358         DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("Connecting to signals on port %1\n", _input_port->name()));
359
360         MIDI::Parser* p = _input_port->parser();
361
362         /* Incoming sysex */
363         p->sysex.connect_same_thread (*this, boost::bind (&LaunchControlXL::handle_midi_sysex, this, _1, _2, _3));
364
365  for (MIDI::channel_t n = 0; n < 16; ++n) {
366         /* Controller */
367                 p->channel_controller[(int)n].connect_same_thread (*this, boost::bind (&LaunchControlXL::handle_midi_controller_message, this, _1, _2, n));
368                 /* Button messages are NoteOn */
369                 p->channel_note_on[(int)n].connect_same_thread (*this, boost::bind (&LaunchControlXL::handle_midi_note_on_message, this, _1, _2, n));
370                 /* Button messages are NoteOn but libmidi++ sends note-on w/velocity = 0 as note-off so catch them too */
371                 p->channel_note_off[(int)n].connect_same_thread (*this, boost::bind (&LaunchControlXL::handle_midi_note_off_message, this, _1, _2, n));
372         }
373 }
374
375 void
376 LaunchControlXL::handle_midi_sysex (MIDI::Parser&, MIDI::byte* raw_bytes, size_t sz)
377 {
378         DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("Sysex, %1 bytes\n", sz));
379
380         if (sz < 8) {
381                 return;
382         }
383
384         MidiByteArray msg (sz, raw_bytes);
385         MidiByteArray lcxl_sysex_header (6, 0xF0, 0x00, 0x20, 0x29, 0x02, 0x11);
386
387         if (!lcxl_sysex_header.compare_n (msg, 6)) {
388                 return;
389         }
390
391
392         switch (msg[6]) {
393         case 0x77: /* template change */
394                 DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("Template change: %1 n", msg[7]));
395                 _template_number = msg[7];
396                 break;
397         }
398 }
399
400
401 void
402 LaunchControlXL::handle_button_message(Button* button, MIDI::EventTwoBytes* ev)
403 {
404   if (ev->value) {
405     /* any press cancels any pending long press timeouts */
406     for (set<ButtonID>::iterator x = buttons_down.begin(); x != buttons_down.end(); ++x) {
407       ControllerButton* cb = id_controller_button_map[*x];
408                         NoteButton*     nb = id_note_button_map[*x];
409                         if (cb != 0) {
410                                 cb->timeout_connection.disconnect();
411                         } else if (nb != 0) {
412                                         nb->timeout_connection.disconnect();
413                         }
414     }
415
416     buttons_down.insert(button->id());
417     DEBUG_TRACE(DEBUG::LaunchControlXL, string_compose("button pressed: %1\n", LaunchControlXL::button_name_by_id(button->id())));
418     start_press_timeout(button, button->id());
419   } else {
420     DEBUG_TRACE(DEBUG::LaunchControlXL, string_compose("button depressed: %1\n", LaunchControlXL::button_name_by_id(button->id())));
421     buttons_down.erase(button->id());
422     button->timeout_connection.disconnect();
423   }
424
425         set<ButtonID>::iterator c = consumed.find(button->id());
426
427   if (c == consumed.end()) {
428     if (ev->value == 0) {
429       (this->*button->release_method)();
430     } else {
431       (this->*button->press_method)();
432     }
433   } else {
434     DEBUG_TRACE(DEBUG::LaunchControlXL, "button was consumed, ignored\n");
435     consumed.erase(c);
436   }
437 }
438
439 void
440 LaunchControlXL::handle_knob_message (Knob* knob)
441 {
442         uint8_t chan = knob->id() % 8; // get the strip channel number
443         if (!stripable[chan]) {
444                 return;
445         }
446
447         boost::shared_ptr<AutomationControl> ac;
448
449         if (knob->id() < 8) { // sendA
450                 ac = stripable[chan]->trim_control();
451         } else if (knob->id() >= 8 && knob->id() < 16) { // sendB
452                 ac = stripable[chan]->pan_width_control();
453         } else if (knob->id() >= 16 && knob->id() < 24) { // pan
454                 ac = stripable[chan]->pan_azimuth_control();
455         }
456
457         if (ac) {
458                 ac->set_value ( ac->interface_to_internal( knob->value() / 127.0), PBD::Controllable::UseGroup );
459         }
460 }
461
462 void
463 LaunchControlXL::handle_fader_message (Fader* fader)
464 {
465
466         if (!stripable[fader->id()]) {
467                 return;
468         }
469
470         boost::shared_ptr<AutomationControl> ac = stripable[fader->id()]->gain_control();
471         if (ac) {
472                 ac->set_value ( ac->interface_to_internal( fader->value() / 127.0), PBD::Controllable::UseGroup );
473         }
474 }
475
476 void
477 LaunchControlXL::handle_midi_controller_message (MIDI::Parser& parser, MIDI::EventTwoBytes* ev, MIDI::channel_t chan)
478 {
479         _template_number = (int)chan;
480
481         if (template_number() < 8) {
482                 return; // only treat factory templates
483         }
484         // DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("CC %1 (value %2)\n", (int) ev->controller_number, (int) ev->value));
485
486         CCControllerButtonMap::iterator b = cc_controller_button_map.find (ev->controller_number);
487         CCFaderMap::iterator f = cc_fader_map.find (ev->controller_number);
488         CCKnobMap::iterator k = cc_knob_map.find (ev->controller_number);
489
490         if (b != cc_controller_button_map.end()) {
491                 Button* button = b->second;
492                 handle_button_message(button, ev);
493         } else if (f != cc_fader_map.end()) {
494                 Fader* fader = f->second;
495                 fader->set_value(ev->value);
496                 handle_fader_message(fader);
497
498         } else if (k != cc_knob_map.end()) {
499                 Knob* knob = k->second;
500                 knob->set_value(ev->value);
501                 handle_knob_message(knob);
502         }
503 }
504
505 void
506 LaunchControlXL::handle_midi_note_on_message (MIDI::Parser& parser, MIDI::EventTwoBytes* ev, MIDI::channel_t chan)
507 {
508         _template_number = (int)chan;
509
510         if (template_number() < 8) {
511                 return; // only treat factory templates
512         }
513
514          //DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("Note On %1 (velocity %2)\n", (int) ev->note_number, (int) ev->velocity));
515
516          NNNoteButtonMap::iterator b = nn_note_button_map.find (ev->controller_number);
517
518          if (b != nn_note_button_map.end()) {
519                 Button* button = b->second;
520                 handle_button_message(button, ev);
521         }
522 }
523
524 void LaunchControlXL::handle_midi_note_off_message(MIDI::Parser & parser, MIDI::EventTwoBytes *ev, MIDI::channel_t chan)
525 {
526   //DEBUG_TRACE(DEBUG::LaunchControlXL, string_compose("Note Off %1 (velocity %2)\n",(int)ev->note_number, (int)ev->velocity));
527         handle_midi_note_on_message(parser, ev, chan); /* we handle both case in handle_midi_note_on_message */
528 }
529
530 /* Ardour session signals connection */
531
532 void
533 LaunchControlXL::thread_init ()
534 {
535         pthread_set_name (event_loop_name().c_str());
536
537         PBD::notify_event_loops_about_thread_creation (pthread_self(), event_loop_name(), 2048);
538         ARDOUR::SessionEvent::create_per_thread_pool (event_loop_name(), 128);
539
540         set_thread_priority ();
541 }
542
543 void
544 LaunchControlXL::connect_session_signals()
545 {
546         // receive transport state changed
547         session->TransportStateChange.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_transport_state_changed, this), this);
548         session->TransportLooped.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_loop_state_changed, this), this);
549         // receive punch-in and punch-out
550         Config->ParameterChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_parameter_changed, this, _1), this);
551         session->config.ParameterChanged.connect (session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_parameter_changed, this, _1), this);
552
553         // receive rude solo changed
554         //session->SoloActive.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_solo_active_changed, this, _1), this);
555         // receive record state toggled
556         //session->RecordStateChanged.connect(session_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::notify_record_state_changed, this), this);
557
558 }
559
560
561 void
562 LaunchControlXL::notify_transport_state_changed ()
563 { /*
564         Button* b = id_button_map[Play];
565
566         if (session->transport_rolling()) {
567                 b->set_state (LED::OneShot24th);
568                 b->set_color (LED::GreenFull);
569         } else {
570
571                  disable any blink on FixedLength from pending edit range op
572                 Button* fl = id_button_map[FixedLength];
573
574                 fl->set_color (LED::Black);
575                 fl->set_state (LED::NoTransition);
576                 write (fl->state_msg());
577
578                 b->set_color (LED::White);
579                 b->set_state (LED::NoTransition);
580         }
581
582         write (b->state_msg()); */
583 }
584
585 void
586 LaunchControlXL::notify_loop_state_changed ()
587 {
588 }
589
590 void
591 LaunchControlXL::notify_parameter_changed (std::string param)
592 { /*
593         IDButtonMap::iterator b;
594
595         if (param == "clicking") {
596                 if ((b = id_button_map.find (Metronome)) == id_button_map.end()) {
597                         return;
598                 }
599                 if (Config->get_clicking()) {
600                         b->second->set_state (LED::Blinking4th);
601                         b->second->set_color (LED::White);
602                 } else {
603                         b->second->set_color (LED::White);
604                         b->second->set_state (LED::NoTransition);
605                 }
606                 write (b->second->state_msg ()) ;
607         } */
608 }
609
610 /* connection handling */
611
612 XMLNode&
613 LaunchControlXL::get_state()
614 {
615         XMLNode& node (ControlProtocol::get_state());
616         XMLNode* child;
617
618         child = new XMLNode (X_("Input"));
619         child->add_child_nocopy (_async_in->get_state());
620         node.add_child_nocopy (*child);
621         child = new XMLNode (X_("Output"));
622         child->add_child_nocopy (_async_out->get_state());
623         node.add_child_nocopy (*child);
624
625         return node;
626 }
627
628 int
629 LaunchControlXL::set_state (const XMLNode & node, int version)
630 {
631         DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("LaunchControlXL::set_state: active %1\n", active()));
632
633         int retval = 0;
634
635         if (ControlProtocol::set_state (node, version)) {
636                 return -1;
637         }
638
639         XMLNode* child;
640
641         if ((child = node.child (X_("Input"))) != 0) {
642                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
643                 if (portnode) {
644                         _async_in->set_state (*portnode, version);
645                 }
646         }
647
648         if ((child = node.child (X_("Output"))) != 0) {
649                 XMLNode* portnode = child->child (Port::state_node_name.c_str());
650                 if (portnode) {
651                         _async_out->set_state (*portnode, version);
652                 }
653         }
654
655         return retval;
656 }
657
658 void
659 LaunchControlXL::port_registration_handler ()
660 {
661         if (!_async_in && !_async_out) {
662                 /* ports not registered yet */
663                 return;
664         }
665
666         if (_async_in->connected() && _async_out->connected()) {
667                 /* don't waste cycles here */
668                 return;
669         }
670
671 #ifdef __APPLE__
672         /* the origin of the numeric magic identifiers is known only to Ableton
673            and may change in time. This is part of how CoreMIDI works.
674         */
675         string input_port_name = X_("system:midi_capture_1319078870");
676         string output_port_name = X_("system:midi_playback_3409210341");
677 #else
678         string input_port_name = X_("Novation Launch Control XL MIDI 1 in");
679         string output_port_name = X_("Novation Launch Control XL MIDI 1 out");
680 #endif
681         vector<string> in;
682         vector<string> out;
683
684         AudioEngine::instance()->get_ports (string_compose (".*%1", input_port_name), DataType::MIDI, PortFlags (IsPhysical|IsOutput), in);
685         AudioEngine::instance()->get_ports (string_compose (".*%1", output_port_name), DataType::MIDI, PortFlags (IsPhysical|IsInput), out);
686
687         if (!in.empty() && !out.empty()) {
688                 cerr << "LaunchControlXL: both ports found\n";
689                 cerr << "\tconnecting to " << in.front() <<  " + " << out.front() << endl;
690                 if (!_async_in->connected()) {
691                         AudioEngine::instance()->connect (_async_in->name(), in.front());
692                 }
693                 if (!_async_out->connected()) {
694                         AudioEngine::instance()->connect (_async_out->name(), out.front());
695                 }
696         }
697 }
698
699 bool
700 LaunchControlXL::connection_handler (boost::weak_ptr<ARDOUR::Port>, std::string name1, boost::weak_ptr<ARDOUR::Port>, std::string name2, bool yn)
701 {
702         DEBUG_TRACE (DEBUG::LaunchControlXL, "LaunchControlXL::connection_handler start\n");
703         if (!_input_port || !_output_port) {
704                 return false;
705         }
706
707         string ni = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_async_in)->name());
708         string no = ARDOUR::AudioEngine::instance()->make_port_name_non_relative (boost::shared_ptr<ARDOUR::Port>(_async_out)->name());
709
710         if (ni == name1 || ni == name2) {
711                 if (yn) {
712                         connection_state |= InputConnected;
713                 } else {
714                         connection_state &= ~InputConnected;
715                 }
716         } else if (no == name1 || no == name2) {
717                 if (yn) {
718                         connection_state |= OutputConnected;
719                 } else {
720                         connection_state &= ~OutputConnected;
721                 }
722         } else {
723                 DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("Connections between %1 and %2 changed, but I ignored it\n", name1, name2));
724                 // not our ports
725                 return false;
726         }
727
728         DEBUG_TRACE (DEBUG::LaunchControlXL, string_compose ("our ports changed connection state: %1 -> %2 connected ? %3\n",
729                                                    name1, name2, yn));
730
731         if ((connection_state & (InputConnected|OutputConnected)) == (InputConnected|OutputConnected)) {
732
733                 /* XXX this is a horrible hack. Without a short sleep here,
734                    something prevents the device wakeup messages from being
735                    sent and/or the responses from being received.
736                 */
737
738                 g_usleep (100000);
739                 DEBUG_TRACE (DEBUG::LaunchControlXL, "device now connected for both input and output\n");
740
741                 begin_using_device ();
742
743         } else {
744                 DEBUG_TRACE (DEBUG::LaunchControlXL, "Device disconnected (input or output or both) or not yet fully connected\n");
745                 stop_using_device ();
746         }
747
748         ConnectionChange (); /* emit signal for our GUI */
749
750         DEBUG_TRACE (DEBUG::LaunchControlXL, "LaunchControlXL::connection_handler  end\n");
751
752         return true; /* connection status changed */
753 }
754
755
756 boost::shared_ptr<Port>
757 LaunchControlXL::output_port()
758 {
759         return _async_out;
760 }
761
762 boost::shared_ptr<Port>
763 LaunchControlXL::input_port()
764 {
765         return _async_in;
766 }
767
768 /* Stripables handling */
769
770 void
771 LaunchControlXL::stripable_selection_changed () // we don't need it but it's needs to be declared...
772 {
773 }
774
775
776 void
777 LaunchControlXL::stripable_property_change (PropertyChange const& what_changed, uint32_t which)
778 {
779
780         if (what_changed.contains (Properties::hidden)) {
781                 switch_bank (bank_start);
782         }
783
784         if (what_changed.contains (Properties::selected)) {
785
786                 if (!stripable[which]) {
787                         return;
788                 }
789                 if (which < 8) {
790                         button_track_focus( (uint8_t)which );
791                 }
792         }
793
794 }
795
796 void
797 LaunchControlXL::switch_template (uint8_t t)
798 {
799         MidiByteArray msg (9, 0xf0, 0x00, 0x20, 0x29, 0x02, 0x11, 0x77, t, 0xf7);
800         write (msg);
801 }
802
803 void
804 LaunchControlXL::switch_bank (uint32_t base)
805 {
806         SelectButton* sl = static_cast<SelectButton*>(id_controller_button_map[SelectLeft]);
807         SelectButton* sr = static_cast<SelectButton*>(id_controller_button_map[SelectRight]);
808
809         if (sl && sr) {
810                 write(sl->state_msg( (base) ));
811                 write(sr->state_msg( !(base) ));
812         }
813
814
815
816         stripable_connections.drop_connections ();
817
818         /* work backwards so we can tell if we should actually switch banks */
819
820         boost::shared_ptr<Stripable> s[8];
821         uint32_t different = 0;
822
823         for (int n = 0; n < 7; ++n) {
824                 s[n] = session->get_remote_nth_stripable (base+n, PresentationInfo::Flag (PresentationInfo::Route|PresentationInfo::VCA));
825                 if (s[n] != stripable[n]) {
826                         different++;
827                 }
828         }
829
830         if (!s[0]) {
831                 /* not even the first stripable exists, do nothing */
832                 for (int n = 0; n < 7; ++n) {
833                         stripable[n].reset ();
834                 }
835                 return;
836         }
837
838         for (int n = 0; n < 7; ++n) {
839                 stripable[n] = s[n];
840         }
841
842         /* at least one stripable in this bank */
843
844         bank_start = base;
845
846         for (int n = 0; n < 8; ++n) {
847
848                 if (stripable[n]) {
849                         /* stripable goes away? refill the bank, starting at the same point */
850
851                         stripable[n]->DropReferences.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::switch_bank, this, bank_start), lcxl);
852                         stripable[n]->presentation_info().PropertyChanged.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::stripable_property_change, this, _1, n), lcxl);
853                         stripable[n]->solo_control()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::solo_changed, this, n), lcxl);
854                         stripable[n]->mute_control()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::mute_changed, this, n), lcxl);
855                         if (stripable[n]->rec_enable_control()) {
856                                 stripable[n]->rec_enable_control()->Changed.connect (stripable_connections, MISSING_INVALIDATOR, boost::bind (&LaunchControlXL::rec_changed, this, n), lcxl);
857                         }
858
859
860                         button_track_focus(n);
861                         update_track_control_led(n);
862                 }
863         }
864 }
865
866 void
867 LaunchControlXL::stripables_added ()
868 {
869         DEBUG_TRACE (DEBUG::LaunchControlXL, "LaunchControlXL::new stripable added!\n");
870         /* reload current bank */
871         switch_bank (bank_start);
872 }
873
874
875 void LaunchControlXL::set_track_mode (TrackMode mode) {
876         _track_mode = mode;
877
878         // now do led stuffs to signify the change
879         switch(mode) {
880                 case TrackMute:
881
882                         break;
883                 case TrackSolo:
884
885                         break;
886                 case TrackRecord:
887
888                         break;
889         default:
890                 break;
891         }
892 }