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